Examples of Cprograms
Examples of Cprograms
#include <stdio.h>
int main ()
{
int j, sum = 0;
printf ("The first 10 natural number is: ");
for (j = 1; j <= 10; j++)
{
sum = sum + j;
}
printf("\n The Sum is : %d\n", sum);
}
Input:
The first 10 natural number is :
1 2 3 4 5 6 7 8 9 10
Output:
The Sum is : 55
4. Write a C program to display a pattern like a right angle triangle with a number.
1
22
333
4444
#include <stdio.h>
int main() {
int i, j, rows;
printf("Input number of rows : ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++)
printf("%d", i);
printf("\n");
}
return 0;
}
Input:
Input number of rows : 10
Output:
1
22
333
4444
6. Write a C program to make such a pattern like a right angle triangle with an asterisk.
*
**
***
****
*****
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Input number of rows : ");
scanf("%d", &rows);
Input:
Input number of rows : 5
Output:
*
**
***
****
*****
7. Write a C program to display the pattern as a pyramid using asterisks, with each row containing an
odd number of asterisks.
8. Write a program in C to display the n terms of a harmonic series and their sum.
1 1 1 1
1 + + + + ...+
2 3 4 𝑛
#include <stdio.h>
int main()
{
int i, n;
float s = 0.0;
printf("Input the number of terms : ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
s =s+ 1 / i;
}
9. Write a program in C to display the n terms of a harmonic series and their sum.
1 1 1 1
+ + + . . .+
2 3 4 𝑛
#include <stdio.h>
#include <math.h>
int main()
{
int i, n;
float s = 0.0;
printf("Input the number of terms : ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
s =s+1 / pow(i,2);
}