-
Basic if else question
I have to create a program that takes 2 numbers. If the first number is equally divisible by the second number, then print the number of times it's divisible, otherwise, print a message saying "not divisible". I have no clue how to write an if statement to find out if the first number is equally divisible by the second number.
My code is below - please explain.
Code:
#include <stdio.h>
int main()
{
int x, y, z;
printf("Enter in 2 numbers: \n");
scanf("%d%d", &x, &y);
if
{x % y ==z}
{
printf("%d\n", z);
}
else
{
printf("not divisible\n");
}
}
return 0;
}
-
Quote:
Originally Posted by
benrogers
Code:
#include <stdio.h>
int main()
{
int x, y, z;
printf("Enter in 2 numbers: \n");
scanf("%d%d", &x, &y);
if
{x % y ==z}
{
printf("%d\n", z);
}
else
{
printf("not divisible\n");
}
}
return 0;
}
bold does the trick.
Code:
#include <stdio.h>
int main()
{
int x, y, z;
printf("Enter in 2 numbers: \n");
scanf("%d%d", &x, &y);
z = x / y;
if (x % y == 0)
{
printf("%d\n",z);
}
else
{
printf("not divisible\n");
}
return 0;
}
-
Code:
while (!(num1 % num2))
{
count++ ;
num1/=2 ;
}
i think that would work
-
1. You didn't assign z to anything.
2. The expression in the if statement should be in parenthesis, not braces.
3. For future reference, you should write code that catches division by zero, like this.
Code:
#include <stdio.h>
int main()
{
int x, y, z;
printf("Enter in 2 numbers: \n");
scanf("%d%d", &x, &y);
if (y != 0) z = x / y;
else {
printf("division by zero\n");
return 1;
}
if (x % y == 0)
{
printf("%d\n",z);
}
else
{
printf("not divisible\n");
}
return 0;
}