C Program - Do - while loops not working - c

My target output is after users entering a number >2 & <20 (result show) then program continue asking users enter another number. Or if users enters number <=2 or >=20, it will not show result but just re-asking users to enter number.
My Current Output: If I input number <=2 || >=20, it will re-ask. but if I enter number between 2 and 20. It will just stops which suppose to be keep asking for entering new numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 20
int main(void)
{
unsigned int random_array[MAX][MAX];
unsigned int r, c, x, y;
do {
printf("Number Matrix in array ? ");
scanf("%d", &c);
system("cls");
r = c;
if (c>2 && c<20) {
r = c;
for (x = 0; x <= r - 1; ++x)
{
for (y = 0; y <= c - 1; ++y)
{
random_array[x][y] = -1;
}
}
for (x = 0; x <= r - 1; ++x)
{
for (y = 0; y <= c - 1; ++y)
{
if (x == y)
random_array[x][y] = 0;
else
if (x<y)
random_array[x][y] = 1;
printf("%4d", random_array[x][y]);
}
puts("");
}
system("pause");
}
} while (c<=2 || c >=20);
return 0;
}

Since you want to prompt the user for input regardless of what they last input, you probably need an infinite loop. For this, replace your line with the while condition to this:
} while (1);
This basically tells your program to loop infinitely.

Your codes
do
{
// show something
} while (c<=2 || c >=20);
means that it will stop after showing something if (c > 2 && c < 20), and that is exactly why your program quits after the condition is met.
To achieve your goal, consider using an infinite loop, and do different things using if-else inside the loop.
printf("Number Matrix in array ? ");
scanf("%d", &c);
system("cls");
if (c<=2 || c >=20)
{
continue;
}
else
{
// show something
}

The while condition should be while(c>2&c<20). But if you enter a number <=2 or >=20 the program will end and will not ask you for an input anymore. So the solution would be to use an infinite while loop and use break to end the loop when you want by using a condition.

A do-while loop will run the block of code once, then will repeat until the while conditional evaluates to false.
do{
//Stuff
}while (c > 20 || c < 2);
That would do the //Stuff part once, then it would do it again until c is either greater than 20 or less than 2.
What you want to do is surround the entire thing in an infinite loop, (either for(;;) or while(1)) so that it continues regardless.
But you also want to validate the input, so that's when you could use a do-while loop. When you're getting the scanf, you could do something like:
do{
printf("Enter c: ");
scanf("%d", &c);
}while (c > 20 or whatever);
Then you could make him keep putting in c until it's the desired input!
Hope this helps.
EDIT: Here's an example of putting the do-while inside the while:
while(1){
do{
printf("Enter a positive number: ");
scanf("%d", &aNum);
}while(aNum < 0);
printf("Your positive number is %d.\n", aNum);
}
That would ask a user for input, and if he puts in a negative number it would ask him again. If it's a positive number it would print, then go back to the start and ask him for an input again.

Related

Why does my program print something before it ends when I press ctrl + D?

So I wrote a simple program that converts a decimal to binary, that only accepts positive whole numbers. So numbers like -2 and 1.1 would output "Sorry, that's not a positive whole number." It infinitely asks the user to input a number until the user presses ctrl + D. However when I tested it it prints out the "Sorry..." statement before it ends the program.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
void DecToBin(int userInput){
int binary[32];
int i = 0;
while (userInput > 0) {
binary[i] = userInput % 2;
userInput /= 2;
i++;
}
for (int j = i - 1; j >= 0; --j) {
printf("%d", binary[j]);
}
}
int main(void) {
double userDec;
int temp;
printf("Starting the Decimal to Binary Converter!\n\n");
while(!feof(stdin)) {
printf("Please enter a positive whole number (or EOF to quit): ");
scanf("%lf", &userDec);
temp = (int)(userDec);
if ((userDec > 0) && (temp / userDec == 1)) {
printf("\n\t%.0lf (base-10) is equivalent to ", userDec);
DecToBin(userDec);
printf(" (base-2)!\n\n");
}
else {
printf("\tSorry, that was not a positive whole number.\n");
}
}
printf("\n\tThank you for using the Decimal to Binary Generator.\n");
printf("Goodbye!\n\n");
return 0;
}
(All the tab and newlines are just how it's supposed to be formatted so don't pay attention to that)
So from what I'm understanding, my program reads ctrl + D as the else in my while loops. So, any idea why that is?
It seems like you think C-d would trigger some kind of break in the code. Like the keyword break. This is not true.
Read this post to see what's happening when you press C-d: https://stackoverflow.com/a/21365313/6699433
That does not cause anything special to happen in the C code. scanf will simply not read anything. After the scanf statement, the code will continue as usual, so the code WILL unconditionally enter the if statement.
This is also a pretty severe thing, because you'll be using userDec uninitialized. scanf returns the number of successful assignments, and you should always check the return value. So in your case you want this:
if(scanf("%lf", &userDec) != 1) { /* Handle error */ }
Because if scanf does not return 1, userDec is unassigned.
To achieve what you want, simply do this:
if(scanf("%lf", &userDec) != 1)
break;

