program to print sum of numbers from 1 to n using for loop ?


Q.) W.A.P to print sum of numbers from 1 to n using for loop ?
 #include<stdio.h>
 #include<conio.h>
 int main()
 {
   int i,n,sum=0;
   printf("enter the number :\n");
   scanf("%d",&n);
   for(i=1;i<=n;i++)
   {
      sum=sum+i;
   }
     printf("sum of 1 to n is :%d",sum);
     getch();
 }
Output
enter the number :
18    /* say n = 18 */.
sum of 1 to n is :171

Program Explanation


Step 1: Include header files (#include<stdio.h> and #include<conio.h>).

Step 2: Start with main function with return type.

Step 3: parenthesis to start and end the program { }.

Step 4: declare variables with data type i.e, 'n' is an integer type so we use "int" data type. We also declare 'i' as "int" because it also has an integer value which we use for the iteration of the for loop. we declared 'sum' as zero so that it won't takes any garbage value and it also returns an integer type so that we declared 'sum' in "int" as well.

Step 5: Use output function printf() to print the output on the screen.

Step 6: Use input function scanf() to get input from the user.

Step 7: A for loop is a control statement using which the programmer can give instructions to the computer to execute a set of statement repeatedly as long as specified condition is satisfied.

  • At first iteration, i is 1. The test condition (i<=n) is satisfied as (1<=n). i.e, say n = 18 which is greater than 1. Since this condition is satisfied, the control enters the loop and executes (sum=sum+1). which means it adds the value and, After the execution of the statement the value of 'i' is incremented by 1 as of i++.
  • Now, the value of 'i' is 2. Again, the test condition (i<=n) is satisfied as (2<=n). Since the condition is satisfied, the control enters the loop and executes the sum and increment the value of 'i' by 1 as of i++.
  • Again, the same iteration the value of 'i' is 3, the test condition (i<=n) is satisfied as (3<=n). Hence, the control enters the loop and executes the sum and again the value of i is incremented by 1 as of i++.
  • Again and again, the same condition is checked and the process is repeated until the value of 'i' becomes greater than 'n', Once the value of 'i' becomes greater than 'n', it comes out of the loop and iteration stops.

Step 8: using getch() function to hold the screen and show the output on the screen.
i.e, enter the number :
18   // say n = 18
sum of 1 to n is :171