Lab Manual # 3. Control Statements
Lab Manual # 3. Control Statements
Programming in C
Lab Manual
Lab 3
Control Statements - while loop, for loop and do-while loop
INDEX
Lab Objectives
Background
Some Examples
Exercises
Lab Objectives:
• Explain the basic of for loop and while loop,
• To apply the syntax of loop structure,
• Design program using loop structure.
Background:
The loop can be used to do repetitive calculations. For example, in order to compute the sum of
1 to 100 (i.e., 1 + 2 + 3 + ... + 100), we can do easily using the following code segment:
int sum = 0;
for (int j = 1; j <= 100; j++)
sum += j;
There are two control structures used often: the ‘for’ loop and the ‘while’ loop (and ‘do while’
as a different way of while). The syntaxes of these loop structures are as follows:
while(condition){
statements in the block or one statement
}
do{
statements in the block or one statement
}while(condition);
Some Examples:
sum = 0;
for(count = 1; count <= noOfIntegers; count++){
scanf("%d",&value);
sum = sum + value;
}
printf("Sum of the entered integers = %d\n",sum);
return 0; }
4. Write a program that accepts the number of rows from the user and generates the
following output:
Sample Input: Sample Input:
Enter the number of rows: 5 Enter the number of rows: 3
Sample Output: Sample Output:
* *
* * * *
* * * * * *
* * * *
* * * * *
Program code:
#include<stdio.h>
int main(){
int n, line, star;
printf("\n Enter the number of rows: ");
scanf("%d",&n);
for(line=1; line<=n; line++){
for(star=1; star<= line; star++){
printf(" * ");
}
printf("\n");
}
return 0;
}
Exercise:
1. Write a program to find the factorial of a given number.
[CLUE: 5! = 1*2*3*4*5; 8! = 1*2*3*4*5*6*7*8]
2. Write a program to find the minimum of N numbers.
3. Write a program that will take a lower limit (x1) and an upper limit (x2) of a range
from the user and find the summation of all the integer numbers which are
between x1 & x2 and divisible by 3.
4. Write three different programs that will accept the number of rows from the user
and generate the following outputs:
(a) Sample Input: (b) Sample Input: (c) Sample Input:
Enter the number of rows: 5 Enter the number of rows: 5 Enter the number of rows: 5
Sample Output: Sample Output: Sample Output:
* * * * * 1 12345
* * * * 2 2 1234
* * * 3 3 3 123
* * 4 4 4 4 12
* 5 5 5 5 5 1