w3resource logo


C Programming Exercises

C Exercises: Calculate the sum of three numbers getting input in one line

Secondary Nav

C Input Output statement: Exercise-8 with Solution

Write a program in C to calculate the sum of three numbers with getting input in one line separated by a comma.

Test Data:
Input three numbers separated by comma : 5,10,15

Expected Output :
The sum of three numbers : 30

C Code:

#include <stdio.h>

int num1,num2,num3;         /* declaration of three variables */  
int sum;
char line_text[50];      /* line of input from keyboard */ 
  
int main() 
{  
    printf("Input three numbers separated by comma : "); 
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%d, %d, %d", &num1, &num2, &num3);
    sum = num1+num2+num3; 
    printf("The sum of three numbers : %d\n", sum);  
    return(0);  
}  

Solution

#include <stdio.h>
int num1,num2,num3;         /* declaration of three varialbes */  
int sum;
char line_text[50];      /* line of input from keyboard */ 
int main() 
{  
    printf("Input three numbers seperated by comma : "); 
	fgets(line_text, sizeof(line_text), stdin);
	sscanf(line_text, "%d, %d, %d", &num1, &num2, &num3);
    sum = num1+num2+num3; 
    printf("The sum of three numbers : %d\n", sum);  
    return(0);  
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables