[go: up one dir, main page]

0% found this document useful (0 votes)
8 views4 pages

C Programming Day4

Uploaded by

gogglezain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

C Programming Day4

Uploaded by

gogglezain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

C Programming - Day 4: switch-case and

Ternary Operator
Topics Covered:
• switch-case statement

• default case

• break statement

• Ternary operator (? :)

• Short form of if-else

• Simple decision-making

switch-case Examples:

Example 1: Simple Menu using switch

#include <stdio.h>

int main() {
int choice;
printf("1. Add\n2. Subtract\n3. Multiply\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("You chose Add.\n");
break;
case 2:
printf("You chose Subtract.\n");
break;
case 3:
printf("You chose Multiply.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}

Example 2: Vowel or Consonant using switch

#include <stdio.h>

int main() {
char ch;
printf("Enter a letter: ");
scanf(" %c", &ch);

switch(ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel\n");
break;
default:
printf("Not a vowel\n");
}
return 0;
}

Example 3: Calculator using switch

#include <stdio.h>

int main() {
int a = 10, b = 5;
char op = '+';

switch(op) {
case '+':
printf("Sum = %d\n", a + b);
break;
case '-':
printf("Difference = %d\n", a - b);
break;
case '*':
printf("Product = %d\n", a * b);
break;
case '/':
printf("Quotient = %d\n", a / b);
break;
default:
printf("Invalid Operator\n");
}

return 0;
}

Ternary Operator Examples:

Example 4: Check Even or Odd using ternary

#include <stdio.h>

int main() {
int num = 4;
(num % 2 == 0) ? printf("Even\n") : printf("Odd\n");
return 0;
}

Example 5: Find Largest of Two Numbers

#include <stdio.h>

int main() {
int a = 5, b = 10;
int max = (a > b) ? a : b;
printf("Largest = %d\n", max);
return 0;
}

Example 6: Pass or Fail

#include <stdio.h>

int main() {
int marks = 38;
(marks >= 40) ? printf("Pass\n") : printf("Fail\n");
return 0;
}
Day 4 Summary:
• switch-case is useful for fixed menu choices.
• Use 'break' to prevent falling through cases.
• Ternary operator is a short if-else for simple decisions.

You might also like