How to make a program restart infinitely using while loops in C - 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

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;

Guess a person's secret number between 0 - 100 using binary search

I converted a code that I know how to construct in python in C Language, but everytime I run the program in CodeBlocks, the program crashes! And I have NO idea why this is happening, can someone help me?
The program is suppose to guess a person's number (between 0 - 100), using binary search.
For example, if my number is 66, the program asks if my number is 50, since 66 is higher than 50, the number 50 becomes the lower boundary while 100 remains to be the higher boundary, and so on...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int x;
printf("Please think of a number between 0 and 100\n\n");
x = binarysearch();
printf("%d", x);
}
int binarysearch()
{
int hi,lo,guess;
hi = 100;
lo = 0;
char user_inp;
while (1){
guess = round(((hi + lo)/2));
printf("Is your secret number %d?\n\n", guess);
printf("Enter 'h' to indicate the guess is too high. \nEnter 'l' to indicate the guess is too low.\nEnter 'c' to indicate I guessed correctly. \n");
scanf("%c", &user_inp);
if (strcmp(user_inp, "c") == 0){
break;
}
else if (strcmp(user_inp, "h")==0){
hi = guess;
}
else if (strcmp(user_inp, "l")==0){
lo = guess;
}
else{
printf("Sorry, I did not understand your input.");
continue;
}
}
printf("Game over. Your secret number was");
return guess;
}
As per the comments, the problem was very likely the incorrect use of strcmp:
char *string = "fish";
char not_a_string = 'f';
if (0 == strcmp( not_a_string, string ))
...
The character 'f' has ASCII value 0x66. strcmp would blindly use this as a pointer (expecting it to point to a valid string) which would cause a crash as you access memory that's not yours (a segmentation fault).
You would have got away with strcmp( &not_a_string, string ) in this case, but that's good fortune, not correct code.
To compare the user's character input with another character, you can just use a straightforward equality (since they're both really integers):
if ( user_inp == 'c' ) ...
So that's your code fixed, but how did you ever get to run it in the first place? For me GCC immediately complained:
In function 'int binarysearch()': so.cpp:17:29: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
if (strcmp(user_inp, "c") == 0){
and didn't produce an output. It's telling you the same thing I just did (albeit fractionally more cryptically).
Lessons to learn: listen to your compiler's complaints (and make your compiler as complainy as possible)
#pmg also noted:
add a space before the conversion specifier: scanf(" %c", &user_inp)
Without it, every time you hit Enter:
Sorry, I did not understand your input.Is your secret number 25?
ie you get a spurious complaint. But with the space it works as desired.
(I hate scanf, so have no idea why this works ;) )
Your binary search is incorrect, you need to swap the check of 'h' and 'l'.
Because you compare chars and not strings, use == and not strcmp().
You don't need to include <math.h> because guess is an int, so it'll automatically round floats.
You can use getchar() to clear the buffer after the scanf()
You need to declare your function before main (possibly by defining the function before main).
#include <stdio.h>
#include <stdlib.h>
// WITHOUT <MATH.H>
int binarysearch(void);
int main(void)
{
int x;
printf("Please think of a number between 0 and 100\n\n");
x = binarysearch();
printf("%d", x);
return 0; // RETRUN 0
}
int binarysearch(void)
{
int hi,lo,guess;
hi = 100;
lo = 0;
char user_inp;
int flag = 1; // USE FLAG, NOT BREAK AND CONTINUE
while (flag){
guess = ((hi + lo)/2); // WITHOUT ROUND
printf("Is your secret number %d?\n\n", guess);
printf("Enter 'h' to indicate the guess is too high. \nEnter 'l' to indicate the guess is too low.\nEnter 'c' to indicate I guessed correctly. \n");
scanf("%c", &user_inp);
getchar(); // CLEAR THE BUFFER
if (user_inp == 'c'){ // MAKE FLAG 0
flag = 0;
}
// USE '==', NOT STRCMP
else if (user_inp == 'l'){ // YOU NEED TO SWAP 'L' & 'H'
hi = guess;
}
else if (user_inp == 'h'){
lo = guess;
}
else{
printf("Sorry, I did not understand your input.");
}
}
printf("Game over. Your secret number was ");
return guess;
}

C Program - Do - while loops not working

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.

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 won't finish reading the program after while loop

Everytime I try to press Ctrl-Z the while loop it won't print out the average.
#include <stdio.h>
int main(void)
{
float a;
float b = 0;
int counter = 0;
while(1){
scanf("%f", &a);
b += a;
counter++;
}
float average = b/counter;
printf("%f", average);
return 0;
}
If you're in Linux and expect Ctrl+Z to finish the input, you're mistaken. It's Ctrl+D, but it's Ctrl+Z in Windows though.
(What Ctrl+Z does in Linux is generally (in Bash and other shells) to suspend the program, meaning it's temporarily stopped but still exists as a process.)
You should change your loop to something like:
while(scanf("%f", &a) == 1)
{
b += a;
++counter;
}
and then try again with the EOF keyboard sequence (or just some non-numeric input).
Because there is no condition to break out (terminate) the loop, i.e, this is an infinite loop.
Try this instead:
while(1){
if(scanf("%f", &a) == 1)
{
b += a;
counter++;
}
else break;
}
}
Now, pressing Ctrl+Z (as you mentioned in the question) will terminate the loop.
Rule of thumb:
NEVER use an endless loop without making sure you have a hitable break statement.
#include <stdio.h>
int main(void)
{
float a;
float b = 0;
int counter = 0;
while(1){
if(scanf("%f", &a) == 1)
{
b += a;
counter++;
}
else break;
}
float average = b/counter;
printf("%f", average);
return 0;
}
instead of while(1), you need to test for eof().
Try while(scant("%f", &a) == 1)
see the man page for scant() and see what it says about return values, at the bottom.
Your control Z is affecting the entire program, since it is inside the loop when you hit cntrl-Z the final section never executes.

Resources