C Programming: if else Examples

更新於 發佈於 閱讀時間約 5 分鐘

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;
}


留言
avatar-img
留言分享你的想法!
avatar-img
邵的沙龍
3會員
5內容數
邵的沙龍的其他內容
2023/08/27
C Programming: If-Else, For Loop Exercises
2023/08/27
C Programming: If-Else, For Loop Exercises
2023/08/26
C program: For Loop
2023/08/26
C program: For Loop
2023/08/26
C programming : Switch
2023/08/26
C programming : Switch
看更多
你可能也想看
Thumbnail
「欸!這是在哪裡買的?求連結 🥺」 誰叫你太有品味,一發就讓大家跟著剁手手? 讓你回購再回購的生活好物,是時候該介紹出場了吧! 「開箱你的美好生活」現正召喚各路好物的開箱使者 🤩
Thumbnail
「欸!這是在哪裡買的?求連結 🥺」 誰叫你太有品味,一發就讓大家跟著剁手手? 讓你回購再回購的生活好物,是時候該介紹出場了吧! 「開箱你的美好生活」現正召喚各路好物的開箱使者 🤩
Thumbnail
介紹朋友新開的蝦皮選物店『10樓2選物店』,並分享方格子與蝦皮合作的分潤計畫,註冊流程簡單,0成本、無綁約,推薦給想增加收入的讀者。
Thumbnail
介紹朋友新開的蝦皮選物店『10樓2選物店』,並分享方格子與蝦皮合作的分潤計畫,註冊流程簡單,0成本、無綁約,推薦給想增加收入的讀者。
Thumbnail
這題的題目會給我們一個輸入整數,要求我們判斷這個整數是否可以用2^k 的形式來表達 (二的冪)?
Thumbnail
這題的題目會給我們一個輸入整數,要求我們判斷這個整數是否可以用2^k 的形式來表達 (二的冪)?
Thumbnail
進入選擇敘述語法了。常用的選擇敘述語法,弄懂了就運用自如。
Thumbnail
進入選擇敘述語法了。常用的選擇敘述語法,弄懂了就運用自如。
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News