I can't figure out the problem in this:
#include<stdio.h>
int main()
{
int a,b,count ;
count =0;
printf("enter the value for a ");
scanf("%d ",&a);
while(a>0)
{
b=a%10;
count=b+count;
a=a/10;
printf ("hence the simplified result is %d",count);
}
return 0;
}
There's a silent killer in your code:
scanf("%d ",&a);
The extra space in your scanf will make entering numbers harder: this will match 12<space>, but not 12. Replace the "%d " with "%d".
You do not terminate your printf() with a "\n". The output stream (stdout) is, usually, line buffered. That means that incomplete lines need not be printed unless you force them with fflush(). But there's no need for that.
Simply add a "\n" to your printf()
printf("hence the simplified result is %d\n", count);
One issue is you print the count with every loop, rather than than after the loop.
Not an issue, but C has arithmetic assignment (aka compound assignment) operators that can be more readable. For example, a /= 10 is equivalent to a = a/10.
I think the printf statement should be outside the loop.
Move the printf out side the loop. That will fix it.
Try the following:
#include<stdio.h>
int main()
{
int a,b,count ;
count =0;
printf("enter the value for a ");
scanf("%d",&a);
while(a>0)
{
b=a%10;
count=b+count;
a=a/10;
}
printf ("hence the simplified result is %d",count);
return 0;
}
Related
I am trying to dynamically initialize an array, but when I enter the while loop the first time printf prints the statement, but the next printf statement doesn't execute unless I put another value. I want to put values between
0--->n-1
First time printf statement executed but the 2nd time does not execute unless I enter any value. tried to enter 5 for the size, and put 0,1,2,3,4 for the values.
#include <stdio.h>
#include <malloc.h>
void main() {
Ex5();
system("pause");
}
void Ex5()
{
int size_a,n_res=0,res=0;
int *arr_a = input_array_dyn(&size_a);
res = includes(arr_a, size_a);
printf("res is %d ", res);
free(arr_a);
}
int* input_array_dyn(int *size) {
int i=0, *p_to_arr;
printf("enter size of arr:");
scanf_s("%d", size);
p_to_arr = (int*)calloc(*size,sizeof(int));
while(i<*size) {
printf("enter %d element", i);
scanf_s(" %d ", &p_to_arr[i]);
i++;
}
return p_to_arr;
}
The format string in
scanf_s(" %d ", &p_to_arr[i]);
is troublesome and could possibly be the cause of your problem.
The problem with the format string is the trailing space. The trailing space means that scanf_s will read all trailing space characters, until there are no more spaces. The problem is that for scanf_s to know there are no more spaces, you must enter some non-space input.
This leads to scanf_s blocking until you write a second input.
The solution is to not have any spaces in the format string at all:
scanf_s("%d", &p_to_arr[i]);
The leading space isn't needed either, as the "%d" specifier will skip leading space automatically.
If I understand you correctly, changing the format of the second scanf to "%d" should help. I've tested it locally and I'm able to enter all the values at once.
I have to create a program that requests integer numbers from the user
repetitively though the keyboard until the user enters 0. I've gotten to the while loop and its not repeating and I'm not sure why. Any help would be greatly appreciated.
Thanks
Edit: I've fixed the loop in terms of it not repeating but now it's infinitely repeating and I have no clue why.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char first[30], last[30];
int n, even, odd, etotal = 0, ototal = 0;
printf("What is your first name?\n");
scanf("%s", &first);
printf("What is your last name?\n");
scanf("%s", &last);
// asks for name
printf("Enter a number\n");
printf("To quit the program enter 0\n");
scanf("%d", &n);
while (n!=0){
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++; }
}
return 0;
}
The loop isn't repeating because you have a return statement in the loop, that will leave the main function immediately. Just remove it.
You also have another problem that's much worse: Undefined behavior. Local non-static variables, like for example n in your code, don't get initialized, instead they have an indeterminate value. Attempting to use such an uninitialized variable leads to said undefined behavior.
You need to explicitly initialize the variable to some value before using it in the condition, for example to reorder the code so you read input before the loop and then also at the end of the loop.
Local variable n is uninitialized producing undefined results collaboratively called undefined behavior. Initialize it before entering loop:
n = 1;
And check result of scanf:
if (scanf("%d", &n) != 1)
// error
Because n is not initialized, so it has a random value:
int n, even, odd, etotal, ototal;
/* ... */
while (n!=0){
Loop is not working because you didn't initialize n and unnecessary return 0 inside the while loop. You can fix it with do..while as below. Because you have the input statement as your first statement, do..while is best opted here.
do{
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++;
}
else {
printf("%d is odd.\n",n);
ototal++;
}
} while (n!=0);
You use scanf to read your input, but after your if/else statement you are returning 0 hence you are leaving the program. So it doesnt matter if you write an even or an odd number.
while (n!=0){
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++;
}
return 0;
}
#include <stdio.h>
int main()
{
int m,i,sum,num;
i=0;
sum=0;
scanf("%d ",&m);
while(i<m){
scanf("%d ",&num);
sum=sum + num;
i=i+1;
printf("Value of sum= %d\n",sum);
//continue;
}
printf("Sum= %d ",sum);
}
In the above code it should display the sum of n numbers. But in my code it is taking one extra value of m (m is number of values to take to compute the sum).
For example if I take m as 3 it takes 4 input and displays the sum of 3.
As others(#BLUEPIXY and #BillDoomProg) have already pointed in the comments, your problem is the space in your scanf format string. Also check this answer.
Change both your scanf format string from:
scanf("%d ",&m);
...
scanf("%d ",&num);
To:
scanf("%d", &m);
...
scanf("%d", &num);
Just remove the space and it will work fine.
scanf()
From the manual
The format string consists of a sequence of directives(...)
A directive is one of the following:
A sequence of white-space characters (space, tab, newline, etc.; see
isspace(3)). This directive matches any amount of white space, including
none, in the input.
Also note that stdin is buffered, so the results are a little different from what you would expect:
man stdin
Notes
The stream stderr is unbuffered. The stream stdout is line-buffered when
it points to a terminal. Partial lines will not appear until fflush(3) or
exit(3) is called, or a newline is printed. This can produce unexpected
results, especially with debugging output. The buffering mode of the
standard streams (or any other stream) can be changed using the setbuf(3)
or setvbuf(3) call. Note that in case stdin is associated with a terminal,
there may also be input buffering in the terminal driver, entirely
unrelated to stdio buffering. (Indeed, normally terminal input is line
buffered in the kernel.) This kernel input handling can be modified using
calls like tcsetattr(3); see also stty(1), and termios(3).
So, lets examine your program step by step.
Your program starts running and you enter the number 2. This is what the input buffer looks like:
2\n
scanf("%d ", &m) assigns 2 to the m variable and starts trying to match a space. It gets a NL and EOL. Control is still with this scanf because it just matched a newline (considered a white-space) and is waiting to match more, but instead it got the End-Of-Line, so it is still waiting when you type:
1\n
Then reads stdin again and realizes that the next character in the input stream is not a space and returns (it's format string condition was done). At this point, you enter the loop and your next scanf("%d ",&num) is called and it wants to read an integer, which it does: it reads 1 and stores that in the num variable. Then again it starts matching white-spaces and gets the new-line and it repeats the above pattern. Then when you enter:
2\n
That second scanf gets a character different than a white-space
and returns, so your loop scope keeps executing printing the current sum.
The loop break condition is not met, so it starts again. It calls the
scanf and it effectively reads an integer into the variable, then the
pattern repeats itself...
3\n
It was waiting for a white-space but it got a character instead. So your
scanf returns and now the loop break condition is met. This is where you exit your loop, prints the whole sum and get that weired felling that it
"added" 3 numbers but the sum is adding only the first 2 (as you intended
in the first place).
You can check that 3 hanging in stdin with a simple addition to your code:
#include <stdio.h>
int main()
{
int m, i, sum, num;
char c;
i = 0;
sum = 0;
scanf("%d ", &m);
while (i < m) {
scanf("%d ", &num);
sum = sum + num;
i = i + 1;
printf("Value of sum= %d\n", sum);
}
while((c = getchar()) != '\n')
printf("Still in buffer: %c", c);
return 0;
}
That will output (with the above input, of couse):
$ ./sum1
2
1
2
Value of sum= 1
3
Value of sum= 3
Still in buffer: 3
This is because you have a space after your %d in the scanf lines.
Change
scanf("%d ",&num);
To
scanf("%d",&num);
Scanf usually ignores whitespaces, so you don't want spaces in your format strings.
It's causes of extra space in scanf(). Change scanf("%d ",&num) to scanf("%d",&num)
From Scanf(), fscanf(), You can follow this.
The scanf() family of functions reads data from the console or from a
FILE stream, parses it, and stores the results away in variables you
provide in the argument list.
The format string is very similar to that in printf() in that you can
tell it to read a "%d", for instance for an int. But it also has
additional capabilities, most notably that it can eat up other
characters in the input that you specify in the format string.
You should write:
int main()
{
int m,i,sum,num;
i=0;
sum=0;
scanf("%d",&m);
while(i<m){
scanf("%d",&num);
sum=sum + num;
i=i+1;
printf("Value of sum= %d\n",sum);
//continue;
}
printf("Sum= %d ",sum);
}
A refactored code will look like this
#include <stdio.h>
int main() {
int m, num, sum = 0;
scanf("%d", &m); // Let scanf automatically skip whitespace
while (m--) {
scanf("%d", &num);
sum += num;
}
printf("Sum= %d\n", sum);
return 0;
}
So I'm trying to find the sum of an unknown amount of user-input numbers. Here's my code
int main()
{
int tmp1 = 1;
int tmp2 = 1;
int total = 0;
printf("Enter numbers for a sum: ");
tmp2 = scanf(" %d", &tmp1);
while(tmp2 > 0){
total+=tmp1;
tmp2 = scanf(" %d", &tmp1);
}
printf("total is %d", total);
return 0;
}
It gets stuck in an endless loop, and then once i hit ctrl-c to end it, it prints the correct sum. So what I'm doing wrong is how will i know when it's done scanning all the integers, and for the loop to end; since i'm not doing it correctly now
Decided to make it stop via ctrl d, and its acceptable. thanks
In your question, it is not clear how you expect your programme to understand that there won't be anymore numbers to input. Shall it be through a specific character? Or shall it just get a line of space-separated numbers and respond with a sum?
From your code, my most sensible guess is: You want it to understand that there won't be any more numbers to add, whenever it encounters a non-digital character. My guess is so, because this is almost exactly what your code does by checking the return value from scanf.
First of all, you have to change that tmp inside your loop into tmp1 because there isn't such a variable as tmp declared. edit: well, never mind
Then try running your programme, putting in any amount of white-space (space, tab or new-line) separated numbers, and then any non-digital character you like. May be a T for example, or ThoAppelsin, it won't matter. Programme won't get beyond the first character, in fact, not even beyond the first character. After that, you shall see that the numbers have been properly added together.
Since you're confused about a non-existent infinite-loop, my second guess is that you might be actually hoping it to get a single line of space-delimited numbers, and have the sum printed; and misinterpret your programme as "in infinite loop" while it merely expects further input from you, just like it does at the very beginning.
You won't get a 0 from non-redirected scanf("%d", &var);, unless you feed it with something that doesn't match to the format string to cause abnormal termination. If there's nothing left in the input stream to consume, it will just wait for more input. But say you give an 'a' to it, then all it can do is to give up and return zero, because it couldn't do a single assignment.
If you really are hoping to have a single line of numbers, then the minimal change I could offer would be something like this:
int main(void)
{
int tmp1 = 1;
char tmp2 = 0;
int total = 0;
printf("Enter numbers for a sum: ");
scanf("%d%c", &tmp1, &tmp2);
while(tmp2 == ' '){
total+=tmp1;
scanf("%d%c", &tmp1, &tmp2);
}
printf("total is %d", total);
return 0;
}
Of course, this approach has many vulnerabilities. However, if user is to input strictly a sequence like:
3 66 2 10 6
// mind the new-line
It will work fine. But if I'm allowed to change more than minimal, this is how I would do it:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
int LastNumber = 0;
int UpcomingCharacter = 0;
int Total = 0;
printf("Enter numbers for a sum: ");
while(scanf("%d%*[ \t]", &LastNumber) == 1)
{
Total += LastNumber;
UpcomingCharacter = getchar( );
if (!isdigit(UpcomingCharacter)) // eliminates a possible EOF return as well
break;
if (ungetch(UpcomingCharacter, stdin) != UpcomingCharacter)
{
fprintf(stderr, "%d: unexpected error with ungetch\n", __LINE__);
return EXIT_FAILURE;
}
}
printf("total is %d", Total);
return EXIT_SUCCESS;
}
Which should work fine on any whitespace-delimited sequence of numbers, excluding the new-lines of course.
Here is a program to find prime numbers using sieve of Eratosthenes. The program is compiling but on execution, it becomes non responsive.The print statement itself is not executed. Can I know where I have gone wrong?
#include<stdio.h>
int main()
{
printf("Enter the range");
int n,i;
scanf("%d",&n);
int j;
int a[--n];
for(i=0;i<n;i++)
a[i]=i+2;
for(i=0;i<n;i++)
if(a[i])
{
printf("%d",a[i]);
for(j=2;(i*j)<n;j++)
a[i*j]=0;
}
return 0;
}
Thanks
Your program is infinite looping the first time through the loop.
When i = 0 this loop never ends:
for(j=2;(i*j)<n;j++)
Your printf call might be being buffered which means it might not actually be printed until the buffer fills up or a newline is encountered.
Try adding a newline to the end of your string or call fprintf(stderr, ...) instead (which isn't buffered).