APL Experiment No2
APL Experiment No2
Program 2
Program to find Factorial of number. Using for loop
#include<stdio.h>
int main()
{
int num, count, fact = 1;
printf("Enter a number to find its Factorial\n");
scanf("%d", &num);
for(count = 1; count <= num; count++)
{
fact = fact * count;
}
printf("Factorial of %d is %d\n", num, fact);
return 0;
}
Output 1:
Enter a number to find its Factorial
5
Factorial of 5 is 120
Program 3
Program to calculate the sum of first n natural numbers
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
Program 4
Program to Print numbers from 1 to 5 using while loop
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
Output
1
2
3
4
5
Here, we have initialized i to 1.
When i = 1, the test expression i <= 5 is true. Hence, the body of the while
loop is executed. This prints 1 on the screen and the value of i is increased
to 2.
Now, i = 2, the test expression i <= 5 is again true. The body of the while
loop is executed again. This prints 2 on the screen and the value of i is
increased to 3.
This process goes on until i becomes 6. Then, the test expression i <= 5
will be false and the loop terminates.
Program 5