3 Replies - 231 Views - Last Post: 24 June 2011 - 01:07 PM Rate Topic: -----

#1 pvpkiller  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 24-June 11

problem with if statement

Posted 24 June 2011 - 12:57 PM

This is my first day learning C, and I am not getting what I need from the code I wrote, please help. ( i am following a book)

/*using if statements and rational operators*/
#include <stdio.h>

int main()
{
	int num1, num2;
	
	printf( "Enter two integers, and I will tell you\n");
	printf( "the relationships they satisfy: "); 
	scanf( "%d%d", &num1, &num2 );
	
	if ( num1 == num2 );
		printf( "%d is equal to %d\n", num1, num2);
	
	if ( num1 != num2 );
		printf( "%d is not equal to %d\n", num1, num2);
	
	if ( num1 < num2 );
		printf( "%d is less than %d\n", num1, num2);
	
	if ( num1 > num2 );
		printf( "%d is greater than %d\n", num1, num2);
	
	if ( num1 <= num2 );
		printf( "%d is less than or equal to %d\n", num1, num2);
		
	if ( num1 >= num2 );
		printf( "%d is greater than or equal to %d\n", num1, num2);
		
	return 0;
}


when i enter 2 numbers, e.g. 5 and 7, i get :

5 is equal to 7
5 is not equal to 7
5 is less than 7
5 is greater than 7
5 is less than or equal to 7
5 is greater than or equal to 7

why is everything showing up?

Is This A Good Question/Topic? 0
  • +

Replies To: problem with if statement

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2101
  • View blog
  • Posts: 3,204
  • Joined: 21-June 11

Re: problem with if statement

Posted 24 June 2011 - 01:02 PM

If an if-statement is not followed by curly braces, it will only apply to the statement directly following it. If you have a semicolon after the if, that semicolon counts as an empty statement and the if applies to that empty statement (and thus not to the printf-call following it).

This means that your printfs will always execute, independently of the if-statement. You can fix this by removing the semicolons following the if-statements. You should also make a habit of always surrounding your if-blocks with braces to avoid such mistakes in the future.
Was This Post Helpful? 2
  • +
  • -

#3 mi14chal  Icon User is offline

  • D.I.C Head

Reputation: 81
  • View blog
  • Posts: 202
  • Joined: 11-December 10

Re: problem with if statement

Posted 24 June 2011 - 01:03 PM

Why did you add ";" after if statement? You must delete ";" after if statement.
Was This Post Helpful? 2
  • +
  • -

#4 pvpkiller  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 24-June 11

Re: problem with if statement

Posted 24 June 2011 - 01:06 PM

I see, thank you very much, it works now!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1