Adding digits of an integer in C - c

My program asks the user to input an integer and adds the sum of the digits.
#include <stdio.h>
int main (void)
{
int inputNum, sum;
// Gets the inputNum
printf("Type in a positive integer, and this program\nwill calculate the sums of the digits: ");
scanf("%i", &inputNum);
do
{
sum += (inputNum % 10);
inputNum /= 10;
} while (inputNum != 0);
printf("Your sum is: %i\n", sum);
}
But every time it put an integer in, I get a number around 36000. I saw another example online that used %d, so I tried it but it made no difference. Am I just going in the wrong direction from the start? Thanks in advance.

You never initialized sum; it may well be starting with value 1,000,000
Just do:
int inputNum, sum = 0;

First thing, initialize sum to 0. Try then. int sum = 0;

Do it:
int inputNum, sum = 0;
i.e., you have to initialize sum.
Because in C the value of an uninitialized variable cannot be determinated. The value that you are getting is garbage from memory.

Initialize sum as zero. int variables don't have any default value unless its a global or static variable. as a (non-static) local variable inside of a function, it has an indeterminate value.

Related

recursion c, program does not display

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.

I cant write this factorial codes

I have some problem with that. I am trying to learn C programming. Please help me
#include<stdio.h>
int main()
{
int a, factorial;
printf("Please enter a value :" );
scanf("%d", &a);
for (int i = 1; i<=a; i++)
{
a = (a - 1)*a;
}
printf("%d", factorial);
return 0;
}
Well in your code line a = (a - 1)*a; you actually changed your input for getting the factorial. It also will blow your loop. See your for loop will continue as long as your i is less than a, lets say you choose a=3 after first iteration the a itself will become 6, so the for loop will continue until it reach the integer limit and you will get overflow error.
What you should do?
First of all you should use a second variable to store the factorial result, you introduced it as factorial, the way that #danielku97 said is a good way to write a factorial since if you present 0 as input it will also give the correct result of 1. so a good code is:
factorial = 1;
for (int i = 1; i<=a; i++)
{
factorial *= i;
}
But lets say you insist of subtraction, the way you just tried to use, then you need to change the code like:
scanf("%d", &a);
if (a==1 || a==0){
printf("1");
return 0;
}
factorial = a;
for (int i = 1; i<a; i++)
{
factorial *= (a - i)*factorial;
}
You can see that the code just got unnecessarily longer. An if included to correct the results for 1 and 0. Also you need to make sure that i never become like i =a since in that case a-i will be equal to zero and will make the factorial result equal to zero.
I hope the explanations can help you on learning C and Algorithm faster.
Your for loop is using your variable 'a' instead of the factorial variable and i, try something like this
factorial = 1;
for (int i = 1; i<=a; i++)
{
factorial *= i;
}
You must initialize your factorial to 1, and then the for loop will keep multiplying it by 'i' until 'i' is greater than 'a'.
You are modifying the input a rather than factorial and also wrong (undefined behaviour) because you are using factorial uninitialized. You simply need to use the factorial variable you declared.
int factorial = 1;
...
for (int i = 1; i<=a; i++) {
factorial = i*factorial;
}
EDIT:
Also, be aware that C's int can only hold limited values. So, beyond a certain number (roughly after 13! if sizeof(int) is 4 bytes), you'll cause integer overflow.
You may want to look at GNU bugnum library for handling large factorial values.

calculation of average number get way to high. I don't get why?

I am trying to get the average number of an array but the output is way to high for it to be correct. What am I doing wrong?
int count(int arr[]){
int sum;
//Average
for(int i=0;i<100; i++)
sum = sum + arr[i];
printf("Average:%f \n", sum/100);
}
int main()
{
int array[100]; //RANDOM NUMBERS 0-900
count(array);
return 0;
}
You need to initialize sum to zero before using it. C or C++ does not do this automatically for you in case of variables with automatic storage duration. It takes "time", and in C or C++ you don't pay for what you don't need. Otherwise you get a junk value (whatever its stored at that memory address, and technically it is undefined behaviour to use un-initialized variables except in assignments).
You also need to initialize the array, like
int arr[100]{}; // C++11 or later
or
int arr[100] = {0}; // C++98 or good old C
then fill it up with values. Do not consider the junk values as "random numbers", since again you are encountering undefined behaviour and the program is not altogether safe.
Undefined behaviour(UB):
sum = sum + arr[i];
You have used sum above and it was not initialized. It is UB to read values of uninitialized variables in C and C++.
Actually given your code it is even once again UB because neither array values arr[i] are initialized.
sum contains garbage value. Do initialize variable sumenter code here.
To verify you can print before updating sum.
Try the following:
int count(int arr[]){
int sum = 0; // <==================== initialize to zero
//Average
for(int i=0;i<100; i++)
sum = sum + arr[i];
printf("Average:%f \n", sum/100);
}
int main()
{
int array[100]; //RANDOM NUMBERS 0-900
count(array);
return 0;
}
Without this initialization, the local variable sum can have any arbitrary initial value. And you will end up with arbitrarily large sum. Which will throw off the average.
The reason for this is that local variables are NOT initialized to zero automatically (unlike global variables).

Calculate Average of 5 Integers Using an Array

I can't seem to get it right. The question is "Calculate the Average of 5 Integers using an array"
#include<stdio.h>
#include<stdlib.h>
int main()
{
int avg[5],i,total;
int average;
printf("Enter the marks entered in 5 subjects");
for (i=0; i<5; ++i){
scanf("%d",&avg[i]);
}
for(i=0; i<5; ++i){
total = total + avg[i];
}
average= (float)total/5;
printf("The average of 5 marks is %d",average);
return 0;
}
1) Your answer CAN be a decimal number but you are storing it in an integer which ignores the decimal points.
The variable average should be declared as float average;
The line where you print the result should be changed to printf("The average of 5 marks is %f",average);
2) Initialize the variable total as int total = 0;
In the for loop's first iteration, variable total is used uninitialized, so the result is wrong since it will automatically acquire a garbage value if not initialized explicitly. Take this whole thing:
#include <stdio.h>
int main() {
int avg[5], i, total = 0, average;
printf("Enter the marks entered in 5 subjects");
for (i = 0; i < 5; ++i) {
scanf("%d", &avg[i]);
total += avg[i];
}
average = total / 5;
printf("The average of 5 marks is %d", average);
return 0;
}
You've just declared the variable total but didn't initialize it. So, total contains a garbage value. For that if you add anything to total, the value will not be the correct as expected. It will be added to the garbage value. So,initialize the variable total with 0.
int total=0;
You need not to use type casting. Just declare the average variable as double.
double average=0;
average = total/5.0;
And you should print as printf("The average of 5 marks is %lf", average);
total should be initialized to 0:
int avg[5],i,total=0;
total is a local variable, hence it needs to be initialised. Had it been within file scope (like, a global variable), or a static variable, you might not have to initialise it to 0.
An initialisation could be simply like:
int avg[5], i, total = 0 ;
or
int avg[5], i, total;
total = 0 ;
Why do you need initialisation? Because of this statement:
total = total + avg[i];
Here total is calculated using its previous value. What is total's previous value the first time this statement is encountered? It could be anything, commonly referred to as garbage value, invoking undefined behaviour. Hence, you need initialisation to give this starting value to total. Note, you don't need to initialise average, because its value does not depend on its previous contents.
Another problem is with the concepts of typecasting. Here is the statement:
average= (float)total/5;
You are right about typecasting total to float (you may also have done total/5.0 instead). However, you are storing the result in an integer. This will result in a second typecasting, from the result in float to int.
Hence, you need to declare average as a float.
(Note: If having a float result is not your requirement, and you really need an integral answer, you may ignore this part).
You need to initialize variables before you use them in your code.
What goes WRONG in your code is,
int avg[5],i,total;
where you have not initialized the int variable "total"
Hence this code will use a garbage value
for(i=0; i<5; ++i){
total = total + avg[i];
}
You need this correction
int avg[5], i, total=0;

Trouble making a running total in C

I'm new at programming, new on this site too, so hello...
I'm attempting to obtain a running total for integers one thru 10, but I'm getting gibberish answers and I just can't understand why.
To attempt to find out what was going wrong, I added the
printf(" running total is %d\n", sum);
line to the while loop, but just got more of the same nonsense...
please see http://codepad.org/UxEw6pFU for the results....
I'm sure this has a blindingly obvious solution...I'm just too dumb to see it though!
anyone know what I'm doing wrong?
#include <stdio.h>
int main(void) {
int count,sum,square;
int upto=10;
count = 0;
square = 0;
while (++count < upto) {
square = count * count;
printf("square of %d is %d",count,square);
sum =square + sum;
printf(" running total is %d\n", sum);
}
printf("overall total of squares of integers 1 thru 10 is %d\n", sum);
return 0;
}
You need to initialize sum to 0.
EDIT As others have stated after the fact, the reason you're seeing garbage is because sum isn't initialized and contains whatever is in memory. It can be anything, and your use of it with sum = square + sum is going to add square to the uninitialized value.
You are never initializing the value of sum.
The first time your code runs
sum = square + sum;
The value of sum (on the right side) is an arbitrary number because it has not been initialized. Therefore, the resulting value of sum (on the left side) is that arbitrary number plus square.
Simply add a sum = 0 statement like you have for count and square already.
Right off the bat, you do not initialize 'sum' to anything.
edit: A cleaned up version, though depending on compiler, you might need to enforce C99 mode, otherwise older compilers might not support initial declarations in the for loop.
#include <stdio.h>
int main()
{
const int COUNT_MAX = 10;
int sum = 0;
for ( int i = 1; i <= COUNT_MAX; ++i )
{
sum += i*i;
}
printf("The sum of squares from 1 to 10 is: %d\n", sum);
return 0;
}
Initialize sum with 0, otherwise it contains arbitrary data:
sum = 0;
See: http://codepad.org/e8pziVHm
sum is not initialized
You should do :
sum=0;
and remove
square=0;

Resources