How this for loop is working how it is printing ap without mathematical fromula.(c programing)

#include<stdio.h>
int main()
{
int n,i;
printf(“enter a number:”);
scanf(“%d”,&n);
int a=4;
for(i=1;i<=n;i++)
{
printf("%d ",a);
a=a+3;
}
return 0;
}

its simple, for loop is a conditional statement in which we apply the three condition first we initialize, then provide a range in which the condition is executed, and next update the value.

for example,
according to your code
for(i=1; i<=n; i++)
i=1; - in this line you first initialized
i<=n; -you provide the range in which your condition is executed.
i++; - it is firstly print the current value then update the value than print value so on and so forth.

1 Like

thanks i was doing well but loops are a bit difficult for me. Any suggestions to do loops

for loops constraints(given) are initialization where you define i=0 . then condition where the loop will last such as i<=n then steps where the value of i will increase with number of steps such as i++ thus , it will work for the value of i =1,2,3,…n-1,n . while running of loop the task defined inside it will be performed thus ap is printed.

1 Like

Here common difference of AP will always be 3 and for loop Is adding 3 to ‘a’ on each iteration till ‘n’.
That’s why you got an AP with common difference=3

You can also change the common difference by replacing 3 with some int variable ‘d’ to make your code to run for different common difference of AP’s

1 Like