4. (C) Write a program to find the sum of numbers from 1 to 100
Sum of Natural Numbers Using while Loop
#include <stdio.h> | |
int main() | |
{ | |
int n, i, sum = 0; | |
printf("Enter a positive integer: "); | |
scanf("%d",&n); | |
i = 1; | |
while ( i <=n ) | |
{ | |
sum += i; | |
++i; | |
} | |
printf("Sum = %d",sum); | |
return 0; | |
} |
Sum of Natural Numbers Using for Loop
#include <stdio.h> | |
int main() | |
{ | |
int n, i, sum = 0; | |
printf("Enter a positive integer: "); | |
scanf("%d",&n); | |
for(i=1; i <= n; ++i) | |
{ | |
sum += i; // sum = sum+i; | |
} | |
printf("Sum = %d",sum); | |
return 0; | |
} |
Program to Read Input Until User Enters a Positive Integer
#include <stdio.h> | |
int main() | |
{ | |
int n, i, sum = 0; | |
do { | |
printf("Enter a positive integer: "); | |
scanf("%d",&n); | |
} | |
while (n <= 0); | |
for(i=1; i <= n; ++i) | |
{ | |
sum += i; // sum = sum+i; | |
} | |
printf("Sum = %d",sum); | |
return 0; | |
} |
4. (C) Write a program to find the sum of numbers from 1 to 100
Reviewed by admin
on
December 23, 2019
Rating:
No comments: