Even or odd
Read an integer n. Print even if n is even and odd otherwise.
4evenA program is the translation of an algorithm. Before writing code, the problem must be described as an ordered sequence of steps. This lab covers representing algorithms and the first category of statements that change the order of execution: decision statements.
if and if-else statementselse ambiguity by using bracesswitch statement and understanding the role of breakAn algorithm is a finite sequence of actions that, applied to input data, lead to the desired result. Describing it is an intermediate stage between the mathematical formulation and the program written in a concrete language.
| Method | Advantages | Disadvantages |
|---|---|---|
| Natural language | needs no special training | ambiguous for complex problems |
| Flowchart | visually clear, easy to follow | becomes hard to draw for large algorithms |
| Pseudocode | concise, close to the final code | not standardized |
| Decision tables | ideal for many combined alternatives | unsuited to sequential algorithms |
| Type | Form | Notes |
|---|---|---|
| Expression statement | expression; | any expression followed by ; becomes a statement |
| Empty statement | ; | does nothing; useful where the syntax requires a statement |
| Compound statement (block) | { ... } | groups several statements; can contain local declarations |
| Decision statements | if, if-else, switch | choose a branch of execution |
| Repetition statements | while, do-while, for | covered in Laboratory 6 |
| Jump statements | break, continue, return, goto | interrupt the normal flow |
if (expression)
statement; // simple form
if (expression)
statement_1;
else
statement_2; // form with an alternative
if (expression_1) {
...
} else if (expression_2) {
...
} else {
... // cascading alternatives
}
if does not
have to be a comparison. Any nonzero value is considered true, and zero is false. That
is why if (n) is equivalent to if (n != 0).Watch step by step how the conditions in an if-else if cascade
are evaluated, and why the order of the tests matters.
grade < 9 seems to also
accept grades under 5, but those cases were already handled by the earlier conditions. In a
cascade, every branch implicitly assumes all the ones before it were false.
switch (expression) {
case c1:
statements;
break;
case c2:
statements;
break;
default:
statements;
}
| Aspect | Rule |
|---|---|
| The expression's type | must be integer or character - not float, not a string |
case labels | must be constants, distinct from each other |
break | stops execution; without it, execution continues into the next case |
default | optional; runs if no case matches |
break makes execution continue into the following cases, regardless of their
value. Sometimes this is intentional - to group several values that get the same treatment -
but most often it is an oversight.if (a > b); is syntactically correct: the body of if becomes the
empty statement, and the following block executes always. The compiler flags nothing.else is always associated with the nearest unassociated if,
regardless of indentation. Indentation fools the eye, not the compiler. Always use braces.if (0.1 + 0.2 == 0.3) is false, because of the approximate binary
representation. Correct: if (fabs(a - b) < 1e-9).if (x = 0) assigns and is always false; if (x = 5) assigns and is
always true. Some programmers write if (5 == x) precisely so that the mistake
becomes a compile error.
#include <stdio.h>
#include <math.h>
int main(void)
{
double a, b, c, delta, x1, x2;
printf("Coefficients a, b, c: ");
scanf("%lf %lf %lf", &a, &b, &c);
if (a == 0) {
if (b == 0) {
if (c == 0) printf("Identity: any x is a solution\n");
else printf("Impossible equation\n");
} else {
printf("First-degree equation: x = %.4f\n", -c / b);
}
} else {
delta = b * b - 4 * a * c;
if (delta > 0) {
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("Two real roots: %.4f and %.4f\n", x1, x2);
} else if (delta == 0) {
printf("Double root: %.4f\n", -b / (2 * a));
} else {
printf("Complex roots: %.4f +/- %.4fi\n",
-b / (2 * a), sqrt(-delta) / (2 * a));
}
}
return 0;
}
#include <stdio.h>
int main(void)
{
double a, b;
char op;
printf("Expression (e.g. 12 * 4): ");
scanf("%lf %c %lf", &a, &op, &b);
switch (op) {
case '+':
printf("%.2f\n", a + b);
break;
case '-':
printf("%.2f\n", a - b);
break;
case '*':
case 'x': // intentional grouping: * and x do the same thing
case 'X':
printf("%.2f\n", a * b);
break;
case '/':
if (b == 0) printf("Division by zero!\n");
else printf("%.2f\n", a / b);
break;
default:
printf("Unknown operator: %c\n", op);
}
return 0;
}
#include <stdio.h>
int main(void)
{
int a = 1, b = 2;
// WRONG: the indentation suggests something other than what the compiler does
if (a > 0)
if (b > 5)
printf("b is large\n");
else // binds to the SECOND if, not the first!
printf("This does NOT mean a <= 0\n");
// CORRECT: the braces remove any ambiguity
if (a > 0) {
if (b > 5) {
printf("b is large\n");
}
} else {
printf("a <= 0\n");
}
return 0;
}
Decisions are best understood by tracing them step by step. Run the programs, then change the input data to force each branch.
1 -4 4 (double root), then
to 1 1 5 (complex roots), and to 0 2 6 (first degree). Each set of
values sends execution down a different branch.This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.
Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.
Read an integer n. Print even if n is even and odd otherwise.
4evenRead two integers a and b. Print the larger of the two.
3 88Read an integer x. Print positive, negative or zero.
5positiveRead a grade (an integer). If the grade is not between 1 and 10, print invalid grade. Otherwise print passed for a grade of at least 5 and failed for a lower one.
7passedRead three integers a, b, c. Print the largest of them.
1 2 33Read an expression of the form a op b, where a and b are integers and op is one of the characters + - * / %. Print the result (division is integer division). For division or remainder with b = 0 print division by zero, and for any other character print unknown operator.
7 + 29Problems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.
Read a year (a positive integer). Print leap or common. A year is a leap year if it divides by 4, except for century years, which are leap years only if they divide by 400.
2024leapRead three integers, the sides of a possible triangle (each at most 100000 in absolute value). If they do not form a non-degenerate triangle, print not a triangle. Otherwise print the type (equilateral, isosceles or scalene), followed by the word right if the triangle has a right angle. Example: for 3 4 5 print scalene right.
3 4 5scalene rightRead a valid date in the form day month year. Print the date of the next day in the format dd.mm.yyyy (with leading zeros). Use switch for the number of days in the month.
15 3 202616.03.2026Read the real coefficients a b c of the equation ax² + bx + c = 0 and print, with two decimals:
x1 = … x2 = … for two distinct real roots, with x1 < x2;x = … for a single root (a double root or a first-degree equation);x1 = p - qi x2 = p + qi for complex roots, with q > 0;no solution or infinitely many solutions when a = b = 0.1 -3 2x1 = 1.00 x2 = 2.00Read a date day month year (year between 1600 and 2400). If the date does not exist, print invalid date. Otherwise print the day of the week: monday, tuesday, wednesday, thursday, friday, saturday, sunday. You may use Zeller's congruence.
15 10 2026thursdayswitch, which also handles division by zero.; after if and explain the observed behavior.else ambiguity and check which if it binds to.if (0.1 + 0.2 == 0.3) and fix the comparison using a tolerance.switch with grouped cases.switch to print the day's name.