C Tutorial

This C program is used to find the sum of number for the given user input number.

for loop is used here to compute sum of numbers and displayed output in the console.

#include<stdio.h> void main() { int sum=0, number; printf("\nEnter the number: "); scanf("%d", &number); for(int i=1;i<=number;i++) { sum = sum + i; } printf("Sum of number %d: %d", number, sum); }

Output:

$ cc sum-of-number.c ]$ ./a.out Enter the number: 5 Sum of number 5: 15

This program is not having the for loop block and computes the sum of number using only for loop.

#includevoid main() { int sum=0, number; printf("\nEnter the number: "); scanf("%d", &number); for(int i=1;i<=number;sum=sum+i,i++); printf("Sum of number %d: %d", number, sum); }

Output:

$ cc sum-of-number.c ]$ ./a.out Enter the number: 5 Sum of number 5: 15

We need to place the statements in correct order in for loop, otherwise program will compute incorrect value for expected logic.

for (int i = 1; i <= number; i++, sum = sum + i) ;

This for loop will produce the incorrect value 20 instead of 15 for number 5.

Output:

$ cc sum-of-number.c $ ./a.out Enter the number: 5 Sum of number 5: 20

C Program Examples

Privacy Policy | Copyright@2017 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page

^