Looping for using while - c

Does anyone know what is the problem with this code? Even after inputting >1 line, the program will end prematurely at the end of the code without allowing the nested while to repeat. Thank you.
#include <stdio.h>
int main() {
int line;
unsigned int sum = 0;
int input;
float average;
printf("Enter number of input lines:");
scanf("%d", & line);
while (line > 0) {
while (input != -1) {
printf("Enter input line:");
scanf("%d", & input);
sum += input;
printf("sum is %d", sum);
printf("Line is %d", line);
}
line--;
printf("Line is %d", line);
}
return 0;
}

In your program the inner loop condition is based on the variable input. But it's value is set as -1 inside the inner loop before exiting the inner loop. But the value of variable input never changes once it becomes -1.
Modify as follows to enter the inner loop on each iteration of the outer loop,
printf("Enter number of input lines:");
scanf("%d",&line);
while (line>0) {
input = 0; /* This line is additional */
while (input != -1) {
printf("Enter input line:");
scanf("%d",&input);
sum += input;
printf("sum is %d",sum);
printf("Line is %d",line);
}
line--;
printf("Line is %d",line);
}

Related

How do i append proper input as integers to an array in C, as long the user wishes to?

int main(){
char answer;
int numbers[100];
int i = 0;
int size;
int max = -9999;
do{
printf("Please enter an number: ");
scanf("%d", &numbers[i]);
printf("Would you like to keep adding numbers:(Y/N)");
scanf("%c", &answer);
scanf("%c");
i++;
}while(answer == 'Y');
size = sizeof(numbers)/sizeof(numbers[0]);
for(int j = 0; j<size; j++){
if(numbers[j]>= max){
max = numbers[j];
}
}
printf("The max number is: %d", max);
return 0;
}
Hello beginner in C, here in my code i am trying to take an arbitrary amount of (the user enters Y if he/she wishes to enter another number.) input as integers and add them to an array and find the maximum of the input using a for loop, however i am not getting the correct output. What could be the error in my code?
Problems include:
Reading a '\n' when a letter is expected
scanf("%c", &answer); reads the character after the prior input of a number (example:9), which is likely the prior entry's '\n' Enter.
Use a space to consume leading white-space like '\n', space, tab, ...
// scanf("%c", &answer);
scanf(" %c", &answer);
Enable all warnings
Invalid/unnecessary code scanf("%c"); will raise a compiler warning with a well enabled compiler.
Best advice in this answer: enable all compiler warnings to save time.
Start at INT_MIN
The maximum input may be less than -9999.
INT_MIN in <limits.h>
// int max = -9999;
int max = INT_MIN;
Iterate to i
Rather than iterate to 100, only need to iterate to i, the count of values entered.
// for(int j = 0; j<size; j++){
for(int j = 0; j<i; j++){
Check return values
scanf() returns a value indicated the number of successful conversions. Use it to validated input successfully happened.
// scanf("%d", &numbers[i]);
if (scanf("%d", &numbers[i]) != 1) {
; // Report error with TBD code.
}
Do not loop too often
// } while(answer == 'Y');
} while(answer == 'Y' && i < 100);
There is no reason to save an array of values
The maximum could be calculated as data is entered.
int max = INT_MIN;
do {
int num;
printf("Please enter an number: ");
if (scanf("%d", number) != 1) {
break;
}
if (num > max) {
max = num;
}
printf("Would you like to keep adding numbers:(Y/N)");
if (scanf(" %c", &answer) != 1) {
break;
}
} while (answer == 'Y' || answer == 'y');
printf("The max number is: %d", max);
Future Improvements
Handle values outside int range. Research intmax_t.
Detect case of no valid input entered. Research fgets()
Detect non-valid Y/N input. Research fgets()
Recover, rather than quit loop with invalid input.

Fixing do-while loop problem and how to add do you want to play again?

I started C courses today and teacher assigned to do:
Guess the number and if the number is higher say it is higher but if it is lower say it is lower and count every time you guess AND if you guess it ten times already then say do you want to try again?
I don't know why my code is stop when I just play it only 1 time and how to do the "do you want to play again?"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int x;
char name[20], result;
int count = 0;
int number;
srand(time(NULL));
x = rand() % 100 + 1;
printf("What's your name :");
scanf("%s", &name);
printf("Hello!! %s\n", name);
printf("Guess the number : ");
scanf(" %d", &number);
do {
count++;
if (x > number) {
printf("This is your count : %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count : %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("\nYou're right!!, the number is %d",x);
}
} while (count == 10);
}
The code allows only 1 try because the test while (count == 10) is false at the end of the first iteration. You should have while (count < 10).
You should move the input call scanf(" %d", &number); inside the loop.
Also note that you should break from the loop if the number was found.
For the Do you want to play again? part, you could wrap this code in another loop.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char name[20] = "", ch;
srand(time(NULL));
printf("What's your name: ");
scanf("%19s", &name);
printf("Hello!! %s\n", name);
for (;;) {
int x = rand() % 100 + 1;
int number;
for (int count = 1; count <= 10; count++) {
printf("Enter your guess: ");
if (scanf(" %d", &number) != 1)
break;
if (x > number) {
printf("This is your count: %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count: %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("You're right!!, the number is %d\n",x);
break;
}
}
printf("Do you want to play again? ");
if (scanf(" %c", &ch) != 1)
break;
if (ch != 'y' && ch != 'Y')
break;
}
return 0;
}
The loop condition in the line
} while (count == 10);
is wrong, because it will be false after the first loop iteration. It would be more meaningful to write
} while (count < 10);
Also, you probably want to put the lines
printf("Guess the number : ");
scanf(" %d", &number);
inside the loop, so that they get executed more than once. Otherwise, you will be processing the same user guess 10 times, which is not what you want.
Another issue is that you don't want the loop to always run 10 times. You only want it to run 10 times if the user hasn't guessed the number. If the user has guessed the number, you want to break out of the loop immediately, without waiting for count to reach 10. For this, you can use the break statement.
I'm a VB guy mostly but can you use while count <= 10?
Perhaps Do Until?

