Solved Examples · Example 20
Q.Write a C program to accept a number and print it if it is an even number.
The textbook presents this worked program, transcribed exactly as printed (including its printed errors):
#include<stdio.h>
void main()
{
int numb;
printf("Enter a number\n");
scanf("%d", &numb);
if ((numb%2)!=0,
printf("%d, is an even number\n", numb);
/*End of main()*/
}
Sample output printed in the textbook:
Enter a number
24
24 is an even number
#include<stdio.h>
void main()
{
int numb;
printf("Enter a number\n");
scanf("%d", &numb);
if ((numb%2)!=0,
printf("%d, is an even number\n", numb);
/*End of main()*/
}
Enter a number
24
24 is an even number
Karnataka PUCTextbookLongImportance★★★★★est
62% · 96/154 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →[!TLDR]
Use if ((numb % 2) == 0) to detect an even number; 24 gives "24 is an even number".
This example demonstrates one-way branching with the if statement and the modulus operator %. For any integer, numb % 2 is the remainder after dividing by 2 - it is 0 for even numbers and 1 for odd numbers - so the correct even-number test is (numb % 2) == 0. Note that == is the equality test, whereas a single = is assignment. A plain one-way if prints nothing at all for an odd number, so an else branch is added here to report the odd case as well. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.