how to get sum of each input printed? - c

I am new to C and need some help with this basic program. I want the program to print out the sum directly after the input. I tried to put printf("..%d", sum); inside the for brackets and got but program shuts after the first input. It works if I have a scanf("%d", &value); before the For and inside the for brackets but there for I don't get the format I want.
I want the values to be printed vertical, left side should be inputs and right side should be output as u can see in the image.
Here is my code
#include <stdio.h>
int main()
{
int sum = 0, c, value;
scanf("%d", &value);
for (c = 1; c <= value; c++)
{
sum = sum + c;
printf("..%d", sum);
scanf("%d", &value);
}
return 0;
}

It appears you are a bit confused about which values you are actually summing (or I am...) From your problem descriptions (and from how you have initialized your for loop), it appears you are to input the ending value and then are to sum from 1 to that value?
If that is the case, there is no need for additional input within the for loop, your loop variable provides all values you are supposed to add to your sum.
Additionally, you cannot use any user-input function correctly unless you validate the return to determine whether input succeeded or failed.
Putting it altogether, you could do:
#include <stdio.h>
int main()
{
int sum = 0, c, value;
fputs ("sum from 1 to: ", stdout); /* prompt for input */
if (scanf ("%d", &value) != 1 || value < 1) { /* VALIDATE EVERY INPUT !!! */
fputs (" error: invalid integer input or negative value.\n", stderr);
return 1;
}
putchar ('\n'); /* add newline before output */
/* you are looping over the values of c -- no input is necessary */
for (c = 1; c <= value; c++)
{
sum = sum + c; /* sum */
printf ("%2d\t\t\t%d\n", c, sum); /* output value added and sum */
}
return 0;
}
Example Use/Output
$ ./bin/suminput
sum from 1 to: 5
1 1
2 3
3 6
4 10
5 15
Or for 1-10:
$ ./bin/suminput
sum from 1 to: 10
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
Or if invalid input is provided:
$ ./bin/suminput
sum from 1 to: twenty
error: invalid integer input or negative value.
Or a negative value:
$ ./bin/suminput
sum from 1 to: -10
error: invalid integer input or negative value.
No harm done.
Taking Input For The Sum
The other way I read your sample input and output (characterized by the 0 ending the loop), is that your task is simply to read inputs and sum them until the user enters 0 (or an invalid integer) displaying the sum after each input. That is quite a bit easier -- but the requirement to validate each input remains the same, e.g.
#include <stdio.h>
int main()
{
int sum = 0, value;
while (scanf ("%d", &value) == 1 && value != 0) { /* input value */
sum += value; /* sum */
printf ("%20d\n", sum); /* output sum */
}
}
Example Use/Output
$ ./bin/suminput2
1
1
2
3
3
6
4
10
5
15
0
Or any random values until 0 is entered:
$ ./bin/suminput2
1
1
-2
-1
3
2
-4
-2
5
3
-6
-3
0
(note: there are ways to place the input and output on the same line but that differs between compilers and operating systems. Windows could use the non-standard getch(), while on Linux you would need to do the same thing by changing input to non-cannonical mode with tcsetattr(). Another way would simply be to save the inputs until the user enters 0 and then to loop over all values input summing and displaying the values (though that would eliminate the 0 at the end of input show in your example input))
Look things over and let me know if you have further questions (and also whether I interpreted your question correctly). If you do need to enter each value to sum, let me know and I am happy to help further.

Related

Couldn't get rid of multiple outputs in a C program

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.

A program in C to compare last digit of UPC code with a calculated value and check if its valid or not?

So i made this code in c on visual studio, basically it takes as an input the UPC code of a product ( 12 integers) The last integer is like the check digit, which is related to the previous 11 digits by a formula. So the code basically checks if the UPC code is valid or not, by using the formula to calculate the check digit in the program itself and then compare it to the inputted value of the last digit :
Problem is, in visual studio the command prompt only takes the input and hangs,, as in it doesnt give any input and if i press enter the cursor blinks and just moves to a new line...
Edit :
The input I gave it is :
031564532525
Written exactly like that with no spaces
int main() {
// initialize the 11 digits of the UPC individually //
int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total ;
int end_dig;
// take input from user of UPC digits //
printf("Enter the UPC code:\n");
scanf_s("%d%d%d%d%d%d%d%d%d%d%d%d", &d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5, &end_dig);
// caclulate what the check digit SHOULD be according to the previous digits //
int last_digit;
first_sum = d + i2 + i4 + j1 + j3 + j5;
second_sum = i1 + i3 + i5 + j2 + j4;
total = (3 * first_sum) + second_sum;
last_digit = 9 - ((total - 1) % 10);
// compare calculated value of check digit with input value, to see wether its valid or not. //
if (end_dig == last_digit) {
printf("VALID\n");
}
else {
printf("NOT VALID\n");
}
return 0;
system("pause");
}
The %d format specifier reads not just a single number but a sequence of decimal digits. So the number you enter is being consumed by the first instance of %d, resulting it the program waiting for more input to satisfy the remaining format specifiers.
You need to split the digits with spaces so you can read each individually:
0 3 1 5 6 4 5 3 2 5 2 5
If you don't want to do that, you need to instead read in a single string, then inspect each digit in the string.

