My increment doesn't work (c) - c

So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:
int main() {
int nej;
printf("1-Triangulo \n");
printf("2-Division \n");
printf("3-Menu \n");
printf("4-Bosque \n");
printf("0-Salir \n");
scanf("%d", &nej);
if (nej == 1) {
// Ejercicio 1-Triangulo:
triangulo();
}
if (nej == 2) {
// Ejercicio 2-Division:
division();
}
if (nej == 3) {
menu();
}
if (nej == 4) {
arboles();
}
if (nej == 0) {
// Salida
exit(1);
}
int nerr = 0;
while (nej < 0 || nej > 4) {
nerr++;
// Contador de error
if (nerr == 4) {
exit(1);
}
}
}
How to fix this?

I believe you have a typo inside the while condition
while (nej < 0 || nej > 4) {
...
should be:
while (nerr < 0 || nerr > 4) {
..

nej being the input, and the input being invalid if less than 0 or larger than 4, the correct statement would be:
if (nej < 0 || nej > 4) {
(and not while as nej is not changed in the code block).

If you initialize the int nerr = 0; every time when you read,the flow will never reach the exit condition
int main()
{
int nej;
int nerr = 0; // Keep the counter outside the loop
while (true){//Start a infinite loop here
printf("1-Triangulo \n");
printf("2-Division \n");
printf("3-Menu \n");
printf("4-Bosque \n");
printf("0-Salir \n");
scanf("%d", &nej);
if (nej == 1) {
// Ejercicio 1-Triangulo:
triangulo();
}
if (nej == 2) {
// Ejercicio 2-Division:
division();
}
if (nej == 3) {
menu();
}
if (nej == 4) {
arboles();
}
if (nej == 0) {
// Salida
exit(1);
}
while (nej < 0 || nej > 4) {
nerr++;
// Contador de error
if (nerr == 4) {
exit(1);
}
}
}

It have following errors:
Code should be in the while loop
Variable nerr should be declared and initialize outside the while loop
Variable nerr should control the while loop
Note: It is Ok to use multiple if. But use of switch is much convenient and advisable.
Corrected code is as following:
int main() {
int nej;
int nerr = 0;
while (nerr < 4) {
printf("1-Triangulo \n");
printf("2-Division \n");
printf("3-Menu \n");
printf("4-Bosque \n");
printf("0-Salir \n");
scanf("%d", &nej);
switch(nej){
case 1:// Ejercicio 1-Triangulo:
triangulo();
break;
case 2:// Ejercicio 2-Division:
division();
break;
case 3:
menu();
break;
case 4:
arboles();
break;
case 0:// Salida
exit(1);
break;
default:
nerr++;
}
// Reset 'nerr' if any valid vaue is entered by user
if ((nej >= 0) && (nej <= 4)) {
nerr = 0;
}
}
}

Related

Eclipse Console Does't Output Anything

When I run my code, the console doesn't output anything. When I go into "debug as c application mode" and step into the makeBoard() method that is supposed to print stuff nothing is shown on the console. I can't work on this project if the console doesn't work.
Whenever I run my code with only makeBoard() in the int main(void) method, the console outputs what it's supposed to. However, when I add the rest of my code in the int main(void) method, nothing is shown in the console window.
I am very new to C and the eclipse IDE. Do I need to download something?
The makeBoard() method:
void makeBoard(){
printf("Row A: ");
for(int i = 0; i< rowAcounter; i++)
{
printf("O");
}
printf("\n");
printf("Row B: ");
for(int i = 0; i< rowBcounter; i++)
{
printf("O");
}
printf("\n");
printf("Row C: ");
for(int i = 0; i< rowCcounter; i++)
{
printf("O");
}
printf("\n");
}
My complete int main method and the rest of my program:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void makeBoard();
void nextTurn(int player);
void prompt(int turn);
_Bool isGameOver();
void done(int currentTurn);
void test();
void update();
int rowAcounter = 3;
int rowBcounter = 5;
int rowCcounter = 8;
int currentPlayer = 0; // 0= player 1's turn, 1
= player 2's turn
char firstIn;
char secondIn;
_Bool flag = 0;
int main(void){
makeBoard();
while(isGameOver() == 0){
prompt(currentPlayer);
update();
nextTurn(currentPlayer);
if(flag == 1){
break;
}
makeBoard();
}
done(currentPlayer);
return 0;
}
the rest of my code:
void update(){
poll: scanf(" %c%c", &firstIn, &secondIn);
int checkFirst = firstIn - 'A';
if((checkFirst < 0) || (checkFirst > 2))
{
printf("\n Try again, you ape.");
goto poll;
}
int checkSecond = secondIn - '0';
if((checkSecond < 0 ) || (checkSecond > 8)){
printf("\n Try again, you fricker.");
goto poll;
}
else if(checkFirst == 0){ // the player chose row A
if(checkSecond > 3){
printf("\n Try again, you frick.");
goto poll;
}
else{
rowAcounter = rowAcounter - checkSecond;
}
}
else if(checkFirst == 1){ // the player chose row B
if(checkSecond > 5){
printf("\n Try again, you headass.");
goto poll;
}
else{
rowBcounter = rowBcounter - checkSecond;
}
}
else{ // the player chose row C
if(checkSecond > 8)
{
printf("\n Try again!");
goto poll;
}
else{
rowCcounter = rowCcounter - checkSecond;
}
}
if(isGameOver() == 1){
flag = 1;
}
}
void nextTurn(int player){
if(player == 0){
player = 1;
}else
{
player = 0;
}
}
void prompt(int turn){
if(turn == 0){
printf("Player 1, make your move:");
}
else{
printf("Player 2, make your move:");
}
}
_Bool isGameOver(){
if((rowAcounter == 0) && (rowBcounter == 0) && (rowCcounter == 0)){
return 1;
}
else{
return 0;
}
}
void done(int currentTurn){
if(currentTurn == 0){
puts("Player 1 wins!");
}
else{
puts("Player 2 wins!");
}
}

Why is the computer's input not being considered?

In the code below there is an error I can't locate causing the computer's selection to not be accounted for. The user's input is being considered in the Nim game yet the computer's pieces are not being subtracted.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
void printInstructions();
int getUserInput(int);
int randomRange(int,int);
int PlayerTurn(int);
int smartCompMove(int);
int dumbCompMove(int);
int main()
{
srand(time(NULL));
int pieceAmount = randomRange(12,24);
char smartCompOrDumb;
printf("Do you want to play a smart computer or a dumb one? Select 'S' or 'D'.");
scanf("%c",&smartCompOrDumb);
bool gameOver = false;
bool playerTurn = true;
printInstructions();
while(pieceAmount > 0 && gameOver == false)
{
if (playerTurn == false)
{
if(pieceAmount <= 4)
{
printf("\nThe Computer has won :P ");
gameOver = true;
exit(0);
}
if (smartCompOrDumb == 's' || smartCompOrDumb == 'S')
{
playerTurn = true;
pieceAmount = smartCompMove(pieceAmount);
printf("%d",pieceAmount);
}
else if (smartCompOrDumb == 'd' || smartCompOrDumb == 'D')
{
playerTurn = true;
pieceAmount = dumbCompMove(pieceAmount);
printf("%d",pieceAmount);
}
}
else
{
if(pieceAmount <= 4)
{
printf("\nYou have won :) ");
gameOver = true;
exit(0);
}
playerTurn = false;
pieceAmount = PlayerTurn(pieceAmount);
printf("%d",pieceAmount);
}
}
return 0;
}
void printInstructions()
{
printf("\nThis game is called Nim and it is thousands of years old.");
printf("\nTake turns picking one to three pieces from a pile and whomever picks the last piece wins.");
printf("\n__________________________________________________________________________________________");
}
int randomRange(int low,int high)
{
return rand()% (high - low) + low;
}
int PlayerTurn(int pieceAmount)
{
pieceAmount = getUserInput(pieceAmount);
return pieceAmount;
}
int getUserInput(int pieceAmount)
{
int userInput = 0;
bool flag = true;
while (flag == true)
{
if (pieceAmount > 4)
{
printf("\nThere are %d pieces remaining.\n",pieceAmount);
printf("\nHow many pieces do you want to select? ");
scanf("%d", &userInput);
if (userInput >= 1 && userInput < 5)
{
pieceAmount = pieceAmount - userInput;
flag = false;
}
else
{
printf("This is not a valid move so try again.");
}
}
}
return pieceAmount;
}
int dumbCompMove(int pieceAmount)
{
int dumbPick = rand() % 3 + 1;
printf("\nComputer will pick from the stack. \n");
pieceAmount = pieceAmount - dumbPick;
printf("\nComputer picked %d pieces. \n", dumbPick );
return pieceAmount;
}
int smartCompMove(int pieceAmount)
{
int smartPick = 1;
printf("\nThe computer will select their pieces. \n");
if (pieceAmount >= 15 && pieceAmount < 24)
{
smartPick = 2;
pieceAmount = pieceAmount - smartPick;
}
else if (pieceAmount >= 10 && pieceAmount < 15)
{
smartPick = 4;
pieceAmount = pieceAmount - smartPick;
}
else if (pieceAmount >= 6 && pieceAmount < 10)
{
smartPick = 1;
pieceAmount = pieceAmount -smartPick;
}
else
pieceAmount = 3;
printf("\nThe computer selected %d pieces. \n",smartPick);
return pieceAmount;
}
I had this code working earlier yet somehow I must have altered something minor and now it will not function properly. I am using the Cloud9 program to run it.

Loop incomplete

I just started learning coding for about 2 months because of the course im taking.
My code works (kinda) but after the 1st loop it wont show the 1st line of the main function("You have been given 20 pokeballs, embrak on you quest on becoming a Pokeman Master!!!:), and i dont know why!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int pokeball = 20;
int rand_num;
int PokemonCaught[5] = { 0, 0, 0 ,0, 0 };
int poke_captured = 0;
int rungame = 1;
int stopgame = 1;
int total;
int randomnum();
int encounter_rate();
int pokemon_met();
void BallThrow();
void CaughtPokemon();
void checkball();
void PokeSummary();
char exitno();
int clear();
int main()
{
printf("You have been given 20 pokeballs, embrak on you quest on becoming a Pokeman Master!!!\n");
getchar();
do
{
checkball();
encounter_rate();
pokemon_met();
} while (stopgame == 0);
PokeSummary();
return 0;
}
int randomnum()
{
srand(time(NULL));
}
int encounter_rate()
{
randomnum();
rand_num = rand() % 100;
}
int pokemon_met()
{
if (rand_num <= 30)
{
printf("A wild Margikarp appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else if (rand_num <= 50)
{
printf("A wild Charmander appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else if (rand_num <= 70)
{
printf("A wild Jigglypuff appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else if (rand_num <= 85)
{
printf("A wild Pikachu appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
else
{
printf("A wild Dragonite appeared!.\n");
printf("Press ENTER to throw a pokeball!. \n");
getchar();
rungame = 1;
BallThrow();
}
}
void checkball()
{
if (pokeball > 0)
{
stopgame = 0;
}
else
{
stopgame = 1;
}
}
void BallThrow()
{
randomnum();
int BallChance;
int PokeRun;
BallChance = rand() % 2;
pokeball = pokeball - 1;
if (BallChance == 1)
{
printf("Gotcha!\n");
printf("Number of Pokeball left: %d\n", pokeball);
printf("Press ENTER to continue your journey!\n\n");
poke_captured = poke_captured + 1;
CaughtPokemon();
getchar();
if (pokeball == 0)
{
printf("Your pokeball has used up!\n");
printf("Press ENTER to check the summary of your journey\n");
getchar();
PokeSummary();
}
}
else if (BallChance == 0)
{
PokeRun = rand() % 2;
printf("The pokemon broke free!!!\n");
if (PokeRun == 0)
{
if (pokeball == 0)
{
printf("Your pokeball has used up!\n");
printf("Press ENTER to check the summary of your journey\n");
getchar();
PokeSummary();
}
else
{
printf("Number of Pokeball left: %d\n", pokeball);
printf("Press ENTER to throw pokeball!\n\n");
getchar();
BallThrow();
}
}
else if (PokeRun == 1)
{
printf("Oh no! The pokemon ran away!\n");
printf("Number of Pokeball left: %d\n", pokeball);
printf("Press ENTER to continue your journey!\n\n");
getchar();
if (pokeball == 0)
{
printf("Your pokeball has used up!\n");
printf("Press ENTER to check the summary of your journey\n");
getchar();
PokeSummary();
}
}
}
}
void CaughtPokemon()
{
if (rand_num <= 30)
{
PokemonCaught[0] = PokemonCaught[0] + 1;
}
else if (rand_num <= 50)
{
PokemonCaught[1] = PokemonCaught[1] + 1;
}
else if (rand_num <= 70)
{
PokemonCaught[2] = PokemonCaught[2] + 1;
}
else if (rand_num <= 85)
{
PokemonCaught[3] = PokemonCaught[3] + 1;
}
else if (rand_num <= 95)
{
PokemonCaught[4] = PokemonCaught[4] + 1;
}
}
void PokeSummary()
{
int point0, point1, point2, point3, point4, total;
point0 = (PokemonCaught[0]) * 10;
point1 = (PokemonCaught[1]) * 30;
point2 = (PokemonCaught[2]) * 30;
point3 = (PokemonCaught[3]) * 50;
point4 = (PokemonCaught[4]) * 70;
total = point0 + point1 + point2 + point3 + point4;
printf("You have successfully caught %d Pokemon!\n\n", poke_captured);
printf("You have caught:\n");
printf("Margikarp = %d (%dpoints)\n", PokemonCaught[0], point0);
printf("Charmander = %d (%dpoints)\n", PokemonCaught[1], point1);
printf("Jigglypuff = %d (%dpoints)\n", PokemonCaught[2], point2);
printf("Pikachu = %d (%dpoints)\n", PokemonCaught[3], point3);
printf("Dragonite = %d (%dpoints)\n", PokemonCaught[4], point4);
printf("\nTotal points = %d\n", total);
exitno();
}
char exitno()
{
char stay;
printf("Press 'y' to continue, press any other key to quit.");
scanf(" %c", &stay);
if (stay == 'y' || stay == 'Y')
{
clear();
return (main);
}
else
{
printf("Thank you for playing!!");
exit(0);
}
}
int clear()
{
total = total * 0;
poke_captured = poke_captured * 0;
PokemonCaught[0] = PokemonCaught[0] * 0;
PokemonCaught[1] = PokemonCaught[1] * 0;
PokemonCaught[2] = PokemonCaught[2] * 0;
PokemonCaught[3] = PokemonCaught[3] * 0;
PokemonCaught[4] = PokemonCaught[4] * 0;
pokeball = pokeball + 20;
}
I appreciate any help and i know my codes are far from being decent (sigh)
. Thanks
You have made an error when calling main in char exitno() function:
char exitno()
{
char stay;
printf("Press 'y' to continue, press any other key to quit.");
scanf(" %c", &stay);
if (stay == 'y' || stay == 'Y')
{
clear();
return ((char)main()); // main it should be called using parenthesis
}
else
{
printf("Thank you for playing!!");
exit(0);
}
}
That is not inside of your do-while loop.
If you want it to execute every time, then just move it down into the the loop. Otherwise, your program will move past in the first few milliseconds of operation. Alternatively, modify it (likely, put it within a new function) to print out some information that might change during execution of your program--say, the current number of pokeballs remaining.

strcmp will not correctly evaluate in if statements [duplicate]

This question already has answers here:
strcmp on a line read with fgets
(6 answers)
Closed 7 years ago.
#include <stdio.h>
#include <math.h>
#include <string.h>
#define size 7
int computeN(char s1[])
{
int n=-1;
if(strcmp(s1, "black") == 0)
{
n = 0;
}
else if (strcmp(s1, "brown") == 0)
{
n = 10;
}
else if (strcmp(s1, "red") == 0)
{
n = 20;
}
else if (strcmp(s1, "orange") == 0)
{
n = 30;
}
else if (strcmp(s1, "yellow") == 0)
{
n = 40;
}
else if (strcmp(s1, "green") == 0)
{
n = 50;
}
else if (strcmp(s1, "blue") == 0)
{
n = 60;
}
else if (strcmp(s1, "violet") == 0)
{
n = 70;
}
else if (strcmp(s1, "grey") == 0)
{
n = 80;
}
else if (strcmp(s1, "white") == 0)
{
n = 90;
}
printf("%d\n", n);
return n;
}
int computeN2(char s2[])
{
int n1=-1;
if(strcmp(s2, "black") == 0)
{
n1 = 0;
}
else if (strcmp(s2, "brown") == 0)
{
n1 = 1;
}
else if (strcmp(s2, "red") == 0)
{
n1 = 2;
}
else if (strcmp(s2, "orange") == 0)
{
n1= 3;
}
else if (strcmp(s2, "yellow") == 0)
{
n1 = 4;
}
else if (strcmp(s2, "green") == 0)
{
n1 = 5;
}
else if (strcmp(s2, "blue") == 0)
{
n1 = 6;
}
else if (strcmp(s2, "violet") == 0)
{
n1 = 7;
}
else if (strcmp(s2, "grey") == 0)
{
n1 = 8;
}
else if (strcmp(s2, "white") == 0)
{
n1 = 9;
}
printf("%d\n", n1);
return n1;
}
int computeExponent(char s3[])
{
int exp=0;
if(strcmp(s3, "black") == 0)
{
exp = 1;
}
else if (strcmp(s3, "brown") == 0)
{
exp = 10;
}
else if (strcmp(s3, "red") == 0)
{
exp = 100;
}
else if (strcmp(s3, "orange") == 0)
{
exp = 1000;
}
else if (strcmp(s3, "yellow") == 0)
{
exp = 10000;
}
else if (strcmp(s3, "green") == 0)
{
exp = 100000;
}
else if (strcmp(s3, "blue") == 0)
{
exp = 1000000;
}
else if (strcmp(s3, "violet") == 0)
{
exp = 10000000;
}
else if (strcmp(s3, "gray") == 0)
{
exp = 100000000;
}
else if (strcmp(s3, "white") == 0)
{
exp = 1000000000;
}
printf("%d\n", exp);
return exp;
}
int computeResistance(int x, int y, int z)
{
int omega = ((x+y) * z);
return omega;
}
int main(void)
{
char color_codes[10][7] = {"black","brown","red","orange","yellow","green","blue","violet","gray","white"};
char s1[7], s2[7], s3[7];
int n, n1, choice;
printf("Enter the colors of the resistor's three bands, beginning with\n");
printf("the band nearest the end. Type the colors in lowercase letters\n");
printf("only, NO CAPS\n");
printf("Band 1 =>\n"); //prints prompts for bands
fgets(s1, size, stdin); //stores band 1 in s1
printf("Band 2 => \n"); //prints prompt
fgets(s2, size, stdin); //stores band 2 in s2
printf("Band 3 => \n"); //prints prompt
fgets(s3, size, stdin); //stores band 3 in s3
printf("Resistance value: %d\n", computeResistance(computeN(s1), computeN2(s2), computeExponent(s3))); //computes resistance
return (0); //make the exit
}
The strings are being stored properly; the issue is the fact that within the functions the correct value is not being found within the comparison in order to find the resistance with the algorithm. If the user enters 'red', 'red', 'red', the values n,n1, and exp will be equal to -1,-1,0. What could be causing this?
The problem here is, fgets() scans and stores the trailing newline, too, into the input buffer.
You need to get rid of that newline before sending the input for comparison. Otherwise, your string comparison is pretty much likely to fail.
A very simple solution can be like, check the string length of the input, then check on the last index value against the newline (\n), if you found that, replace that with null (\0) and then, pass on the input to the comparison function(s).
fgets includes the newline character in the string it reads. You'll either have to remove it or use a function like scanf which does not include the newline. (If you use scanf, remember to use e.g. %7s specifiers to prevent buffer overflows).

scanf doesn't work (integer)

When I execute my code, scanf("%d", &n); don't scan anything, I mean, if I introduce any number it doesn't do anything, regardless of the numbers I introduce.
void testEsPrimo() {
int n;
printf("Comprobando si un número es o no primo\n");
printf("Teclee un número entero: ");
fflush(stdout);
scanf("%d", &n); //<---- The problem ?
if(esPrimo(n) == cierto){
printf("%d es primo\n", n);
}else{
printf("%d NO es primo\n", n);
}
fflush(stdout);
}
Logico esPrimo(int n){
int divisor;
int esPrimox;
for(divisor = 2; sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
if(esPrimox == 1) {
return cierto;
}
return falso;
}
This is my esPrimo code that is about decide if a number is prime or not.
typedef enum {falso, cierto} Logico;
and this is Logico, defined in a .h file
PD: This are my first steps on C so my code might be bad.
PD2: Excuse me for my bad English I'm not native and my English isn't really good.
Your scanf is perfect.
I think that your mistake is the loop for from esPrimo. Actually you have an infinite loop, because sqrt(n) has always the same value and it isn't a boolean expression.
Change your loop:
for(divisor = 2; sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
for this:
for(divisor = 2; divisor < sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
But then you have a problem when you know that your number is not prime: you have to finish the loop.
You can do this:
for(divisor = 2; divisor < sqrt(n); divisor++) {
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
break;
}
}
}
But if you can avoid using breakinside a loop for, don't use that.
With complicated algorithms you have a clean code with that, but when you read a loop for, usually your understand that the loop do a exactly number of iterations. If you have another flag to end the loop, use while.
While (divisor < sqrt(n) && esPrimox == 0){
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
} else {
esPrimox =1;
}
}
}
There are 2 main problems in esPrimo.
First, the for loop will not terminate:
for(divisor = 2; sqrt(n); divisor++) {
Change the condition to:
for(divisor = 2; divisor <= sqrt(n); divisor++) {
Second is in the logic. If you find that n is not a prime, you need to break the loop or the function will always return true. You could do it either with the break statement or by checking the value of esPrimox in the loop condition.
Here's how to do it using break:
for(divisor = 2; divisor <= sqrt(n); divisor++) { /* fixed loop condition */
if(n <= 0) {
return falso;
} else {
if(n%divisor == 0) {
esPrimox = 0;
break; /* break the loop */
} else {
esPrimox =1;
}
}
}

Resources