Code Example of Exercise 1: Even or odd
In this exercise, the program prompts the user to enter an integer. It then uses the modulo operator % to check whether the number is divisible evenly by 2. If the remainder is 0, the number is even; otherwise, it's odd.
#include <stdio.h>
int main() {
int number;
// Input the number from the user
printf("Enter an integer: ");
scanf("%d", &number);
// Check if the number is even or odd
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
return 0;
}
Code Example of Exercise 2: Grading System
#include <stdio.h>
int main() {
int score;
printf("Enter the student's score: ");
scanf("%d", &score);
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Exercise 3: Calculator Program
In this exercise, the program takes two numbers and an operator as input and uses "if-else" statements to perform the corresponding arithmetic operation. It handles division by zero as well as invalid operators.
int main() {
float num1, num2;
char operator;
printf("Enter the first number: ");
scanf("%f", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter the second number: ");
scanf("%f", &num2);
if (operator == '+') {
printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
} else if (operator == '-') {
printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
} else if (operator == '*') {
printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2);
} else if (operator == '/') {
if (num2 != 0) {
printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
} else {
printf("Cannot divide by zero.\n");
}
} else {
printf("Invalid operator.\n");
}
return 0;
}