/* */ Click to Join Live Class with Shankar sir Call 9798158723

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


Q.) W.A.P to print numbers from 1 to n using for loop ?
 #include<stdio.h>
 #include<conio.h>
 int main()
 {
	int n,i;
     printf("enter an integer :\n");
     scanf("%d",&n);
    for(i = 1; i<=n; i++)
    {
        printf("%d\n",i);
    }
     getch();
 }
Output
enter an integer :
10    /* say n = 10 */.
1
2
3
4
5
6
7
8
9
10

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.

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 = 10 which is greater than 1. Since this condition is satisfied, the control enters the loop and executes the statement and print the value of 'i'. 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 statement and print the value of 'i' 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 statement and the print the value of 'i' 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.