How to find how many times a number has been repeated in an array?

I am confused how to find out how many times a number has been repeated in a user input. I am able to input numbers and see which numbers are repeating but am unsure of how to print out each inputed number and how many times that number was used. This is what I have so far
#include <stdio.h>
#include <stdlib.h>
int main(){
double numArray[100];
int x = 0;
int y = 0;
int counter = 1;
int count = 0;
setvbuf(stdout, NULL, _IONBF, 0);
printf("Enter any number of integers between 0 and 99 followed a non-numeric: \n");
for (x = 0; x < 100; x++) {
if (scanf("%lf", &numArray[x]) != 1)
break;
counter = counter + 1;
}
counter = counter - 1;
for(x = 0; x < counter; x++){
for(y = x + 1; y < counter; y++){
if(numArray[x] == numArray[y]){
printf("duplicate found: %lf\n", numArray[x]);
break;
}
}
}
return EXIT_SUCCESS;
}
Continuing for my initial comment, whenever you want to capture the frequency of values within a range, you generally want to declare an array and let each element of the array represent one value within the range. (this applies to integer input). For example, in your case, if you want to find the frequency of the integer values entered by a user in the range of 0-99, you would declare an array with 100 elements (representing values 0-99) and initialize all values to 0.[1]
Then each time the user enters a valid value in the range, you increment that element. For example, if your user enters 58, you would increment array[58] = array[58] + 1; (or simply array[58]++;). The value of array[58] is now 1 indicating the user has entered 58 once. (if 58 was entered again, it would be 2, and so on...)
This lends itself nicely for your input loop. You simply declare say int x; and in your scanf call, you fill x, validate it is within the range and then array[x]++; For example with your numarray declared as int [100], you could do [2]:
#define NMAX 100 /* define constants, avoid 'magic' numbers in code */
...
for (;;) { /* loop until non-numeric encountered */
int x;
if (scanf("%d", &x) != 1) /* check for non-numeric */
break;
if (x < 0 || x >= NMAX) { /* validate value in range */
fprintf (stderr, "error: value outside of range -- "
"try again.\n");
continue; /* if out of range - get new number */
}
numarray[x]++; /* increment frequency at element x */
}
Now in your case the 0-99 exactly matches the zero-based array indexing used in C, but you can index any range simply by adjusting the indexes. For example, if you were interested in a range of 50-150 you would simply adjust the indexes as required (e.g. numarray[x-50]++;)
However, in your code, it is quite unclear what your actual intent is. For instance you ask for values between 0-99, but then declare numarray as a floating-point type. If your intent was to have the user enter whole number values, then your array type should be an integer type instead. That reduces to the classic frequency problem which you could handle simply in a manner similar to the following:
#include <stdio.h>
#include <stdlib.h>
#define NMAX 100 /* define constants, avoid 'magic' numbers in code */
int main (void){
int i, numarray[NMAX] = {0}; /* C favors all lower-case over
* camelCase variable names */
printf ("Enter any number of integers between 0 and 99 "
"followed a non-numeric: \n");
for (;;) { /* loop until non-numeric encountered */
int x;
if (scanf("%d", &x) != 1) /* check for non-numeric */
break;
if (x < 0 || x >= NMAX) { /* validate value in range */
fprintf (stderr, "error: value outside of range -- "
"try again.\n");
continue; /* if out of range - get new number */
}
numarray[x]++; /* increment frequency at element x */
}
for (i = 0; i < NMAX; i++) /* output frequency of values */
printf (" %2d : %d times\n", i, numarray[i]);
return EXIT_SUCCESS;
}
Example Use/Output
For example, you can generate 500 values between 0-99 and output the frequency for each of the 500 numbers generated with something similar to the following:
$ ./bin/freqarray < <(for i in $(seq 1 500); do
printf " %d" $(($RANDOM %100)); done; echo "done")
Enter any number of integers between 0 and 99 followed a non-numeric:
0 : 4 times
1 : 7 times
2 : 7 times
3 : 4 times
4 : 5 times
5 : 11 times
6 : 5 times
7 : 5 times
8 : 3 times
9 : 8 times
10 : 5 times
...
90 : 8 times
91 : 2 times
92 : 5 times
93 : 8 times
94 : 4 times
95 : 4 times
96 : 8 times
97 : 6 times
98 : 4 times
99 : 8 times
Handling floating-point values
Now if you truly wanted your user to enter floating-point values, e.g. 58.01831, 58.01826538, etc..., conceptually accounting for the frequency of each number isn't any difference, but the implementation is much more involved given the way floating-point numbers are stored in memory. See IEEE floating point and the numerous post on this site. The problems related to floating point storage and exact comparison of random user input can become fairly involved -- quickly. Even for the range of 0-99 there are literally 4e+18+ 64-bit values involved.
As noted in the second comment, one approach that can help is to hash the input values and store the hashed values in a hash-table to reduce the size of the array needed to track/store all values. You will have to balance precision you keep against storage size.
There is no way you could declare an array of 4e+18 elements. A hash table essentially provides a storage and lookup mechanism that can give you reasonable accuracy, and also provides a reasonable storage size. If the user enters 2-values that have the same hash a collision will be generated in your table, which you could use to indicate a duplicate entry. If that was your intent, then you will need to investigate the floating point hash functions available to meet your needs (which from your question, doesn't seem like what you intended, and it well beyond full-explanation here)
Look things over and let me know if you have any questions. If your intent was different, then please edit the question and I'm happy to work with you further.
footnote 1: choose an array type capable of holding the maximum number of entries you expect, e.g. each int element of the array can capture a maximum of INT_MAX, or 2147483647 repetitions (where an int is 32-bits)
footnote 2: C generally favors variable names of all lower-case, and avoids the use of camelCase or MixedCase variable names; reserving all upper-case for constants and macros. It is a matter of style -- so it is completely up to you.

How to get input for arrays whose length is not determined

I am supposed to write a program that "quicksort"s a given array of numbers. The problem is , dynamic memory allocation is not allowed and nor am I given the number of "numbers" that are supposed to be inputs of my program.
For instance, here's an input/output example:
INPUT: 0 1 5 3 6 2 4
OUTPUT: 0 1 2 3 4 5 6
But I just can't seem to be able to close my while loop when getting the numbers using scanf(); (I know , scanf() is silly , but I can't use "iostream" either)
Here's the code I was trying to get to work:
int main()
{
int target_arr[1000], l, h, i = 0, c = 0, k = 0;
while (scanf("%d", &target_arr[i]) != EOF)
{
i++;
}
h = i -1;
l = 0;
quick(l, h, target_arr);
print_arr(target_arr, i );
return 0;
}
quick() and print_arr() functions are previously defined and work perfectly well given the proper input.I just don't know how to stop the loop when I'm done inputting.
Any help would be greatly appreciated.

