kusur
kusur

Reputation: 618

printf() function and displaying %

I am trying to execute a program that prints the numerical value when the && operator returns true and when it returns false. The code is as follows:-

#include <stdio.h>
main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("Part I\n");
printf("(a%2 == 0) && (b%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
printf("(a%3 == 0) && (b%3 == 0): %d\n",(a%3 == 0) && (b%3 == 0));
printf("(a%5 == 0) && (b%5 == 0): %d\n",(a%5 == 0) && (b%5 == 0));
printf("(a%7 == 0) && (b%7 == 0): %d\n",(a%7 == 0) && (b%7 == 0));
printf("Part II\n");
printf("The AND operator yields: %d\n",(a%2 == 0) && (b%2 == 0));
printf("The AND operator yields: %d\n",(a%3 == 0) && (b%3 == 0));
printf("The AND operator yields: %d\n",(a%5 == 0) && (b%5 == 0));
printf("The AND operator yields: %d\n",(a%7 == 0) && (b%7 == 0));

return 0;
}

The output ( along with my input ) is as follows:-

210
210
Part I
(a%2 == 0) && (b%2 == 0): %d
(a%2 == 0) && (b%2 == 0): %d
(a%2 == 0) && (b%2 == 0): %d
(a%2 == 0) && (b%2 == 0): %d
Part II
The AND operator yields: 1
The AND operator yields: 1
The AND operator yields: 1
The AND operator yields: 1

Why is the first part behaving in such a manner? This is happening even when I replace && by ||. I am using a Borland C++ Compiler 5.5 . Please Help.

Upvotes: 0

Views: 182

Answers (3)

Pankaj Prakash
Pankaj Prakash

Reputation: 2428

You are actually using illegal escape sequence character to print % in the first part. Thats why printf is yielding garbage values.

printf("(a%2 == 0) && (b%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
              ^                        ^
      Here is you are mistaking

It should be like

printf("(a%%2 == 0) && (b%%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));  

You can also read about all format specifiers used in C.

Upvotes: 0

Alko
Alko

Reputation: 771

I've tested this with http://codepad.org/, which I think uses gcc, and the code worked ok. But you might try to add an extra % before a literal % (i.e, %%) so the compiler knows the % that follows is an actual character. Like this:

printf("Part I\n");
printf("(a%%2 == 0) && (b%%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
printf("(a%%3 == 0) && (b%%3 == 0): %d\n",(a%3 == 0) && (b%3 == 0));
printf("(a%%5 == 0) && (b%%5 == 0): %d\n",(a%5 == 0) && (b%5 == 0));
printf("(a%%7 == 0) && (b%%7 == 0): %d\n",(a%7 == 0) && (b%7 == 0));

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Because if you want to actually display a %, then you must escape it in the printf format string with another %. e.g.

printf("(a%%2 == 0) && (b%%2 == 0): %d\n",(a%2 == 0) && (b%2 == 0));
          ^              ^

Upvotes: 4

Related Questions