I created a program that calculates the divisibility by 3 and 5. If divisible by 3 print 'CS' and if divisible by 5 print 'CS1714'. If divisible by both print 'CS1714'. If not divisible by 3 or 5 print 'ERROR'.
My code executes properly. However is it possible for the Boolean && to break if say both values are false. Also why does the code print 'CSERROR' when input is 98988?
#include <stdio.h>
int main(void)
{
int userInput;
scanf("%d", &userInput);
if((userInput % 3) == 0){
printf("CS");
}
if((userInput % 5) == 0){
printf("1714");
}
else if(!((userInput % 5) == 0 && (userInput % 3) == 0)){
printf("ERROR");
}
return 0;
}
When the input is 98988 it is printing CSERROR because the number 98988 is divisible by 3 and that is why the first if condition is true and thus it prints CS, and then you gave another if where you are checking if the number is divisible by 5 or not, if the number is divisible by 5 then you print 1714, else you print ERROR, as 98988 is not divisible by 5 that is why it goes to the else part and prints ERROR (The last else will always true if your second if is false. So, here is a logical error). Previously it printed CS and now it printed ERROR, combinedly you are seeing CSERROR.
One is need to be clear that, the if-else blocks structures are like below, and it started implementing from a if to go further until finds a true condition or else.
if(condition){
}
else if(condition){
}
else{
}
You should check both conditions (when the number is divisible by 3 and also divisible by 5) first, then check whether it is divisible by 3 , if not then check by 5. And finally if all are false that means it is not divisible by 3 and also not divisible by 5, so print error.
The code should be like:
#include <stdio.h>
int main(void)
{
int userInput;
scanf("%d", &userInput);
if(((userInput % 5) == 0 && (userInput % 3) == 0)){
printf("CS1714");
}
else if((userInput % 3) == 0){
printf("CS");
}
else if((userInput % 5) == 0){
printf("1714");
}
else{
printf("ERROR");
}
return 0;
}
Input: 98988
Output: CS
#include <stdio.h>
int main(void)
{
int userInput;
scanf("%d", &userInput);
if((userInput % 3) == 0){
printf("CS");
}
if((userInput % 5) == 0){
printf("1714");
}
else if(((userInput % 5) != 0 && (userInput % 3) != 0)){
printf("ERROR");
}
return 0;
}
Related
I recently wrote a program in C for a calculator. To produce a function that checks if the user input is a prime number or not (amongst other functions).
I essentially used this code (excluding all other functions):
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^
This code above produces the errors
I am not sure why the code produces an error for the value 9 (I fixed that above by adding the condition: if (operand1 == 9), but I don't understand why 9 is seemingly the only value that results in an incorrect solution (It would say 9 was prime, but not any other number give an incorrect result).
One other bug that I remidied with an extra condition statement was the value of 2.
Before adding the extra conditional statement in the main function: if (ioperand1 == 2), the value 2 would always come up as a non prime number.
I originally found this solution to check for prime numbers online, and I still don't understand why the for loop starts from 2.
#include <stdio.h>
#include <math.h>
int testForPrime(int);
int main(void) {
int ioperand1 = 0;
printf("\nEnter the value to check if prime (positive integer): ");
scanf("%d", &ioperand1);
if (testForPrime(ioperand1) != 0 || ioperand1 == 2)
printf("\nThis number is prime.\n");
else
printf("\nThis number is not prime.\n");
return 0;
}
int testForPrime(int operand1) {
int i = 0;
for (i = 2; i <= sqrt(operand1); i++) {
if (operand1 == 0 || operand1 == 1 || operand1 == 9)
return 0;
else if (operand1 % i == 0)
return 0;
else
return 1;
}
}
^This code above fixed the problem, though I don't undesttand why the problem existed in the first place.
TL;DR:
I don't know why this code doesn't work without the extra conditional statements:
if (operand1 == 9) in function definition,
and
if (ioperand1 == 2) in main function.
If anyone could help clear this up, I'd appreciate it.
It is because your prime checking loop does not iterate. It always returns on the first iteration. It must run to completion, and then the number will be prime. So
int testForPrime(int operand1) {
if(operand1 < 2) {
return 0;
}
int sr = (int)round(sqrt(operand1));
for(int i = 2; i <= sr; i++) {
if (operand1 % i == 0) {
return 0;
}
}
return 1;
}
I'm not able to find the write line for third case. I'm a beginner in programming world. Much appreciated if someone helped me with this Thanks in advance!
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
if(n%3==0) {
printf("\n 1");}
else if(n%5==0){
printf("\n 2");}
else if((n%3==0) && (n%5==0)){
printf("\n 3");}
else{
printf("\n 4");
}
return 0;
}
The 3. test condition, else if ((n % 3 == 0) && (n % 5 == 0)), will never be true, because if n % 3 == 0 the 1. test, if (n % 3 == 0), will catch it before. The same goes for the case if n % 5 == 0 with the 2. test, else if (n % 5 == 0).
You need to place if ((n % 3 == 0) && (n % 5 == 0)) at the start instead to proof both sub-expressions before the testing for each sub-expression:
scanf("%d",&n);
if ((n % 3 == 0) && (n % 5 == 0)) {
printf("\n 1");
}
else if (n % 5 == 0) {
printf("\n 2");
}
else if (n % 3 == 0) {
printf("\n 3");
}
else {
printf("\n 4");
}
First you check if the number can be divided by 3, then you check if it can be divided by 5 and then if it can be divided by both.
If it can be divided by both (in other words it can be divided by 15), then it can be divided by 3, so you'll get out of the first loop and print "\n 1".
Change the order of your test. If you put the longest case first, then if both n%3 and n%5 == 0, it will print. Otherwise, it can be one or the other.
if (n%3 == 0 && n%5 == 0)
{
printf("\n 3"); // You might want this to be printf("3\n"); instead
}
else if... // other cases.
Another way to do it if you really want to keep the order is to test on the single cases that they aren't both true, ie:
if (n%3 == 0 && n%5 != 0)
{
// Only a multiple of 3
}
else if (n%5 == 0 && n%3 != 0)
{
// Only a multiple of 5
}
else if (n%3 == 0 && n%5 == 0)
{
// Multiple of 3 and 5
}
I'm not able to find the write line for third case.
else if((n%3==0) && (n%5==0))
3rd line never true as first if(n%3==0) would have also been true and code would have executed that block.
Simplify with
// v------v 1 for multiple of 3
// v------v 2 for multiple of 5
int m15 = (n%3 == 0)*1 + (n%5 == 0)*2;
if (m15 == 0) m15 = 4;
printf("\n %d", m15);`
Below is a code I wrote for a dice game called cho han. To input your guess I've used number to represent the words 'odd' and 'even'. Since then I have tried to write it again, but to actually write odd or even in the scanf section, but can't get it to work. Any help would be appreciated :)
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter '1'. To guess even, enter '2'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
scanf_s("%d", &guess);
if (guess == 2)
{
printf("\nyour guess is even.\n");
}
if (guess == 1)
{
printf("\nyour guess is odd.\n");
}
if (guess > 2 || guess < 1)
{
printf("\nInvalid guess.\nYou lose!\n");
return (1);
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
result = x + y;
printf("\ncombined total of both rolls is %d", result);
if (result == 1 || result == 3 || result == 5 || result == 7 || result == 9 || result == 11)
{
printf("\ncombined total of both rolls is odd.\n");
}
else
{
printf("\ncombined total of both rolls is even.\n");
}
if (guess == 1 && result == 1 || guess == 1 && result == 3 || guess == 1 && result == 5 || guess == 1 && result == 7 || guess == 1 && result == 9 || guess == 1 && result == 11)
{
printf("\nYou win!\n");
}
else if (guess == 2 && result == 2 || guess == 2 && result == 4 || guess == 2 && result == 6 || guess == 2 && result == 8 || guess == 2 && result == 10 || guess == 2 && result == 12)
{
printf("\nYou win!\n");
}
else
{
printf("\nYou lose!\n");
}
return 0;
}
You should change scanf_s to scanf
The line if (result == 1 || result == 3 ... could be if (result % 2 == 1) {
You could use strcmp to solve your question
The following code could work:
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
char buf[10];
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter 'odd'. To guess even, enter 'even'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
fgets(buf, sizeof buf, stdin);
if (strcmp(buf, "even\n") == 0) {
guess = 2;
printf("\nyour guess is even.\n");
} else if (strcmp(buf, "odd\n") == 0) {
guess = 1;
printf("\nyour guess is odd.\n");
} else {
printf("\nInvalid guess.\nYou lose!\n");
return 1;
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
printf("\ncombined total of both rolls is %d", x + y);
result = (x + y) % 2;
if (result == 1)
printf("\ncombined total of both rolls is odd.\n");
else
printf("\ncombined total of both rolls is even.\n");
if (guess == result)
printf("\nYou win!\n");
else
printf("\nYou lose!\n");
return 0;
}
You need to change your guess to char type and scanf to capture string.
char guess[256];
scanf("%s", guess);
And then the best way would be to call toupper() and compare with your text using strcmp().
2 questions. 1 - I'm struggling to figure out how to exit this loop when a negative number is entered. 2 - my section of code regarding checking if the sum of the digits of a number isn't working correctly and need a different equation to get the correct output but cant figure it out. That part of the code needs to add the digits of an integer and output whether the sum is odd or even.
int main(void)
{
int number, sum, i;
int divisor, prime;
do {
printf("Enter an integer:");
scanf("%d", &number);
i = number;
sum = 0;
if (i % 7 == 0) {
printf("Multiple of 7\n");
} else if (i % 11 == 0) {
printf("Multiple of 11\n");
} else if (i % 13 == 0) {
printf("Multiple of 13\n");
}
if (i % 2 == 0) {
printf("Is sum of digits Odd? 1\n");
} else {
printf("Is sum of digits Odd? 0\n");
}
int check = 1;
for (divisor = 2; divisor <= i / 2; ++divisor) {
if (i % divisor == 0) {
check = 0;
break;
}
}
if (check == 0) printf("Is number prime? 0\n");
else printf("Is number prime? 1\n");
} while (i > 0);
return (0);
}
This should work:
...
do {
printf("Enter an integer:");
scanf("%d", &number);
if ( number < 0 )
break ;
...
One way to exit a loop with certain condition in C is using BREAK
if( a < 0) {
/* terminate the loop using break statement */
break;
}
When a negative number is entered, you can check with an if condition just after taking the input, and use exit(0).
Like
if(number < 0)
exit(0);
What you are doing will not work. Because you've used the while condition at the end, the modulus functions may not work(I'm not so sure, but I think the modulus function needs a positive integer as an argument)
You're not checking the sum of digits of the number in your code, but only if the number itself is even or odd.
The part would be
while(i > 0)
{
sum += i % 10;
i /= 10;
}
That should give you the sum of the digits, and you can check if it is odd or even
Anyway, the prime part will completely fail when a negative number, or even 1 is entered.
If you mean that you don't want to enter the loop at all, you can use a while loop instead of a do while loop.
You would have to get the first input before entering the loop, though, and would need another input at the bottom of the loop. This probably isn't what you want.
You probably want to use
if (number < 0) break;
And that would go right after you read the value.
If you do this, you don't need
while (i > 0);
At the end of your loop, you can just use
while (true);
Personally, I use while loops in such cases but that's really just a stylistic choice.
In any case, there is no need to check the value twice.
wiHi everyone since last time i found extreme help on here, im gonna ask a question again
My code doesnt return right values :
something is wrong in the play_game function and i cant figure out what it is.I believe that all cases are covered but somehow they end up messed up.
also the code doesnt loop for everytime i want to play a game after the second game it stops.
this is not an assignment
any suggestion?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
static int sum, point, win = 0, roll = 0;
bool play_game(void);
int roll_dice(void);
int main(void){
srand(time(NULL));
play_game();
char input[10];
do{ point = 0;
play_game();
if(win == 1){ // I'm assuming that play returns whether you won or not
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
gets(input);
}while(*input == 'y'); // gets() flushes the buffer for next time you need input
return 0;
}
bool play_game(void){
point=0;
roll_dice();
printf("Your point is %d\n", sum);
while(roll == 1) /* first round */
{
if(sum == 7 || sum == 11)
return win = 1;
else if(sum == 2 || sum == 3 || sum == 12)
return win = 0;
else if(sum == 1 || sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
point=sum;
roll_dice();
}
}
while(roll > 1) /* all others rounds*/
{
if(sum == 7)
return win = 0;
else if(sum == point)
return win = 1;
else if(sum != point || sum != 7)
roll_dice();
}
}
int roll_dice(void){
int a,b;
a=1+rand() % (6);
b=1+rand() % (6);
sum=a+b;
roll++;
printf("You rolled %d\n", sum);
return sum;
}
OUTPUT
A couple of points:
You probably want 1 + rand() % 6
The return value of printf() is probably not what you want to return from roll_dice()
The loop needs to be more like:
main(){
char input[10];
do{
score = 0; //Always initialize the score
if(play_game()){ // I'm assuming that play returns whether you won or not
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
gets_s(input, 9);
}while(*input == 'y'); // gets() flushes the buffer for next time you need input
}
Kyle's answer is just fine (as I see it), But I can spot a few problems, hope it'll help you in further cases.
You always win, and I know it's nice, but I bet it's not the expected behavior:
while(true) // This will always happen, because true is always evaluated as true
{
printf("Won\n\n");
printf("Play again? y/n: ");
break;
}
while(false) //This will never happen, since false is always evaluated as false
{
printf("Lost\n\n");
printf("Play again? y/n: ");
break;
}
I think you meant to check the result of play_game(). So add another variable and check against it:
bool win;
win = play_game();
while (win == true)
...
while (win == false)
...
Why using while loop there? you break it in the first iteration anyway
if(win == true)
{
printf("Won\n\n");
}
else
{
printf("Lost\n\n");
}
printf("Play again? y/n: ");
The game will run not more than twice, because you don't have a loop that depends on the answer, but only an if statement that is evaluated just one time:
if(v=getchar() == 'y') //This is the second time the code runs, after that? nada.
{
point =0; /* reset point var */
play_game();
}
else if(v=getchar() == 'n') // Why adding this check? you're going out anyway after the if-else
exit(1);
EDIT
When you use a while loop, what you do is saying:
While (some expression in the parenthesis) is true, execute the code in the block {..} and then check again the expression in parenthesis.
If you write while(true), you actually writing while true is true, execute the code in the block. And this will always happen.
If you write while(false) you actually write while false is true, execute the code in the block. and this false is never true, than it will never execute the code in the block.
If you want a real condition here, you can use while(play_game()). this is like writing, while the returned value from the function play_game is true, execute the code in the block and then the code will be executed only when the play_game function return true (which indicates a win in the game).
There are many good C tutorials out there, start here or here
It is hard to tell from your description (please say what you expected to happen, and what happened instead), but the first thing I notice is that you are rolling 5-sided dice for a and b.
Rolling of the dice is happening at at incorrect points during your game sequence.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// add defines to make states easier to read
#define WIN 1
#define LOSE 0
static int sum, point, win = 0, roll = 0;
//bool play_game(void);
int play_game(void); // changed return type to be int
int roll_dice(void);
int main(void){
srand(time(NULL));
// play_game(); // unncessary
char input[10];
do
{
point = 0;
//play_game();
// if(win == 1){
if(play_game()){ // use return value from play_game()
printf("You won!\n");
}else{
printf("You lost!\n");
}
printf("Would you like to continue? y/n\n");
// gets(input);
fgets(input, sizeof(input), stdin); // a safer input read
} while(*input == 'y'); // gets() flushes the buffer for next time you need input
return 0;
}
// bool play_game(void)
int play_game(void) // changed return type to be int
{
point=0;
// remove as this messes up the roll sequence.
// roll_dice();
// incorrect place to display this message
//printf("Your point is %d\n", sum);
// the while loop here is unnecessary
//while(roll == 1) /* first round */
//{
roll_dice(); // add for initial come out roll.
if(sum == 7 || sum == 11) { // I use braces to remove ambiguity
// return win = 1;
return WIN;
} else if(sum == 2 || sum == 3 || sum == 12) {
//return win = 0;
return LOSE;
}
// sum will never be 1
// on that note if it control reaches here it will be one of the other numbers.
//} else if(sum == 1 || sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10){
// point=sum;
// roll_dice(); // remove as this messes up the roll sequence.
// }
point=sum;
printf("Your point is %d\n", sum);
//}
// while(roll > 1) /* all others rounds*/
while (1) // might as well loop forever
{
roll_dice(); // add for subsequent dice rolls
if(sum == 7) {
//return win = 0;
return LOSE;
} else if(sum == point) {
// return win = 1;
return WIN;
}
// remove as this is unnecessary
// else if(sum != point || sum != 7)
// remove as this messes up the roll sequence.
//roll_dice();
}
}
int roll_dice(void){
int a,b;
a=1+rand() % (6);
b=1+rand() % (6);
sum=a+b;
// roll++; // unncessary
printf("You rolled %d\n", sum);
return sum;
}