Cse 122
Cse 122
OBJECTIVE:
Theory:
For loop in C is the most general looping construct. The loop header contains three parts: an initialization,
a continuation condition, and step.
Syntax:
for (initialization, condition, step)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
For statement contain three parts separated by two semicolons. The first part is known as
initialization. The variable called loop control variable or index variable is initialized in this part.
The second part is known as the condition. The condition should be a value one. The condition
check can be a compound expression made up of relational expression connected by logical AND, OR.
The third part is known as step. It should be an arithmetic expression. The initialization need
not be contained to a single variable. If more than one variable is used for initialization they are separated
by commas. The step can also applied to more than one variable separated by commas.
When for statement is encountered at first index variable is get initialized. This process is done only once
during the execution of for statement. When condition is evaluated, if it is true the body of the loop will
be executed. If more than one statement has to be executed it should end with a pair of braces. The
condition of for loop is executed each time at the beginning of the loop. After executing the body of the
loop the step is executed, again the condition is executed. If the condition become false it exit from the
loop and control transferred to the statement followed by the loop.
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
1. #include <stdio.h>
2.
3. main()
4. {
5. int i;
6.
7. printf("All odd numbers from 1 to 50 are: \n");
8.
9.
10. for(i=1; i<=50; i++)
11. {
12.
13. if(i%2!=0)
14. {
15. printf("%d\n",i);
16. }
17. }
18.
19. }
Code 2: In mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the
following integer sequence:
By definition, the first two numbers in the Fibonacci sequence are 1 and 1. And Each subsequent
number is the sum of the previous two. You have to add ‘n’ number of Fibonacci numbers.
Code:
#include<stdio.h>
void main()
{
int n, first = 0, second = 1,sum=0, next, i;
printf("Enter the number of terms=");
scanf("%d",&n);
for (i=1 ; i<=n ; i++ )
{
if ( i == 1 )
next = i;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\t",next);
sum=sum+next;
}
printf("\nSum=%d",sum);
}
Exercise: