I am trying to make a program that allows the user to input a positive integer, and the program will output the sum of each digit added together. For example, if the user inputs 54, the program will output 9. For some reason, the program is outputting outrageously huge numbers. When 54 is the input, the output will read something like 5165451 or 2191235. I'm new to C programming, but I don't see a single thing wrong with this code..
//This program takes a positive integer
//from the user, and adds all the digits
//of the number together.
#include <stdio.h>
int main() {
system("clear");
int given, add, hold, i;
printf("Enter a positive integer (up to 10 digits): ");
scanf("%d", &given); //User input
for (i = 0; i < 10; i++) { //Loop to add digits
hold = (given % 10);
given = (given / 10);
add = (add + hold);
}
printf("Sum of the digits is %d\n", add); //Output
}
int given, add, hold, i;
You haven't initialized add, so it contains unspecified data, aka garbage. Using its value while it is unspecified is undefined behaviour.
Insert add = 0; before the loop to see if that helps.
I think the for loop is wrong
The loop will run 10 times whereas scanf will only take the input upto the limit of int data type i.e 32768.
You should make given a long data type.
and make the for loop as
for(;given!=0;)
{
hold = (given % 10);
given = (given / 10);
add = (add + hold);
}
and of course initialize add to zero.
Related
I couldn't share the original code but the below program is as similar to my problem.
#include<stdio.h>
#include<conio.h>
void clrscr(void);
int reverse_of(int t,int r)
{
int n=t;
r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n",n); /*displays the input*/
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
return r; /*returns the value to main function*/
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
};
int main()
{
int n,r;
void clrscr();
printf("Enter a number: ");
scanf("%d",&n);
//while (n!=0) /*Use this for any number of digits*/
/* {
int z=n%10;
r=r*10+z;
n=n/10;
} */
r=reverse_of(n,r);
printf("The reverse of your number is: %d\n",r);
return 0;
};
This program displays the reverse of a 4 digit number. it works perfect when my first input is a 4 digit number. The output is as below.
(Keep in mind that i dont want this program to display the reverse of
a number unless its 4 digit)
Enter a number: 1234
Your number is: 1234
The reverse of your number is: 4321
Now when i give a non 4 digit number as the first input the program displays that it is not a 4 digit number and asks me for a 4 digit number. Now when i give a 4 digit number as the second input. It returns the correct answer along with another answer which is supposed to be the answer for the first input. (since the program cannot find the reverse value of a non 4 digit number the output always return 0 in that particular case). If i give 5 wrong inputs it displays 5 extra answers. Help me get rid of this.
Below is the output when i give multiple wrong inputs.
Enter a number: 12
The number you entered is 2 digit so please enter a four digit number
Enter a number: 35
The number you entered is 2 digit so please enter a four digit number
Enter a number: 455
The number you entered is 3 digit so please enter a four digit number
Enter a number: 65555
The number you entered is 5 digit so please enter a four digit number
Enter a number: 2354
Your number is: 2354
The reverse of your number is: 4532
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
Help me remove these extra outputs btw im using visual studio code and mingw compiler.
The problem lies here:
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
You're calling main() from reverse_of().
Try replacing the main(); with return 0; and in main(), do this:
int n,r;
do{
printf("Enter a number: ");
scanf("%d",&n);
r=reverse_of(n,r);
}while(r==0);
printf("The reverse of your number is: %d\n",r);
This happens because of the multiple recursion caused by the call of main() inside of the reverse_of function.
To avoid such thing you can move the printf("The reverse of your number is: %d\n", r); to the inside of the if(count==4){} and your problem is solved!
Also, note that your reverse_of functions does not need to receive the int r, instead it can be written like this:
#include <stdio.h>
int reverse_of(int t)
{
int n = t;
int r = 0;
int count = 0;
while (t != 0) /*Loop to check the number of digits*/
{
count++;
t = t / 10;
}
if (count == 4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n", n); /*displays the input*/
while (n != 0) /*This loop will reverse the input*/
{
int z = n % 10;
r = r * 10 + z;
n = n / 10;
}
printf("The reverse of your number is: %d\n", r);
return 1;
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n", count);
return 0;
}
};
int main()
{
int n, r=0;
while (r!=1){
printf("Enter a number: ");
scanf("%d", &n);
r=reverse_of(n);
}
return 0;
};
Hope it helped!
Well, your program has some ambiguity: If you stop as soon as you get 0, then the reverse of 1300, 130 and 13 will be the same number, '31'.
So, first of all you need two parameters in your function, to deal with the number of digits you are considering, so you don't stop as soon as the input number is zero, but when all digits have been processed. Then you extract digits from the least significant, and add them to the result in the least significant place. This can be done with this routine:
int reverse_digits(int source, int digits, int base)
{
int i, result = 0;
for (i = 0; i < digits; i++) {
int dig = source % base; /* extract the digit from source */
source /= base; /* shift the source to the right one digit */
result *= base; /* shift the result to the left one digit */
result += dig; /* add the digit to the result on the right */
}
return result;
}
The extra parameter base will allow you to operate in any base you can represent the number. Voila!!!! :)
#include <stdio.h>
int main()
{
int src;
while (scanf("%d", &src) == 1) {
printf("%d => %d\n",
src,
reverse_digits(src, 5, 10));
}
}
will provide you a main() to test it.
In contrast to C++, in C, it is allowed to call main recursively. But it is still not recommended. There are only a few situations where it may be meaningful to do this. This is not one of them.
Recursion should only be used if you somehow limit the depth of the recursion, otherwise you risk a stack overflow. In this case, you would probably have to call the function main recursively several thousand times in order for it to become a problem, which would mean that the user would have to enter a value that is not 4 digits several thousand times, in order to make your program crash. Therefore, it is highly unlikely that this will ever become a problem. But it is still bad program design which may bite you some day. For example, if you ever change your program so that it doesn't take input from the user, but instead takes input from a file, and that file provides bad input several thousand times, then this may cause your program to crash.
Therefore, you should not use recursion to solve this problem.
The other answers have solved the problem in the following ways:
This answer solves the problem by making the function reverse_of not return the reversed value, but to instead directly print it to the screen, so that it does not have to be returned. Therefore, the return value of the function reverse_of can be used for the sole purpose of indicating to the calling function whether the function failed due to bad input or not, so that the calling function knows whether the input must be repeated. However, this solution may not be ideal, because normally, you probably want the individual functions to have a clear area of responsibility. To achieve this clear area of responsibility, you may want the function main to handle all the input and output and you may want the function reverse_of to do nothing else than calculate the reverse number (or indicate a failure if that is not possible). The fact that you defined your function reverse_of to return an int indicates that this may be what you originally intended your function to do.
This answer solves the problem by reserving a special return value (in this case 0) of the function reverse_of to indicate that the function failed due to bad input, so that the calling function knows that the input must be repeated. For all other values, the calling function knows that the function reverse_of succeeded. In this case, that solution works, because the value 0 cannot be returned on success, so the calling function can be sure that this value must indicate a failure. Therefore, in your particular case, this is a good solution. However, it is not very flexible, as it relies on the fact that a return value exists that unambiguously indicates a failure (i.e. a value that cannot be returned on success).
A more flexible solution, which keeps a clear area of responsibility among the two functions as stated above, would be for the function reverse_of to not always return a single value, but rather to return up to two values: It will return one value to indicate whether it was successful or not, and if it was successful, it will return a second value, which will be the result (i.e. the reversed value).
However, in C, stricly speaking, functions are only able to return a single value. However, it is possible for the caller to pass the function an additional variable by reference, by passing a pointer to a variable.
In your code, you are declaring your function like this:
int reverse_of(int t,int r)
However, since you are not using the argument r as a function argument, but rather as a normal variable, the declaration is effectively the following:
int reverse_of( int t )
If you change this declaration to
bool reverse_of( int t, int *result )
then the calling function will now receive two pieces of information from the function reverse_of:
The bool return value will indicate whether the function was successful or not.
If the function was successful, then *result will indicate the actual result of the function, i.e. the reversed number.
I believe that this solution is cleaner than trying to pack both pieces of information into one variable.
Note that you must #include <stdbool.h> to be able to use the data type bool.
If you apply this to your code, then your code will look like this:
#include <stdio.h>
#include <stdbool.h>
bool reverse_of( int t, int *result )
{
int n=t;
int r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
*result = r;
return true;
}
else /*This will execute when the input is not a 4 digit number */
{
return false;
}
};
int main()
{
int n, result;
for (;;) //infinite loop
{
//prompt user for input
printf( "Enter a number: " );
//attempt to read number from user
if ( scanf( "%d",&n ) != 1 )
{
printf( "Invalid input!\n" );
//discard remainder of line
while ( getchar() != '\n' )
;
continue;
}
printf( "Your input is: %d\n", n );
//attempt to reverse the digits
if ( reverse_of( n, &result) )
break;
printf( "Reversing digits failed due to wrong number digits!\n" );
}
printf("The reverse of your number is: %d\n", result );
return 0;
};
Although the code is now cleaner in the sense that the area of responsibility of the functions is now clearer, it does have one disadvantage: In your original code, the function reverse_of provided error messages such as:
The number you entered is 5 digit so please enter a four digit number
However, since the function main is now handling all input and output, and it is unaware of the total number of digits that the function reverse_of found, it can only print this less specific error message:
Reversing digits failed due to wrong number digits!
If you really want to provide the same error message in your code, which specifies the number of digits that the user entered, then you could change the behavior of the function reverse_of in such a way that on success, it continues to write the reversed number to the address of result, but on failure, it instead writes the number of digits that the user entered. That way, the function main will be able to specify that number in the error message it generates for the user.
However, this is getting a bit complicated, and I am not sure if it is worth it. Therefore, if you really want main to print the number of digits that the user entered, then you may prefer to not restrict input and output to the function main as I have done in my code, but to keep your code structure as it is.
Problem:
You are provided an array A of size N that contains non-negative integers. Your task is to determine whether the number that is formed by selecting the last digit of all the N numbers is divisible by 10.
Note: View the sample explanation section for more clarification.
Input format
First line: A single integer N denoting the size of array Ai.
Second line: N space-separated integers.
Output format:
If the number is divisible by 10 , then print Yes . Otherwise, print No.
Constraints:
1<=N<=100000
0<=A[i]<=100000
i have used int, long int ,long long int as well for declaring N and 'm'.But the answer was again partially accepted.
#include <stdio.h>
int main() {
long long int N,m,i;
scanf("%ld", &N);
long data[N];
for(auto i=0; i<N; i++) {
scanf("%ld", &data[i]);
}
// write your code here
// ans =
m=(data[0]%10);
for(i=1; i<N; i++) {
m=m*10;
m=(data[i]%10)+m;
}
if(m%10!=0 && m==0) {
printf("Yes");}
else{
printf("No");
}
return 0;
}
Try making a test suite, that is, several tests for which you know the answer. Run your program on each of the tests; compare the result with the correct answer.
When making your tests, try to hit also corner cases. What do I mean by corner cases? You have them in your problem statement:
1<=N<=100000
0<=A[i]<=100000
You should have at least one test with minimal and maximal N - you should test whether your program works for these extremes.
You should also have at least one test with minimal and maximal A[i].
Since each of them can be different, try varying them - make sure your program works on the case where some of the A[i] are large and some are small.
For each category, include tests for which the answer is Yes and No - to exclude the case where your algorithm always outputs e.g. Yes by mistake.
In general, you should try to make tests which challenge your program - try to prove that it has a bug, even if you believe it's correct.
This code overflows:
m=(data[0]%10);
for(i=1; i<N; i++) {
m=m*10;
m=(data[i]%10)+m;
}
For example, when N is 1000, and each of the input items A[i] (scanned into data[i]) ends in 9, this attempts to compute m = 99999…99999, which grossly overflows the capability of the long long m.
To determine whether the numeral formed by concatenating a sequence of digits is divisible by ten, you merely need to know whether the last digit is zero. The number is divisible by ten iff data[N-1] % 10 == 0. You do not even need to store these numbers in an array; simply use scanf to read but ignore N−1 numerals (e.g., scanf("%*d")), then read the last one and examine its last digit.
Also scanf("%ld", &N); wrongly uses %ld for the long long int N. It should be %lld, or N should be long int.
An integer number given in decimal is divisible by ten if, and only if, its least significant digit is zero.
If this expression from your problem:
the number that is formed by selecting the last digit of all the N numbers
means:
a number, whose decimal representation comes from concatenating the least significant digits of all input numbers
then the last (the least significant) digit of your number is the last digit of the last input number. And that digit being zero is equivalent to that last number being divisible by 10.
So all you need to do is read and ignore all input data except the last number, then test the last number for divisibility by 10:
#include <stdio.h>
int main() {
long N, i, data;
scanf("%ld", &N);
for(i=0; i<N; i++)
scanf("%ld", &data); // scan all input data
// the last input number remains in data
if(data % 10 == 0) // test the last number
printf("Yes");
else
printf("No");
return 0;
}
I really need help to store double values in a double array. I am trying using scanf_s and it works. But if I try to input more than 4 values, my program crashes and returns me the error code 3
I actually need a dynamic array, but as I was getting too many errors with that, I changed and I'm trying to use a common array, just so I can get at least some marks for this project.
This is the code I am using now...
int main()
{
printf("Enter white-space separated real numbers. Terminate input with ^Z\n");
//get the dynamic array
double numSet[1000] = { 0 };
int size = 0;
double number;
while (scanf_s("%lf", &number) == 1)
{
numSet[size] = number;
size++;
}
//sort the array using qsort
//range of the array
double min = numSet[0];
double max = numSet[size - 1];
//get the mean
double sum = 0.0;
for (size_t i = 0; i < size; i++)
{
sum += numSet[i];
}
double mean = sum / size;
printf("Range: [%.2f ... %.2f]\n", min, max);
printf("Arithmetic mean is: %f", mean);
}
I have two problems:
Is a warning about buffer overrun:
Warning C6385 Reading invalid data from 'numSet':
the readable size is '8000' bytes, but '-8' bytes may be read.
When I try to input more than 4 numbers, my program crashes and returns the code 3
while (scanf_s("%lf", &number) == 1)
{
numSet[size] = number;
size++;
}
instead of this use
while (scanf_s("%lf", &number) == 1 && size <= 1000)
{
numSet[size] = number;
size++;
}
Your loop goes infinitely because it has no termination character.
scanf_s only reads value from keyboard and has another parameter to set its maximum input buffer value which is useful to limit your input.
What you can do is either read size from the user before letting him enter values or you can ask every time if the user wants to add more values to the array or not.
for example:
char option = 'Y';
while ( (scanf_s("%lf", &number) == 1 && option == 'Y'){
// code to enter a new number
printf("Do you want to add more numbers? (Y/N) ");
scanf("%c", &option);
}
Also, the scanf_s function returns the number of values scanned and every time is 1 as you are always taking one double value.
So even if you remove it, it wont be of much trouble.
I think the problem is how you end the input loop, scanf_s isn't needed, please see the watch window. I simply change the end condition to some no digit char.
Code::Blocks watch window
As mentioned in the comments, it's possible for
double max = numSet[size - 1];
to evaluate as
double max = numSet[-1];
when size = 0. I'm guessing that a double is 8 bytes wide, so the compiler warns that it could try to read -1 * 8 = -8 bytes from memory.
// Program to convert a positive interger another base
#include <stdio.h>
int main (void)
{
const char baseDigits[16] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F' };
int convertedNumber[64];
long int numberToConvert;
int nextDigit, base, index = 0;
// get the number and the base
printf ("Number to be converted?");
scanf ("%ld", &numberToConvert);
printf("Base?");
scanf ("%i",&base);
// convert to the indicated base
do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while (numberToConvert != 0);
//display the result in the reverse order
printf(" Converted number = ");
for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}
printf("\n");
return 0;
}
I do not understand this code. How will it be able to show the reverse order? Especially the for statement inside the brackets. Why does --index appear twice? What's the meaning it and index >=0? What's the use of nextDigit?
for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
Another new question:""
Why we also should output a number at least? and so here with the do loop?""
(Because using scanf to read long integer number of formatted input symbols is %ld. Because even if the user's input is 0 ,we also should output a number
at least, so here with the do loop)
For example, consider a number n, that needs to be converted to binary.
Now, if the number n is divided multiple times, by 2, you acquire the binary representation of the number in reverse.For example,
Say n=4, then considering the loop, we find that, the number is stored as 001, in convertedNumber, which is basically the reverse of the binary representation of 4(100).
At the end of the conversion,index is incremented an extra time.For the n=4 case, index=3(2increments + an extra).
So, the for(--index;index>=0;--index) basically states that,
start for loop at index=2(--index(3)=2), loop until index>=0, decrement once after every loop.This would print out the "reverse" of the reverse.(in the n=4 case, 001 is printed as 100, which is binary 4).
Your code basically converts base10 "numberToConvert" to a required base number. I hope you know about this. You can read this for more information.
Now analyse the code.
do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while (numberToConvert != 0);
This code actually do the conversion and stores each digit of new base number as a different number in array.
Example: If input is 146 and you want to convert it to base 13 number, then
convertedNumber[0] = 3
convertedNumber[1] = 11
At the end of the conversion thread exits from while loop and index value will be 2.
Now it comes to the for loop.
for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}
You need to print value at index 1 and index 0. So index value start with decrementing itself.
Please remember, the first statement in for loop is executed only once. So effectively, there is only one --index;per loop.
It finds the character to display for a given digit. Ex: for index[1]=10, it prints 'A' and index[0]=3, it prints '3'. So output is A3. This is done to do conversion from base 10 to any base from 2 to 16 (However, that check is not there! You need to add a check for user entered base and make sure it is [2, 16]).
I've been pouring over my code (which does not work) now for quite some time. It is for a Project Euler problem in which one is given a very large sum to find, and then required to print the first ten digits of said sum. (The problem can be found here: https://projecteuler.net/problem=13)
I have run several 'tests' where I add print commands to see various values at various points in the code. When I run the code, I have gotten anything from symbols to ten digit numbers that should be single digits.
Anyways. My question is this: is this a type conversion issue or is there some other glaring issue with my method that I'm missing? I've been studying type conversions trying to find a fix, but to no avail.
Thank you for any help!
The code is as follows:
// this is a program to find a very large sum of many very large numbers
#include <stdio.h>
#include <math.h>
int main()
{
//declare all ints needed
int i;
int j;
int d; // digit, need to add 48
int placesum; // sum of addition in _'s place (1's, 10's, 10000's)
int place; // final place value
int c = 0, tens = 1, otherc; // counters for start finder
int a = 0; // another counter
//declare all arrays
char numarray[101][51]; //array of strings containing all 100 numbers
char sum[100];
printf("please save data to largesumdata.txt\n\n press enter when ready");
getchar();
// THE PROBLEM- I don't know how to get my data into my program // FIXED
// using fscanf()
FILE *pf; // declare a pointer to the file
pf = fopen("largesumdata.txt", "r"); // trys to open file // "r" means read only
if(pf == NULL)
printf("Unable to open file, sorry Jar\n");
else
{
for(j = 0; j < 100; j++)
fscanf(pf, "%s\n", &numarray[j]); // fscanf(pointer, data type, location)
}
//TESTING
//printf("You have reached point A\n");//POINT A WAS REACHED
//TESTING
//TESTING
//printf("Check1, %c\n", numarray[45][23]);
//TESTING
//TESTING
//printf("%c\n", numarray[90][22]);//Can successfully call characters from array
//TESTING
// (Brute force attempt) //I NEVER MESS WITH numarray WHY IS IT CHANGING
for(i = 49; i >= 0; i--)
{
//printf("%d\n", d);
for(j = 0; j < 100; j++)
{
d = (int)numarray[j][i] - 'o';
//printf("%d\n", d);
//holdup// d -= 48; // ASCII conversion // could also write "d = d-48"
//printf("%d\n", d);
placesum += d; // could also write "placesum = placesum + d"
//printf("%d\n", placesum);
}
place = placesum % 10;
placesum = placesum / 10; // takes "10's place" digit for next column
// now need to put 'int place' into 'char sum'
sum[i+5] = (char)place+'0'; // ASCII conversion // "+5" for extra space //HERE not properly stored in sum
}
//TESTING
//printf("Check2, %c\n", numarray[45][23]);
//TESTING
//TESTING
//printf("You have reached point B\n");//POINT B WAS REACHED
//TESTING
// find out where sum starts
for(c=0; c<10; c++)
if(sum[c] != '0')
break;
//TESTING
//printf("You have reached point C\n"); //POINT C WAS REACHED
//TESTING
otherc = 4-c;
printf("The first 10 digits of the sum of all those f***ing numbers is....\n");
printf("%d-%d-%d-%d-%d-%d-%d-%d-%d-%d", sum[otherc, otherc+1, otherc+2, otherc+3, otherc+4, otherc+5, otherc+6, otherc+7, otherc+8, otherc+9]);
//%c-%c-%c-%c-%c-%c-%c-%c-%c-%c //copy and paste purposes
//%d-%d-%d-%d-%d-%d-%d-%d-%d-%d // ^^^^^
getchar();
return 0;
}
P.S. I apologize if my plethora of notes is confusing
You are using wrong form to print an array in C.
sum[otherc, otherc+1, otherc+2, otherc+3, otherc+4, otherc+5, otherc+6, otherc+7, otherc+8, otherc+9] -> This actually decays to sum[otherc+9] because C treats , as an operator.
To print value at each array index, you should use it like this: sum[otherc], sum[otherc+1], sum[otherc+2],..
To read more about C's , (comma) operator, you can begin here
In your printf as I explained above, the first format specifier %d gets sum[otherc + 9], since sum[otherc,...,otherc+9] is actually a single number and that is otherc + 9th index of array sum. You do not provide anything to print for other format specifiers, hence you get garbage.
After a while I revisited my code, and realized that I was working with numbers upwards of 10 million. I had a mix of int, long int, and long long int variables declared.
I re-analyzed which was which, and made sure that all variables could handle the data it needed to (after looking at this handy link, showing what max integer sizes are for different data types.
Before I had been using the wrong ones, and going over the max values returned incorrect values, causing my program to crash during run time.
Lesson here: Check your data types!