Adding numbers until a negative is encountered - c

I'm trying to create a program that lets the user enter numbers(maximum entries>10^6) until a negative is encountered. I've tried a lot of version but they either don't register that a negative value is entered or they crash.
This is where I'm currently at:
#include <stdio.h>
#define HIGHEST 999999
int main(){
int i=0, entry, sum=0;
while(i<HIGHEST){
scanf("%i", entry);
if(entry>0){
sum+=entry;
}
else{
i=HIGHEST;
}
i++;
}
printf("Sum: %i", sum);
system("pause");
}

Your problem is on this line:
scanf("%i", entry);
Which should be:
scanf("%i", &entry);
You need to pass in the address of the integer variable that will store the scanned value. Since
entry was never initialized, it is just filled with garbage/whatever is in memory and not the entered value. See this reference, which states,
"Depending on the format string, the function may expect a sequence of additional arguments,
each containing a pointer to allocated storage where the interpretation of the extracted
characters is stored with the appropriate type"

You provide a way to leave if the entered number is too big:
while(i<HIGHEST){
But nothing to leave if it is less than 0; Try this:
while((i<HIGHEST)&&(i>=0)){
Additionally, #OldProgrammer is correct, your scanf() should be as he has pointed out.

Related

Infinite for loop? ()in c

the value of i resets after it reachers 7
#include <stdio.h>
int main(){
char marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
output
Problem is here:
scanf("%d", &marks[i]);
Specifier "%d" expects a pointer to int, not char. Usually it will write 4 bytes what is a typical size of int.
Therefore on 8th iteration the elements of marks at index from 7 to 10 are touched. However, marks[10] is outside of marks array (only indices 0-9) are valid. Undefined Behaviour is invoked and the program can do anything, from crashing to infinite looping or conjuring nasal deamons.
To fix the program change the type of marks to int:
int marks[10];
Note:
UB is invoked even on the first iteration because "%d" expects a pointer to int while type of &marks[0] is char*. This operation is undefined by C standard because int* and char* may differ in size and/or representation and/or alignment. However it is a unlikely case for modern CPUs.
You have declared the marks as a character array and tried to get input from user using %d which asks asks for an integer,
#include <stdio.h>
int main(){
int marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
Also I didn't understand the use of all so I couldn't find a solution for it. If you want to print a specific number then you have to specify it like you have done it for second or if you want to display the total you want to add a furthermore code to calculate the sum of elements in the array.

C - how to read input from text file to 2D array [duplicate]

Suppose,"5181 2710 9900 0012"- is a string of digits.I need to take one single digit at a time as input from the string of number without space to make arithmatic operations . So, i write that,
int a[20];
for(int i=0;i<16;i++)
{
scanf("%d",&a[i]);
}
but it didn't give me expected result. But when i use "%1d"instead of "%d",it gave me the expected result. so, how it works?
Since scanf is the inverse of printf, you could verify this by printing any number with the modifier (just a little tip).*
In general, the number before the format is a 'width' modifier. In this case it means you're only reading one byte into a number. If you specify %d, it may be a number of arbitrary length.
Example:
#include <stdio.h>
int main() {
int a;
sscanf("1234", "%d", &a);
printf("%d\n", a); // prints 1234
sscanf("1234", "%1d", &a);
printf("%d\n"m a); // prints 1
}
*) this appears to be false for this particular case. Makes sense that numbers are not truncated when specifiying a %d format, though, since that would change the meaning of the number. However, for many cases you could try what printf would do to predict scanf's behavior. But of course, reading the manual or docs on it is always the more helpful approach :)

How to take one character at a time as input from a string of characters without space in c?

Suppose,"5181 2710 9900 0012"- is a string of digits.I need to take one single digit at a time as input from the string of number without space to make arithmatic operations . So, i write that,
int a[20];
for(int i=0;i<16;i++)
{
scanf("%d",&a[i]);
}
but it didn't give me expected result. But when i use "%1d"instead of "%d",it gave me the expected result. so, how it works?
Since scanf is the inverse of printf, you could verify this by printing any number with the modifier (just a little tip).*
In general, the number before the format is a 'width' modifier. In this case it means you're only reading one byte into a number. If you specify %d, it may be a number of arbitrary length.
Example:
#include <stdio.h>
int main() {
int a;
sscanf("1234", "%d", &a);
printf("%d\n", a); // prints 1234
sscanf("1234", "%1d", &a);
printf("%d\n"m a); // prints 1
}
*) this appears to be false for this particular case. Makes sense that numbers are not truncated when specifiying a %d format, though, since that would change the meaning of the number. However, for many cases you could try what printf would do to predict scanf's behavior. But of course, reading the manual or docs on it is always the more helpful approach :)

c program giving 32767 for letters

My C program is giving the number "32767" when I enter a letter, but when I enter an integer it tells me the number that I entered.
why will my program not tell me what letters I entered? why is it giving me the number "32767"?
#include <stdio.h>
main()
{
int number;
printf("Enter an integer\n");
scanf("%d",&number);
printf("Integer entered by you is %d\n", number);
return 0;
}
If scanf doesn't find what it's looking for (in this case, an int), it will simply return without modifying whatever gets passed in. In other words, scanf won't change number, so it'll have it's old value, which, in this case, is undefined (since it's not initialized).
What you are seeing is "undefined behaviour", which pretty much means "anything can happen". The value in number, in particular, can have any value, because it has not been initialized. If you initialize it int number = 42; it will (probably) print 42, but I'm not sure that's guaranteed.
If you want printf() to display characters and scanf() to get that data, you must point that it's a character, using "char" instead of "int" and use "%c" instead of "%d".
Something like this (I still used the "number" variable and the description in the printf() about the " integer":
#include <stdio.h>
main()
{
char number;
printf("Enter an integer\n");
scanf("%c",&number);
printf("Integer entered by you is %c\n", number);
return 0;
}

C - error: ignoring return value of scanf?

I'm only a few days into C programming, so I am not quite sure what's wrong with this code:
#include <stdio.h>
int main(int argc, char * argv[]) {
int sides;
printf("Please enter length of three sides :\n");
scanf("%d", &sides);
return 0;
}
The error message I receive is as follows:
ignoring return value of scanf
What am I doing wrong here, and what can I do to fix it?
You might code
if (scanf("%d", &sides) >0) {
printf("you want %d sides.\n", sides);
}
else printf("You did not enter any number.\n");
The scanf function (please follow the link) has several roles
it is expecting some input and could modify the variables you passed by address to it
it is returning the number of successfully input items
It's a warning that stops your compiler from performing it's task (too strict settings). Check the return value of the scanf() function for errors and the warning should disappear.
Return Value
On success, the function returns the number of items
successfully read. This count can match the expected number of
readings or fewer, even zero, if a matching failure happens. In the
case of an input failure before any data could be successfully read,
EOF is returned.
scanf returns the number of "items", i.e. values passed both in the format string (a single item is e.g. %d, %c and so on), and in the subsequent arguments to scanf, for example, to read two integers separated by comma and space, you would use:
int x, y;
int items = scanf("%d, %d", &x, &y);
assert(items == 2);
I've already spoiled what my suggestion will be above - instead of adding unused variables, if you just want to read it, add an assertion:
#include <assert.h>
/* ... */
assert(scanf("%d", &sides) > 0);
/* ... */
Unfortunately, assert(scanf("%d", &sides)); is not enough, because of EOF (this will return -1). It would be really elegant.
I think this is the way to go, if you don't want to continue your program with an uninitialized variable (sides) in this case.
Alternatively, you can capture scanf's result to a variable, and handle it gracefully like in the other answers.
You don't capture the return value of scanf in a variable. It's a count (as an integer) of how many characters were read, so if that's important to you, then it may be good to capture it.

Resources