odd , even


4 replies [Last post]
raunaqrox
raunaqrox's picture
Offline
Joined: 2012-06-24
Points: 0

i knew while typing the code that it wont work , and it did'nt , so here's the code

#include <stdio.h>

int main()

{ int i;

int x;

float y;

printf("enter a number");

scanf("%d",i);

if(i/2 == x)

printf("%d is even",i);

else if (i/2 == y)

printf("it is odd");

else printf("its not a number");

return 0;

}

i think i know the problems but still i'd like anyone to explain in detain all that went wrong

thanks in advance

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
davidz
davidz's picture
Offline
Joined: 2012-06-07
Points: 0

I think that your problem is that you've declared the type for int x and float y, but not the value.

You seem to be saying that x is an integer and y is a float. Compare i to x to see if it is an integer.

However, C thinks you are saying that whatever is in x is an integer, but you never said what value integer it should be. So C picks a random number - 45678, and if I make i = 4, it is not the same as 45678.

I think your program will say that i is not x and not y, unless you win the lottery!

The way I would do the program would be to use the % which is the mod command.

4 % 2 == 0 is true because 4/2 has no remainder. 5 % 2 == 1 means that there is a remainder of 1 and so 5 is odd. Anything else is not a number. (Although I am not sure what C will make of characters in this case.)

Hope I'm right!

raunaqrox
raunaqrox's picture
Offline
Joined: 2012-06-24
Points: 0

Thanks , i thought that too . I dont know about mod , i'll learn it later .

any other way to do the program without mod?

 

Kevin
Offline
When things break I did it. I am an admin!Enjoy my soothing baritone.Completionist. I am better than you.My name if Forest WiBit.Nothing on Earth could stop the coding...A Coding BeautyDriving Ms. ChickyYou maniac! You blew it up! The compiler that is.Halfsies!W007! I watched 10 vids!Boot up or shut up!I don't know when to shut up.I'm not a fanboy!
Joined: 2011-03-20
Points: 2570

Are you just trying to write a program that will tell the user if their number is even or odd? If so, you don't need x, or y or anything... Just the user's number. Here is working code, let me know what you think:

#include <stdio.h>

int main() {
	int i;
	char* result = NULL;
	
	printf("Please enter a number: ");
	scanf("%d", &i);
	
	if(i % 2 == 0)
		result = "even";
	else
		result = "odd";
	
	printf("%d is an %s number.\n", i, result);
	return 0;
}

raunaqrox
raunaqrox's picture
Offline
Joined: 2012-06-24
Points: 0

ok thanks . Thats much simpler .