• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

I could use some VERY basic C programing help.

mcveigh

Diamond Member
I have taken a simple C (not C++) class before. now for a new class I have a really simple first program, almost heloo world simple.
I have to take a 5 digit input number then add it to gether that's it.
EX: 12345 is the input the output would be 1+2+3+4+5=15

I originally wrote a program that did that but I thought the input was 5 separate integers, pressing enter after each one.
how can I read a string as separate integers? I'm thinking using getchar() is that right or am I way off?

here's what i wrote so far


#include <stdio.h>

int main()
{

int a,b,c, sum = 0;
printf("\nPlease enter three integers to be added together.\n");

scanf ("%d",&a);

scanf ("%d",&b);

scanf ("%d",&c);

sum = a + b + c;
printf("\n\n\nThe sum of your integers is %d\n", sum);
return 0;
}
 
You could input the entire integer and then mod by powers of 10 to get each individual integer. As you get each integer, you can add it to the sum.
 
int sum, i = 0;

printf("\nPlease enter three integers to be added together.\n");

for(i=0; i<5; i++)
sum += getchar();

printf("\n\n\nThe sum of your integers is %d\n", sum);
return 0;

------

It's been ages since I've touched C though (and when I did, it wasn't much more complex than this)

(I think getchar needs string.h)
 
Thanks everyone! I used your idea igowerf, as I recalled the instructor seemed to be stressing modulus functions in class.
(at the time I was surfing ATOT 😉....sometimes internet access in class can be a bad thing.)


#include <stdio.h>
//begin main function
int main()
{
//setup space for the whole integer, it's parts and the sum

int a,b,c,d, sum;
printf("\nPlease enter three integers to be added together.\n");
//gather input
scanf ("%d",&a);
//echo input to confirm
printf("\nYour three digit number was %d\n", a);
//get the last integer by using modulus 10
d = a % 10;
//get second integer by modulus 100 then subtracting the last digit and diving by 10
c = ((a % 100) - d) /10;
//get the first integer by diving by 100 as I am using integers and not floating numbers
b = a / 100;
//add all the parts up
sum = b + c + d;
//output to screen
printf("\nThe sum of your integers is:\n%d + %d + %d = %d\n", b,c,d,sum);
//return from function
return 0;
}
 
Back
Top