Weird output on TicTacToe game written in C - c

I am a beginner C programmer and while writing a tictactoe game in C, I encountered a strange output. I mainly used if statements to check if the "squares" are either 'X' or 'O'
#include <stdio.h>
int main(){
int p1,p2;
char arr[] = {'1','2','3','4','5','6','7','8','9'};
void drawboard(){
printf("%c|%c|%c\n",arr[0],arr[1],arr[2]);
printf("-----\n");
printf("%c|%c|%c\n",arr[3],arr[4],arr[5]);
printf("-----\n");
printf("%c|%c|%c\n",arr[6],arr[7],arr[8]);
}
while(1>0){
drawboard();
printf("Player 1, enter your choice:\n");
scanf("%d",&p1);
printf("Player 2, enter your choice:\n");
scanf("%d",&p2);
arr[p1-1] = 'X';
arr[p2-1] = 'O';
if(arr[0]&&arr[1]&&arr[2]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[3]&&arr[4]&&arr[5]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[6]&&arr[7]&&arr[8]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[0]&&arr[3]&&arr[6]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[1]&&arr[4]&&arr[7]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[2]&&arr[5]&&arr[8]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[0]&&arr[4]&&arr[8]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[2]&&arr[4]&&arr[6]=='X'){
printf("Player 1 won.\n");
return 1;
}
else if(arr[0]&&arr[1]&&arr[2]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[3]&&arr[4]&&arr[5]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[6]&&arr[7]&&arr[8]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[0]&&arr[3]&&arr[6]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[1]&&arr[4]&&arr[7]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[2]&&arr[5]&&arr[8]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[0]&&arr[4]&&arr[8]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[2]&&arr[4]&&arr[6]=='O'){
printf("Player 2 won.\n");
return 1;
}
else{
continue;
}
}
return 0;
}
After the first and the second player's input, if the input is '8' or '6', it says he won, even if only one space was occupied.

You wrote:
arr[6]&&arr[7]&&arr[8]=='X'
which means:
if arr[6] is true and arr[7] is true and arr[8]=='X' is true.
True means any character except '\0', so all the squares are true and this condition is true as soon as arr[8] is an X.
You meant:
arr[6]=='X' && arr[7]=='X' && arr[8]=='X'
(spaces are optional) which checks that all 3 of them are X. And you have to fix all the if statements this way.

Prefaced by my top comments. A few issues ...
Don't use nested functions
Put arr at global scope.
if syntax is incorrect. (e.g.) if(arr[0]&&arr[1]&&arr[2]=='X') should be if ((arr[0] == 'X') && (arr[1] == 'X') && (arr[2] == 'X'))
No check for illegal moves or out of range moves.
Not all possible win positions checked (e.g. missing a diagonal).
No need for separate win check for each player. A win [for either player] is all three in a given direction match.
The program can be greatly simplified with breakup into smaller functions.
Here is the corrected code. It is annotated.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
char arr[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
void
drawboard(void)
{
printf("%c|%c|%c\n", arr[0], arr[1], arr[2]);
printf("-----\n");
printf("%c|%c|%c\n", arr[3], arr[4], arr[5]);
printf("-----\n");
printf("%c|%c|%c\n", arr[6], arr[7], arr[8]);
}
// match3 -- decide if win
// RETURNS: winning char or zero
int
match3(int a,int b,int c)
{
int x;
--a;
--b;
--c;
x = arr[a];
return ((arr[b] == x) && (arr[c] == x)) ? x : 0;
}
// check -- check for win
int
check(void)
{
int win;
do {
// top row
win = match3(1,2,3);
if (win)
break;
// middle row
win = match3(4,5,6);
if (win)
break;
// bottom row
win = match3(7,8,9);
if (win)
break;
// left column
win = match3(1,4,7);
if (win)
break;
// middle column
win = match3(2,5,8);
if (win)
break;
// right column
win = match3(3,6,9);
if (win)
break;
// left to right diagonal
win = match3(1,5,9);
if (win)
break;
// right to left diagonal
win = match3(3,5,7);
if (win)
break;
} while (0);
switch (win) {
case 'X':
printf("Player 1 won.\n");
break;
case 'O':
printf("Player 2 won.\n");
break;
}
if (win)
drawboard();
return win;
}
// legal -- check for remaining legal moves
void
legal(void)
{
int more;
// look for remaining legal moves
more = 0;
for (int idx = 0; idx < 9; ++idx) {
more = (arr[idx] != 'X') && (arr[idx] != 'O');
if (more)
break;
}
if (! more) {
printf("No more legal moves -- no winner\n");
drawboard();
exit(0);
}
}
// ask -- ask player for moves
int
ask(int playno,int x)
{
char buf[100];
char *cp;
int move;
printf("\n");
legal();
while (1) {
drawboard();
printf("Player %d, enter your choice:\n",playno);
if (fgets(buf,sizeof(buf),stdin) == NULL) {
printf("EOF\n");
exit(0);
}
// echo for debug input from file
do {
struct termios tio;
if (tcgetattr(fileno(stdin),&tio) < 0)
fputs(buf,stdout);
} while (0);
// get the move
move = strtol(buf,&cp,10);
if (*cp != '\n') {
printf("syntax error\n");
continue;
}
// move is within bounds
if ((move >= 1) && (move <= 9)) {
--move;
// check for move to an already occupied space
if ((arr[move] == 'X') || (arr[move] == 'O')) {
printf("already has an '%c'\n",arr[move]);
continue;
}
// make the move
arr[move] = x;
break;
}
printf("move out of range\n");
}
return check();
}
int
main(void)
{
int more;
while (1) {
if (ask(1,'X'))
break;
if (ask(2,'O'))
break;
}
return 0;
}
Below are some sample games I used to test the program ...
1|2|3
-----
4|5|6
-----
7|8|9
Player 1, enter your choice:
1
X|2|3
-----
4|5|6
-----
7|8|9
Player 2, enter your choice:
4
X|2|3
-----
O|5|6
-----
7|8|9
Player 1, enter your choice:
2
X|X|3
-----
O|5|6
-----
7|8|9
Player 2, enter your choice:
5
X|X|3
-----
O|O|6
-----
7|8|9
Player 1, enter your choice:
3
Player 1 won.
X|X|X
-----
O|O|6
-----
7|8|9
1|2|3
-----
4|5|6
-----
7|8|9
Player 1, enter your choice:
1
X|2|3
-----
4|5|6
-----
7|8|9
Player 2, enter your choice:
4
X|2|3
-----
O|5|6
-----
7|8|9
Player 1, enter your choice:
2
X|X|3
-----
O|5|6
-----
7|8|9
Player 2, enter your choice:
5
X|X|3
-----
O|O|6
-----
7|8|9
Player 1, enter your choice:
3
Player 1 won.
X|X|X
-----
O|O|6
-----
7|8|9
1|2|3
-----
4|5|6
-----
7|8|9
Player 1, enter your choice:
1
X|2|3
-----
4|5|6
-----
7|8|9
Player 2, enter your choice:
2
X|O|3
-----
4|5|6
-----
7|8|9
Player 1, enter your choice:
3
X|O|X
-----
4|5|6
-----
7|8|9
Player 2, enter your choice:
4
X|O|X
-----
O|5|6
-----
7|8|9
Player 1, enter your choice:
5
X|O|X
-----
O|X|6
-----
7|8|9
Player 2, enter your choice:
9
X|O|X
-----
O|X|6
-----
7|8|O
Player 1, enter your choice:
8
X|O|X
-----
O|X|6
-----
7|X|O
Player 2, enter your choice:
7
X|O|X
-----
O|X|6
-----
O|X|O
Player 1, enter your choice:
6
No more legal moves -- no winner
X|O|X
-----
O|X|X
-----
O|X|O

Related

How do I change my program to end an incorrect output from continuously being printed to the console?

Im coding a Rock Paper Scissors program and eveything works completely fine except for one thing. In the line of the else condition, the one that contains the while loop (choice > 3 && choice < 1) it only ever works when an inncorect input like 4 is entered once but not a second time.
When an incorrect input is entered the first time the program will ask for the input again but if you enter another inncorrect input it will just continously just keep printing the same printf line
printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n"); and then proceed to just keep printing
Computer choice is ROCK. Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, randNum, seed, choice;
int counter = 0;
int counterUser = 0;
int counterComputer = 0;
printf("Please enter the random number generator seed.\n");
/* ANY integer value can be given as a seed */
scanf("%d", &seed);
/* Seed the random number generator */
srand(seed);
/* Counter to ensure only 10 games are played */
while (counter != 10) {
for (i=0;i<1;i++) {
/* Generate a random number and restrict it to the range 1 to 3 */
randNum = rand()%3+1;
/*printf("A random number between 1 and 3: %d\n", randNum);*/
}
printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n");
scanf("%d", &choice);
/* User picks an option */
if ( choice == 1 ){
printf("User choice is ROCK.\n");
}
else if ( choice == 2 ){
printf("User choice is PAPER.\n");
}
else if ( choice == 3 ){
printf("User choice is SCISSORS.\n");
}
else {
while (choice > 3 && choice < 1){
printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n");
scanf("%d", &choice);
}
}
/* Computer choses an option */
if ( randNum == 1 ){
printf("Computer choice is ROCK.\n");
}
else if ( randNum == 2 ){
printf("Computer choice is PAPER.\n");
}
else {
printf("Computer choice is SCISSORS.\n");
}
/* Compare the user and computers choices */
if ( randNum == 1 && choice == 1){
printf("It's a draw. Computer chose ROCK and User also chose ROCK.\n");
}
else if ( randNum == 2 && choice == 2 ){
printf("It's a draw. Computer chose PAPER and User also chose PAPER.\n");
}
else if ( randNum == 3 && choice == 3 ){
printf("It's a draw. Computer chose SCISSORS and User also chose SCISSORS.\n");
}
else if ( randNum == 1 && choice == 2 ){
printf("User wins because PAPER beats ROCK.\n");
counterUser = counterUser + 1;
}
else if ( randNum == 1 && choice == 3 ){
printf("Computer wins because ROCK beats SCISSORS.\n");
counterComputer = counterComputer + 1;
}
else if ( randNum == 2 && choice == 3 ){
printf("User wins because SCISSORS beats PAPER.\n");
counterUser = counterUser + 1;
}
else if ( randNum == 3 && choice == 2 ){
printf("Computer wins because SCISSORS beats PAPER.\n");
counterComputer = counterComputer + 1;
}
else if ( randNum == 2 && choice == 1 ){
printf("Computer wins because PAPER beats ROCK.\n");
counterComputer = counterComputer + 1;
}
else if ( randNum == 3 && choice == 1 ){
printf("User wins because ROCK beats SCISSORS.\n");
counterUser = counterUser + 1;
}
else {
}
counter = counter + 1;
}
printf("In 10 games, computer won %d", counterComputer);
printf(" times");
printf(" and user won %d", counterUser);
printf(" times.");
return 0;
}
UPDATE: I've tweaked it now so the only problem is now getting rid of the Computer choice is ___ when i input 4 or another inncorect value
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
2
User choice is PAPER.
Computer choice is ROCK.
User wins because PAPER beats ROCK.
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
4
Computer choice is PAPER.
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
4
Computer choice is ROCK.
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
4
Computer choice is ROCK.
Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.
This is the if statement that follows the code above and is outputing its responses when i dont want it to because when i enter or 4 or antoher incorrect value these responses should not be printing to the console aswell
/* Computer choses an option */
if ( randNum == 1 ){
printf("Computer choice is ROCK.\n");
}
else if ( randNum == 2 ){
printf("Computer choice is PAPER.\n");
}
else {
printf("Computer choice is SCISSORS.\n");
}
Sorry for not phrasing it properly before, so how do i get the the line Computer choice is ___ to stop printing because 4 is an incorrect value and hence the Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS. line should just appear on its own
I think your issue is that you're checking whether the user's input is valid or not at the very end. you should move the while loop:
while (choice > 3 && choice < 1){
printf("Please choose 1 for ROCK, 2 for PAPER or 3 for SCISSORS.\n");
scanf("%d", &choice);
}
above the if statement:
if ( choice == 1 ){
printf("User choice is ROCK.\n");
}else if ( choice == 2 ){
printf("User choice is PAPER.\n");
}else if ( choice == 3 ){
printf("User choice is SCISSORS.\n");
}
So when the user inputs an invalid number, it will go over the if statement and then it will ask again. Once it gets a valid input i'll go to check the computers move and not print the users move.
I guess this is what you were trying to do?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void state_machine(int *choice, int user);
void request_input(int* choice);
char array[3][20] = {"ROCK", "PAPER", "SCISSORS"};
int main() {
int counter = 0, randNum = 0, choice = 0, counterUser = 0, counterComputer = 0;
srand(time(NULL));
while (counter < 10) {
randNum = rand()%3+1;
request_input(&choice);
state_machine(&choice, 1);
state_machine(&randNum, 2);
if(randNum == choice) {
printf("It's a draw. Computer chose %s and User also chose %s.\n", array[randNum-1],array[choice-1]);
}
else if ( randNum == 1 && choice == 2 || randNum == 2 && choice == 3 || randNum == 3 && choice == 1) {
printf("User wins because %s beats %s.\n", array[choice-1], array[randNum-1]);
counterUser = counterUser + 1;
}
else {
printf("Computer wins because %s beats %s.\n", array[randNum-1], array[choice-1]);
counterComputer = counterComputer + 1;
}
counter++;
}
printf("In %d games, computer won %d times and user won %d times.", counter, counterComputer, counterUser);
return 0;
}
void request_input(int* choice) {
printf("Please choose 1 for %s, 2 for %s or 3 for %s.\n", array[0], array[1], array[2]);
scanf("%d", choice);
}
void state_machine(int *choice, int user) {
if(*choice < 1 || *choice > 3) {
printf("Invalid Selection was made.\n");
request_input(choice);
state_machine(choice,1);
}
else if(user == 1) {
printf("User choice is %s.\n", array[*choice-1]);
}
else if(user == 2) {
printf("Computer choice is %s.\n", array[*choice-1]);
}
}
(choice > 3 && choice < 1) should never work as it is impossible for it to satisfy both predicates. Think, for it to succeed, you need first choice to be greater than 3. Let's assume it is 4, and evaluate the second test (4 is never less than 1, so the second test fails)
No number can be at the same time greater than 3 and less than 1, so the test you have written is always false (as if you had written if (false) instead) Every number that is greater than 3 is also greater than 1, and you are asking for a number less than 1 that is greater than 3. It cannot even work for the case of 4 you state in the question.

How to stop a while loop in C

In this code, the computer asks the user what he wants to purchase between 1-7 options. And if the user presses the wrong option up to 3 times -> computer will print this message: "Do you want to leave or make a purchase? Press y(for leave) or n(for stay)". I know another way how to do this, but how can I stop the while loop and print a message?
!!!This is incorrect code(has mistakes), used for example!!!
#include <stdio.h>
int DisplayMenu();
double OrderPrice(int itemNumber);
int main
{
char process = 'y';
int mainOption;
while (process == 'y' || process == 'Y')
{
optionMain = DisplayMenu();
printf("\nYour choice was %d", optionMain);
};
return 0;
}
int DisplayMenu()
{
int option, optionCount;
printf("1 - ..., 2 - ..., 3 - ..., 4 - ..., 5 - ..., 6 - ..., 7 - ...");
scanf("%d", &option);
while (option > 7 || option < 1) {
printf("Make your chose between 1-7:");
scanf(" %d", &option);
optionCount++;
if (optionCount == 2) {
printf("Do you want to leave or make a purchase? Press y(for leave) or n(for stay)");
}
};
return option;
return 0;
}
double OrderPrice(int itemNumber)
{
double price;
switch (itemNumber) {
case 1 :
printf("\nSelection 1.");
price = 1.1;
break;
case 2 :
printf("\nSelection 2.");
price = 2.2;
break;
case 3 :
printf("\nSelection 3.");
price = 3.3;
break;
case 4 :
printf("\nSelection 4.");
price = 4.4;
break;
case 5 :
printf("\nSelection 5.");
price = 5.5;
break;
case 6 :
printf("\nSelection 6");
price = 6.6;
break;
case 7 :
printf("\nSelection 7.");
price = 7.7;
break;
// default:
// printf("Incorrect selection");
// price = 0.00;
}
return price;
}
was solved by #tadman: You need to get input at that point, test it, and if it's a stop request, break
optionCount++;
if (optionCount == 2) {
break;
}

Loop terminates because of condition, but the condition is necessary?

I'm working on a program that is a guessing game.
The problem is I have to set remainingguesses to 0 so that the amount of guesses a person can make decreases by 1. But at the same time the condition set in the loop is based on the remainingguesses not being 0. Meaning once it is 0 the loop terminates and moves on.
I don't know how to solve this while making the condition in the loop work properly.
Here's the loop in question:
printf( "Type the number of guesses that player 2 gets and press return: \n");
scanf("%d",&guesses);
remainingguesses = 0;
while (remainingguesses != 0) {
printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",remainingguesses);
scanf(" %d",&secretnumberguess);
remainingguesses = guesses - 1;
if (secretnumberguess > secretnumber) {
printf("Your guess was greater than the secret number.\n");
}
else if (secretnumberguess < secretnumber){
printf("Your guess was less than the secret number.\n");
}
else{
printf("Your guess was equal to the secret number. You win!\n");
}
}
if (remainingguesses == 0)
printf("Sorry you are out of guesses. You lose.\n");
Here's the full code in question if needed:
#include <stdio.h>
int main()
{
int secretnumber;
int guesses;
int secretnumberguess;
int remainingguesses;
while (1) {
printf("Player 1: Type a number between 0 and 99 and press return:\n");
scanf(" %d",&secretnumber);
if (secretnumber > 99 || secretnumber < 0) {
printf("Secret number cannot be greater than 99 or below 0.\n");
continue;
}
break;
}
printf( "Type the number of guesses that player 2 gets and press return: \n");
scanf("%d",&guesses);
remainingguesses = 0;
while (remainingguesses != 0) {
printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",remainingguesses);
scanf(" %d",&secretnumberguess);
remainingguesses = guesses - 1;
if (secretnumberguess > secretnumber) {
printf("Your guess was greater than the secret number.\n");
}
else if (secretnumberguess < secretnumber){
printf("Your guess was less than the secret number.\n");
}
else{
printf("Your guess was equal to the secret number. You win!\n");
}
}
if (remainingguesses == 0)
printf("Sorry you are out of guesses. You lose.\n");
return 0;
Simplified code:
#include <stdio.h>
int main()
{
int secretnumber;
int guesses;
int secretnumberguess;
int flag=0;
while (1) {
printf("Player 1: Type a number between 0 and 99 and press return:\n");
scanf(" %d",&secretnumber);
if (secretnumber > 99 || secretnumber < 0) {
printf("Secret number cannot be greater than 99 or below 0.\n");
continue;
}
break;
}
printf( "Type the number of guesses that player 2 gets and press return: \n");
scanf("%d",&guesses);
while (guesses > 0 && flag==0) {
printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",guesses);
scanf(" %d",&secretnumberguess);
guesses=guesses - 1;
if (secretnumberguess > secretnumber) {
printf("Your guess was greater than the secret number.\n");
}
else if (secretnumberguess < secretnumber){
printf("Your guess was less than the secret number.\n");
}
else{
printf("Your guess was equal to the secret number. You win!\n");
flag=1;
}
}
if (guesses == 0 && flag==0)
printf("Sorry you are out of guesses. You lose.\n");
return 0;
}
Here is probably a simple way of coding this.
read guesses;
while (guesses > 0) {
read input;
if (input == secret) {
print "you win!!";
return;
}
else {
print "try again!";
}
guesses--;
}
print "Sorry! You are out of guesses";

Switch statement executes case 2 even after break

When case 1, the program executes the code intended but then when it asks you if you want to calculate volume again if you pick yes it just executes case 2. I'm not sure what's wrong. How can I get it to only execute case 1 unless the you pick 2 in the menu?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float menu1, opt1, opt2, opt3, opt4, t;
int td;
printf("Enter: ");
scanf("%d",&td);
switch(td) {
case 1:
printf("Enter a, b, c, and h of the triangular prism in meters\n\n");
printf("a ");
scanf("%f", &opt1);
printf("b ");
scanf("%f", &opt2);
printf("c ");
scanf("%f", &opt3);
printf("h ");
scanf("%f", &opt4);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
case 2:
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
scanf("%f", &opt1);
printf("h ");
scanf("%f", &opt2);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
}
}
Your break statements [for case 1:] are only inside if blocks. If neither if is true, you get the fall through.
Here is your original:
case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
// BUG: there should be a break here
case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...
Here is the fixed code:
case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
break; // FIX: this is your _missing_ break statement
case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...

It prints The printf statement twice

This is really strange it prints this line printf("Do you want to continue Yes (Y) or No (N): \n"); Not using any loop nothing but still it prints that statement twice
int main()
{
int led=0;
int ohm=0;
char check;
int flag=0;
while (led < 1 || led > 3){
printf("Enter the number of switch you want to close: \n\n");
printf(" ******************** Press 1 for switch (LED) 1 ********************\n");
printf(" ******************** Press 2 for switch (LED) 2 ********************\n");
printf(" ******************** Press 3 for switch (LED) 3 ********************\n");
printf("Switch: ");
scanf("%d", &led);
}
printf("\n\n");
while (ohm < 1 || ohm > 3){
printf("Enter the resistance of Rheostat: \n\n");
printf(" ******************** Press 1 for 10 ohm resistance ********************\n");
printf(" ******************** Press 2 for 20 ohm resistance ********************\n");
printf(" ******************** Press 3 for 30 ohm resistance ********************\n");
printf("Resistance: ");
scanf("%d", &ohm);
}
while (flag == 0)
{
//LED-1
if(led== 1 && ohm== 1 )
{
printf("LED-1 is blinking 2 times\n");
}
if(led== 1 && ohm== 2)
{
printf("LED-1 is blinking 4 times\n");
}
if(led== 1 && ohm== 3 )
{
printf("LED-1 is blinking 6 times\n");
}
//LED-2
if(led== 2 && ohm== 1 )
{
printf("LED-2 is blinking 2 times\n");
}
if(led== 2 && ohm== 2 )
{
printf("LED-2 is blinking 4 times\n");
}
if(led == 2 && ohm == 3)
{
printf("LED-2 is blinking 6 times\n");
}
//LED-3
if(led == 3 && ohm == 1 )
{
printf("LED-3 is blinking 2 times\n");
}
if(led == 3 && ohm == 2)
{
printf("LED-3 is blinking 4 times\n");
}
if(led == 3 && ohm == 3)
{
printf("LED-3 is blinking 6 times\n");
}
led = 0;
ohm = 0;
printf("Do you want to continue Yes (Y) or No (N): \n");
scanf("%c", &check);
if(check =='Y' || check =='y')
{
while (led < 1 || led > 3){
printf("Enter the number of switch you want to close on: ");
scanf("%d", &led);
}
while (ohm < 1 || ohm > 3){
printf("Enter the resistance of Rheostat: ");
scanf("%d", &ohm);
}
}
if(check=='N' || check=='n')
{
printf("Thanks for using the program");
flag = 1;
}
}
return 0;
}
Use scanf(" %d", &led); , scanf(" %c", &check); etc. in the code.
Adding an extra space before the format specifier will solve the problems caused by garbage/newline in the buffer.
The first time scanf("%c", &check); finds some garbage (that does not match y or n) so your program can do another loop.
As someone else already noticed, that garbage might be the newline after the ohm input.
Some ideas to solve the problem:
http://www.velocityreviews.com/forums/t436518-get-rid-of-trailing-newline-for-scanf.html
scanf(" %c", &input);
(leading space will eat whitespace in the input)
scanf() leaves the new line char in the buffer
scanf("%d", &ohm);
Here when you input a number and press ENTER, the number is processed by scanf, but the newline is still in the input buffer, then later
printf("Do you want to continue Yes (Y) or No (N): \n");
scanf("%c", &check);
check will actually store the newline, not 'N',
if(check=='N' || check=='n')
{
printf("Thanks for using the program");
flag = 1;
}
so flag will not be set to 1, the while loop will continue again. In the second loop, check can be assigned 'N', the loop will terminate after.
Please try scanf("%c ", &check);. Notice the extra space given after %c which will absorb extra new line character.
use getchar and it works just fine, you can try it here

Resources