Why my program in c keeps looping and not storing values in memory?

I am a beginner in C programming and I am stuck in my little program .
I just wanna make a list from which I ask users to select a number from that list. Then the program should do what it should be done.
My list is:
Create a table
Max & Min Number Checking
Negative & Positive Number Checking
Ascending Order
Descending order
Exit
I couldn't start correctly! When I first press 1 to create the table, the program keeps looping again and again!!
I want my program to ask me for some values then take my value and draw me a table and then store these values temporary in memory, so that I can execute the rest of commands from my list.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t[100],n,a,f,s=0,i,max,min,m,l;
{
printf("Welcome to My simple Math Program in C language \n");
printf("1:Create a table\n 2:Max&Min Number Checking\n 3:Negative&Positive Number Checking\n 4:Ascending Order\n 5:Descending ordert\n 6:Exit\n ");
printf("Please Choose a number from the list" );
scanf("%d",&a);
while(a!=6){
switch(a){
case 1:printf("Please Enter The Length Of Your Table ");
scanf("%d",&n);
printf("Please Enter Your Table Elements ");
for(int i=0;i<n;i++){
scanf("%d",&t[i]);
}
for(int i=0;i<n;i++){
printf("%d ",t[i]);
}
break;
case 3:
if(t[i]<0){
printf("This Number is Negative %d",t[i]);
}
else if(t[i]==0){
printf("This Number is nulle %d",t[i]);
}
else
{
printf("This Number is Positive %d",t[i]);
}
;break;
case 6:
break;
}
}
return 0;
}
}
Your scanf() statement is outside your while loop so it is only executed once. You need something like this:
do
{
scanf("%d",&a);
...rest of code
} while (a!=6)
You should print the message and read the option inside the main loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int t[100], n, a, f, s = 0, i, max, min, m, l;
printf("Welcome to My simple Math Program in C language\n");
for (;;) {
printf("1: Create a table\n"
"2: Max&Min Number Checking\n"
"3: Negative&Positive Number Checking\n"
"4: Ascending Order\n"
"5: Descending ordert\n"
"6: Exit\n");
printf("Please Choose a number from the list: ");
if (scanf("%d", &a) != 1) /* invalid input */
break;
if (a == 6)
break;
switch (a) {
case 1:
printf("Please Enter The Length Of Your Table ");
if (scanf("%d", &n) != 1)
break;
if (n > 100)
n = 100;
printf("Please Enter Your Table Elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &t[i]);
}
for (i = 0; i < n; i++) {
printf("%d ",t[i]);
}
break;
case 3:
i = 0;
if (t[i] < 0) {
printf("This Number is Negative %d\n", t[i]);
} else
if (t[i] == 0) {
printf("This Number is null %d\n", t[i]);
} else {
printf("This Number is Positive %d",t[i]);
}
break;
}
}
return 0;
}

C: With one variable entered wrong, my "incorrect input" if kicks in and doesn't let the user to finish typing in rest of variables

The problem is, basically, that if user enters a:5, b:f, everything works fine. But if it's the other way around and enters a letter to the 'a' variable, the program ends saying "Incorrect input", not letting the user to finish typing in rest of the variables. Why? Is it because of how I dealt with checking if the input is correct in the first place? How to "delay" the message and make it show after user finishes entering variables?
Here's the code:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
As Weather Vane already pointed out, the reason the program exits is, that when you enter a character (%c) and the scanf function is waiting for a integer (%d) it ignores the char, doesn't find an int but ends its' search on the '\n' (enter), so your variable l1 stays 0. This happens for all of your scanf calls, as it doesn't clear the buffer from characters that don't match.
Solving this
You can clear the input buffer, so that all the other scanf calls can get an actual input, though, you are still going to get an "Incorrect input" at the end.
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
printf("Number b: ");
l2 = scanf("%d", &b);
while (getchar() != '\n');
If you want to repeat the input process until a user enters the numbers correctly, you have to check the return value of the scanf in a while loop, something like this:
do {
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
} while (l1 != 1 || l1 != EOF);
Try this:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
getchar();
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
Reference : scanf() leaves the new line char in the buffer

Infinite while loop not waiting for scaning data again in C

#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf(" %d", &i) > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
}
}
I want to continue the scan again if user entered a value other than integer when I run the above code with a char input it is running infinite loop. Please suggest why or any solution ...?
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf_s(" %d", &i) > 0) { // step-2
printf("Num=%d\n", i);
break;
}
else {
printf("Entered character.Pls enter int\n");
fseek(stdin, 0, SEEK_END);
}
}
}
If you enter a character say a for the above program it will not match with %d so it will remain in the buffer. The next time in the loop, it will again not match %d and you will enter an infinite loop.
What you can do, is read from the buffer until you encounter a newline character. The second loop will remove any characters until and including the newline character.
#include <stdio.h>
int main() {
int i;
char dummy;
while (1) {
printf("Enter no?\n"); // step -1
scanf(" %d", &i)
if (i > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
do{
scanf("%c",&dummy);
}while (dummy != '\n'); // Add this loop
}
}

Resources