How to read a graph from console without knowing how many edges it has? [duplicate]

This question already has answers here:
How to read the standard input into string variable until EOF in C?
(5 answers)
Closed 9 years ago.
I have this graph (with the first line is number of vertices, the following lines are directed edges):
9
1 4
1 5
2 5
4 5
4 6
6 9
7 6
7 8
8 9
There is no information to know how many edges are in the input so can anyone suggest a way to read this kind of input?
Thank you you all,
I finally solved it, here is the input code:
while (1) {
tmp1 = scanf("%d", &x);
if (tmp1 == -1) // fix here
break;
tmp2 = scanf("%d", &y);
new_vertex = (Vertex *) malloc(sizeof(Vertex));
new_vertex->adj_vertex = NULL;
new_vertex->vertex_no = y;
new_vertex->time_stamp_visit = 0;
new_vertex->time_stamp_finish = 0;
last_vertex = getLastVertex((graph+x));
last_vertex->adj_vertex = new_vertex;
}
Loop over this list from 1 to n-1 read the pair and insert the edge between these two nodes in your graph data structure.
I advise reading this: http://shygypsy.com/iotutorial.html
And using the method under "Read integers, one at a time, skipping whitespace, until the end of input."
In your code maintain state on whether it's a beginning or a ending vertice being inputted.
Don't forget to press ctrl+d when done typing input.
You can use a "termination character" that counts as EOF, like a -1 or something after the last pair of nodes.
Then your data would be:
9
1 4
1 5
2 5
4 5
4 6
6 9
7 6
7 8
8 9
-1
And your code:
while(1){
scanf("%d %d", &num1, &num2);
if(num1==-1) break;
// process
}
I wrote getnum() to return an integer from stdin:
int getnum(int * last) {
int c, n = 0;
while ((c = getchar()) != EOF && 0x30 <= c && c < 0x40)
n = n * 10 + (c - 0x30);
if (last)
*last = c;
return n;
}
It will get digits from stdin until a non-digit character is retrieved. Because getnum() doesn't care what the non-digit character is, it doesn't matter how the numbers are arranged. They could all be on the same line, or in space-delimited pairs, one per line. I put this in a loop that stops once it reads in the right number of numbers, but you could easily loop until last pointed to non-whitespace.
Additionally, if you want to read from a FILE or fd (integer file descriptor), pass the FILE/fd to getnum() and use getc(FILE *)/fgetc(int).

Resources