How to limit an integer's input to 2-12 only?

I want to strictly limit a user's input on an integer in this program to 2-12 only. How do I do that?
#include <stdio.h>
int main(){
int i;
scanf("%d", &i);
int diceThrown, diceResult;
int sum = 0;
for(diceThrown = 1; diceThrown <= i; diceThrown++){
scanf("%d", &diceResult); //limit this input to 2-12 only, how?
sum += diceResult;
}
if(sum >= 40){
sum = sum % 40;
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
} else if(sum < 40){
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
}
return 0;
}
Also just to clarify, that I'm still a beginner in programming (like only 2 months into C.SCi course), so if you could explain it to me like I'm not a expert that would be great.
scanf has no functionality to do what you want. You can just use an if to validate input.
if(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//handle invalid input here
}
If the input is invalid it is up to you what you want to do. You could ignore the input and ask the user to enter a valid number, you can quit the whole program or just ignore the error, or something else entirely.
You can also check the input repeatedly with an while:
while(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//prompt user to enter valid input here
}
As mentioned by chux, part of handling invalid input would be to cosume the invalid input and check for EOF.
The scanf("%d", &diceResult) != 1 will assure, that scanf actually read exactly one number and no parsing errors occurred.
Consider this:
#include <stdio.h>
int main(){
int x;
do
{
printf("give a number between [2-12]\n");
scanf ("%d",&x);
}
while(x<2 || x>12);
return 0;
}
You can use a do-while loop so that you only take the values that are between the 2-12 range. That way you can force the user to give an integer as an input that is in the range that you ask for, in that case from [2,12]. Otherwise the program will turn back and request a valid input again.

How to make a program restart infinitely using while loops in C

I am a beginner at learning C language, I have an assignment asking me to write a program that determines whether the data inputted by user makes sense as triangle sides or not.
If it is, I have to determine the type of the triangle, and if it is not, an output such as "It is not a triangle" should be written.
I have to use a while loop for this purpose, and not allowed to use do while.
So that's what I've coded. I'm using DevC++ program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a;
int b;
int c;
printf("Enter the first side:\n");
scanf("%d", &a);
printf("Enter the second side:\n");
scanf("%d", &b);
printf("Enter the third side:\n");
scanf("%d", &c);
while ((a > 0) && (b > 0) && (c > 0))
{
if (((a + b) > c) && ((a + c) > b) && ((b + c) > a))
{
if ((a == b) && (b == c))
{
printf("That is an EQUILATERAL triangle\n");
break;
}
if ((a == b) || (b == c) || (a == c))
{
printf("That is an ISOSCELES triangle\n");
break;
}
else
{
printf("That is a SCALENE triangle\n");
break;
}
}
else
{
printf("That is not a TRIANGLE.\n");
break;
}
return 0;
}
Now the problems I have are; I am asked to make the program restarts (repeats) itself after each time we have the decision if it is a triangle or not, but I don't know how. This "break" statement that I have written does not work and I think it is not necessary am I right? Also there is this error that comes out when I check my code
D:\Homework1.c [Error] expected declaration or statement at end of input
Could you help me please?
Edit1: Simply and specifically, the loop should always be repeated unless the input numbers are not 0 or (-). So users will always be able to re-enter values if they are not 0 or negative ( And actually that's the loop main condition)
Edit2: I corrected missing } and ((b + c) > c) errors so thank you all.
I do not see a closing brace } at the end of your main (i.e. after return 0). This might be a reason for your compilation error.
here you can go for many ways...
1.Use label,goto
2.Go for functions
3.Avoid break;
4.Alter the code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int flag=1;//for handling while loop
while (flag)
{
//call a function to input
//call a function to process
//call a function to output
//flag = get input to repeat(1) or finish (0)
}
return 0;
}
Dont use while loop for checking >0 condition. It is of no use.
Here you use if-else, so break condition is not required.
Handle <0 condition also.
Simply create a loop, while in your case with an endless condition to run. Endless at first but give the ability to the user to be able to terminate the loop.
Read your user input at the start of the loop.
Process the input, so decide if its a triangle and give an output to the user
Ask the user if she/he wants to exit or rerun.
#include <stdio.h>
int main()
{
int exit = 0; // surly you want to exit sometimes
int a;
int b;
int c;
while(!exit)
{
// Get your input
printf("Enter the first side:\n");
scanf("%d",&a);
printf("Enter the second side:\n");
scanf("%d",&b);
printf("Enter the third side:\n");
scanf("%d",&c);
// check your input, process data if it is a triangle, give output
// your code here
printf("a:%d b:%d c:%d\n", a, b, c); // test code of mine
// ask if the user wants to rerun
printf("Exit? Yes(1) No(0):\n");
scanf("%d",&exit);
}
return 0;
}
Just use while(1) loop, do your inputs and checks in it and after each result use continue

