Lab 4
Lab 4
Lab Manual
Programming in C
Lab 4
Index
Lab Objectives
Background
Some Examples
Exercises
Lab Objectives:
Explain the basic of for loops and while loops,
Background:
The loop can be used to do repetitive calculations. For example, in order to compute the sum
of 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:
1. Write a program to find the summation 1+2+3+4+…….+100
Program code:
#include<stdio.h>
int main()
{
int sum = 0;
for (int j = 1; j <= 100; j++)
sum += j;
printf("1+2+3+......+100= %d",sum);
return 0;
}
#include<stdio.h>
int main()
{
int a, b, c; char ch;
while(1) {
printf("Enter values of a and b\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("a + b = %d\n", c);
printf("Do you wish to add more numbers(y/n)\n");
scanf(" %c",&ch);
if ( ch == 'y' || ch == 'Y' ) continue;
else
break;
}
return 0;
}
#include <stdio.h>
int main() {
int n, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d",&n);
while(n != 0) {
remainder = n % 10;
sum = sum + remainder;
n = n / 10;
}
printf("Sum of digits of entered number = %d\n",sum);
return 0;
}
#include <stdio.h>
int main() {
int a, b, x, y, t, gcd, lcm;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
a = x; b = y;
while (b != 0) { t = b;
b = a % b;
a = t;
}
gcd = a;
lcm = (x*y)/gcd;
printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
return 0;
}
6. Write a program to find factorial of a given number.
Program code:
#include<stdio.h>
int main()
{
int i,n,f;
printf("Enter the number to find the factorial\n");
scanf("%d",&n);
f=1;
for(i=1;i<=n;i++)
f=f*i;
printf("The factorial of a number %d without using recursion is %d",n,f);
Exercise:
1. Write a program that will print the prime numbers in a given range.
Sample input: Given range- 1 to 20
Sample output: 2 3 5 7 11 13 17 19
2. Write a program that will check whether a given number is palindrome or not.
Palindrome Numbers
Palindrome number in c: A palindrome number is a number such that if we reverse it, it will
not change. For example some palindrome numbers examples are 121, 212, 12321, 454. To
check whether a number is palindrome or not first we reverse it and then compare the number
obtained with the original, if both are same then number is palindrome otherwise not.
Palindrome number algorithm
2.
*
* *
* * *
* * * *
3.
*
* *
* * *
* * * *
4.
*
* *
* * *
* *
*