End while loop with ctrl+d, scanf?

I want the user to be asked "how many circles" they wanna write until the user decides to end it with (Ctrl+d) which is EOF?
extra question: if I write a letter for example "k" it will spam out circles. How do I change that?
#include <stdio.h>
int main ()
{
int i;
int x;
printf("\nHow many circles do you want to write?\n");
scanf("%d", &x);
while(x != EOF)
{
for (i = 1; i <= x; i = i + 1)
{
putchar('o');
}
printf("\nHow many circles do you want to write?"
"(to end program click ctrl+d at the same time!))\n");
scanf("%d", &x);
}
printf("\n\n Bye! \n\n");
return 0;
}
The biggest problem with your program is that scanf will not read an EOF into a variable. However, fixing just this problem is not going to make your program entirely correct, because there are other issues in your code:
Your code repeats itself - when possible, you should unify the code that deals with the first iteration vs. subsequent iterations.
Your code will not handle invalid input - when an end-user enters non-numeric data, your program goes into an infinite loop.
Your code follows the old style of C - declaring all variables at the top has not been required for more than fifteen years. You should declare your loop variable inside the loop.
Here is how you fix all these shortcomings:
int x;
for (;;) {
printf("\nHow many circles do you want to write? (to end the program click Ctrl+D at the same time!)\n");
int res = scanf("%d", &x);
if (res == EOF) break;
if (res == 1) {
... // Draw x circles here
} else {
printf("Invalid input is ignored.\n");
scanf("%*[^\n]");
}
}
printf("\n\n Bye! \n\n");
return 0;
As per the man page, scanf() will return EOF, not scan EOF to x as a value.
Return Value
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs......
Also,
if I write a letter for example "k" it will spam out circles, how do I change that?
In case of input of one char value, it causes matching failure, in your case, scanf() returns 0, instead of 1.
So, altogether, you've to collect the return value of scanf() and check check that value for the required condition. You can change your code as
int retval = 0;
while ((retval = scanf("%d", &x))!= EOF && (retval == 1))
if you're allowed to #include , there are two convenient functions bool kbhit() and char getch().
So you can write
char c=0;
if(kbhit()) c = getch();
if(c== whatever code ctrl+d returns) x=EOF;
Hint: Take a look at what scanf(%d,&x) returns when you enter a letter instead of a number.
You can read char by char input :
#include <stdio.h>
int main ()
{
int i;
int x = 0;
int nb = 0;
while(x != EOF)
{
printf("\nHow many circles do you want to write?\n");
nb = 0;
for (x = getchar(); x != '\n'; x = getchar()) {
if (x == EOF)
goto end;
if (x >= '0' && x <= '9') {
nb = nb * 10 + x - '0';
}
}
for (i = 0; i < nb; i++)
{
putchar('o');
}
}
end:
printf("\n\n Bye! \n\n");
return 0;
}

C-Code...trying to combine a while loop with an OR operator to check if the input number is prime or not

Hey guys so this is the ques which i have coded but its not working properly..i cant seem to understand where am i going wrong..
Write a program that determines if a number that the user has entered is a prime
number. The program will continue to ask for numbers until the user enters a
value less than 2.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int num;
int count = 1;
bool check = true;
do{
printf("Enter a number: ");
scanf("%d", &num);
count = num - 1;
bool check = false;
while (count > 1 || num % count == 0){
check = true;
count--;
}
if (check == true){
printf("%d is a prime number\n", num);
}
else
printf("%d is not a prime number\n", num);
}
while (num > 2);
}
while (count > 1 || num % count == 0){
check = true; // <-
count--;
}
On the indicated line you set check to true - this means that if the body of the loop executes even once, check will be true after the loop and the program will indicate that the number is prime. What you should do instead is show the number as prime iff the entire loop runs to completion.
The loop condition is also wrong; num % count == 0 indicates that the number is not prime, so you can stop checking if that is true. (Hint: you can terminate the loop from within using break)
Also if the user enters 2 or less, the checks will still run before the outer loop terminates.
You'll want your while loop to look like this:
bool prime = true;
while (count > 1 && prime) {
prime = ((num % count) != 0);
count--;
}
The way you wrote it will assign check to true on the first iteration, regardless of num's primality.
Say
int num = 3;
or whatever number you want bigger than 2
instead of
int num;
This is to make use you enter the loop.

Resources