Embedded C Module2
Embedded C Module2
3 Switch Statements
7 Case Studies
Syntax
if (condition) {
// code to execute if condition is true
}
Example
Check if a number is positive:
if (number > 0) {
printf("Positive");
}
Code
int num = 4;
if (num % 2 == 0) {
printf("Even");
} else {
printf("Odd");
}
Output
"Even" for num = 4
Syntax
if (condition) {
/* code if true */
}
else {
/* code if false */
}
Problem
Determine the grade based on a score.
Code
int score = 85;
if (score >= 90) {
printf("Grade A");
} else if (score >= 80) {
printf("Grade B");
} else if (score >= 70) {
printf("Grade C");
} else {
printf("Grade F");
}
Syntax
if (condition1) {
/* code1 */
}
else if (condition2) {
/* code2 */
}
...
else {
/* default code */
}
Problem
Categorize age groups based on years.
Code
int age = 25;
if (age < 13) {
printf("Child");
} else if (age < 20) {
printf("Teen");
} else if (age < 60) {
printf("Adult");
} else {
printf("Senior");
}
Syntax
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}
Syntax
switch (expression) {
case value1:
// code block Example Output
break; The output depends on the
case value2: expression value and can execute any
// code block of the case blocks or the default
break; block if no case matches.
default:
// default code block
}
Problem
Execute different operations based on user choice.
Code
char operation = ’+’;
int a = 10, b = 5;
switch (operation) {
case ’+’: printf("%d", a + b); break;
case ’-’: printf("%d", a - b); break;
case ’*’: printf("%d", a * b); break;
case ’/’: printf("%d", a / b); break;
default: printf("Invalid operation");
}
Code
int day = 3;
switch (day) {
case 1: printf("Monday"); break; Output
case 2: printf("Tuesday"); break; "Wednesday"
case 3: printf("Wednesday"); break;
// Additional cases
}
Syntax
while (condition) {
// code to be executed
}
Example
Print numbers from 1 to 5.
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
Code
int i = 1;
while (i <= 5) { Output
printf("%d ", i); 1 2 3 4 5
i++;
}
Syntax
do {
/* code */
}
while (condition);
Problem
Print numbers from 1 to 5, using a ’do-while’ loop.
Code
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
Syntax
for (initialization; condition; increment) {
/* code */
}
Syntax
for (initialization; condition; update) {
// code to be executed
}
Example
Print numbers from 1 to 5.
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
Nested loops are loops inside another loop, commonly used for
multi-dimensional data processing.
Inner loop runs completely for each iteration of the outer loop.
Problem
Print a 3x3 matrix of numbers.
Code
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i*j);
}
printf("\n");
}
Problem
Exit the loop when a specific condition is met.
Code
for (int i = 1; i <= 10; i++) {
if (i == 6) break;
printf("%d ", i);
}
The ’continue’ statement skips the current iteration of a loop and moves
to the next.
Often used to skip certain conditions within a loop.
Problem
Skip even numbers in a loop.
Code
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
printf("%d ", i);
}
The ’goto’ statement directs the flow to a labeled part of the program.
Can be used for exiting multiple nested loops.
Generally discouraged due to readability and maintainability issues.
Problem
Using ’goto’ for error handling in nested loops.
Code
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (/* error condition */) {
goto error;
}
// process data
}
}
error:
// error handling code
Answers
1. ’break’ exits the loop completely, while ’continue’ skips to the next
iteration.
2. ’goto’ can be useful in nested loops for error handling, jumping out of
multiple loop levels.
Challenge
Write a program using ’if-else’ to categorize a character as a vowel or
consonant.
Challenge
Write a program using ’if-else’ to categorize a character as a vowel or
consonant.
Solution
char ch = ’a’;
if (ch == ’a’ || ch == ’e’ || ch == ’i’ ||
ch == ’o’ || ch == ’u’) {
printf("%c is a vowel", ch);
} else {
printf("%c is a consonant", ch);
}
Problem
Determine the most significant digit of a number.
Problem
Determine the most significant digit of a number.
Solution
int num = 982;
int significant = num;
while (significant >= 10) {
significant /= 10;
}
printf("Most significant digit: %d", significant);
Problem
Execute different math operations based on user input.
Problem
Execute different math operations based on user input.
Solution
char op = ’+’;
int a = 10, b = 5, result;
switch (op) {
case ’+’: result = a + b; break;
case ’-’: result = a - b; break;
case ’*’: result = a * b; break;
case ’/’: result = a / b; break;
default: printf("Invalid operation");
}
printf("Result: %d", result);
Problem
Print numbers divisible by either 2 or 3 up to 20.
Problem
Print numbers divisible by either 2 or 3 up to 20.
Solution
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0 || i % 3 == 0) {
printf("%d ", i);
}
}
Problem
Identify and fix the error in the following loop.
Problem
Identify and fix the error in the following loop.
Problem
Identify and fix the error in the following loop.
Fixed Code
for (int i = 0; i < 10; i += 2) {
printf("%d ", i);
}
Answers
1. A ’while’ loop checks the condition before executing, while a ’do-while’
loop executes at least once before checking.
2. Nested loops are used for multi-dimensional array processing, like
matrix operations.
Solution
int n = 50, flag = 0;
for (int i = 2; i <= n; i++) {
flag = 1;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1) {
printf("First prime number: %d", i);
break;
}
}
Module-2 Control and Loop statements 40/77
When to Use ’Continue’
Problem
Skip numbers that are not prime in a loop.
Problem
Skip numbers that are not prime in a loop.
Solution
for (int num = 2; num <= 20; num++) {
int isPrime = 1;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
if (!isPrime) continue;
printf("%d ", num);
}
Module-2 Control and Loop statements 41/77
’Goto’: Good or Bad?
Challenge
Write a loop that prints numbers from 1 to 10 but skips any number that
is a multiple of 3, and stops the loop if the number is 7.
Challenge
Write a loop that prints numbers from 1 to 10 but skips any number that
is a multiple of 3, and stops the loop if the number is 7.
Solution
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue;
if (i == 7) break;
printf("%d ", i);
}
Challenge
Implement a nested loop structure where an error in the inner loop leads
to a jump to an error-handling section using ’goto’.
Challenge
Implement a nested loop structure where an error in the inner loop leads
to a jump to an error-handling section using ’goto’.
Solution
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (/* error condition */) goto handleError;
// process data
}
}
handleError:
// error handling code
Advanced Example
Develop a program that checks if a number is both positive and even.
Advanced Example
Develop a program that checks if a number is both positive and even.
Solution
int num = 8;
if (num > 0 && num % 2 == 0) {
printf("Number is positive and even");
} else {
printf("Condition not met");
}
Solution
int count = 0;
for (int i = 2; count < 5; i++) {
int isPrime = 1;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime) {
printf("%d ", i);
count++;
}
}
Module-2 Control and Loop statements 50/77
Case Study: Simple Game Development
Scenario
Developing a simple number guessing game using loops and conditionals.
Game Logic
The computer picks a random number between 1 and 100.
The player guesses the number; the computer provides hints (’higher’
or ’lower’).
The game continues until the player guesses correctly or exits.
Code Overview
Provide an overview of the game’s code, highlighting the use of a ’while’
loop for the guessing process and ’if-else’ statements for hinting.
Code Snippet
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int number, guess, attempts = 0;
srand(time(0));
number = rand() % 100 + 1;//Random number from 1 to 100 Gameplay
printf("Guess the number (1 to 100):\n");
do { Output
scanf("%d", &guess); Guess: 50 → Lower!
attempts++; Guess: 25 → Higher!
Guess: 37 → Correct!
if (guess > number) { Attempts: 3
printf("Lower!\n");
} else if (guess < number) {
printf("Higher!\n");
}
} while (guess != number);
printf("Correct! Attempts: %d", attempts);
return 0;
}
Challenge Description
Develop a program to simulate a traffic light controller using control
statements. The traffic light should change from green to yellow, then to
red, and back to green, with appropriate time delays.
int main() {
char light = ’G’; // Start with Green
while (1) {
switch (light) {
case ’G’: printf("Green\n"); sleep(5); light = ’Y’; break;
case ’Y’: printf("Yellow\n"); sleep(2); light = ’R’; break;
case ’R’: printf("Red\n"); sleep(7); light = ’G’; break;
}
}
return 0;
}
Explanation
This program simulates a traffic light using a switch-case inside a loop.
The ‘sleep‘ function provides the delay.
Challenge Description
Create an algorithm for a simple checkout system in a store. The system
should calculate the total cost, apply discounts if applicable, and display
the final amount.
Task
Design an algorithm to simulate this scenario. Consider factors like
movement distance per turn and strategy to either capture or evade.
Module-2 Control and Loop statements 57/77
Solution to the Police-Thief Puzzle
Algorithm Approach
A strategy-based algorithm where both the police and the thief make
decisions each turn, considering factors like distance and potential
movement.
Pseudo-Code
Initialize positions of Police (P) and Thief (T)
while (distance between P and T is not zero) {
Update position of P based on strategy
Update position of T based on evasion
Check for capture condition
}
Key Concepts
Use loops for continuous checking, conditional statements for
decision-making, and movement strategies.
Module-2 Control and Loop statements 58/77
Police-Thief Grid Puzzle Simulation
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int policePos, thiefPos;
srand(time(NULL));
policePos = (rand() % 2 == 0) ? 1 : 4;
thiefPos = (policePos == 1) ? 4 : 5;
printf("Police: %d, Thief: %d\n", policePos, thiefPos);
while (policePos != thiefPos) {
policePos = (policePos % 5) + 1;
thiefPos = (thiefPos % 5) + 1;
printf("Police: %d, Thief: %d\n", policePos, thiefPos);
if (policePos == thiefPos) {
printf("Thief caught at %d\n", thiefPos);
break;
}
}
return 0;
} Module-2 Control and Loop statements 59/77
Crazy Gangster Puzzle
Puzzle Scenario
Let’s play a game of Russian roulette. You are tied to your chair and
can’t get up. Here’s a gun.
Crazy gangster with a 6-shot revolver
Initially all six chambers are empty.
He puts two bullets into adjacent chambers(in front of you), spins it
and closes the cylinder.
He now puts the gun to your head & pulls the trigger...
Puzzle Scenario
Let’s play a game of Russian roulette. You are tied to your chair and
can’t get up. Here’s a gun.
Crazy gangster with a 6-shot revolver
Initially all six chambers are empty.
He puts two bullets into adjacent chambers(in front of you), spins it
and closes the cylinder.
He now puts the gun to your head & pulls the trigger...
Luckily you survive.
He is going to pull the trigger again...
Puzzle Scenario
Let’s play a game of Russian roulette. You are tied to your chair and
can’t get up. Here’s a gun.
Crazy gangster with a 6-shot revolver
Initially all six chambers are empty.
He puts two bullets into adjacent chambers(in front of you), spins it
and closes the cylinder.
He now puts the gun to your head & pulls the trigger...
Luckily you survive.
He is going to pull the trigger again...
But before he proceeds he asks you for your preference whether:
1 - He should re-spin the cylinder then pull the trigger
2 - He should pull the trigger right away (no spin)
Question
A vending machine dispenses drinks only when the correct combination of
buttons is pressed. Implement this scenario in C using control structures.
Question
A vending machine dispenses drinks only when the correct combination of
buttons is pressed. Implement this scenario in C using control structures.
Challenge
Identify and correct the error in this C program intended to calculate the
sum of digits of a number.
Code Snippet
#include <stdio.h>
int main() {
int n = 1234, sum = 0;
while (n > 0) {
sum = sum + n % 10;
n = n / 10;
}
printf("Sum of digits: %d", sum);
return 0;
}
Module-2 Control and Loop statements 65/77
Solution to Code Debugging Challenge
Corrected Code
The provided code is actually correct. It successfully calculates the sum of
digits of the number 1234.
Output
Sum of digits: 10
Question
What will be the output of the following C code snippet?
#include <stdio.h>
int main() {
int x = 5;
printf("%d %d %d", x++, x, ++x);
return 0;
}
Question
Predict the output of the following C code snippet involving a loop and a
control statement:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
if (i == 4) break;
printf("%d ", i);
}
return 0;
}
Explanation
The loop iterates from 0 to 4. The ’continue’ statement skips the printing
when ’i’ is 2. The ’break’ statement stops the loop when ’i’ reaches 4.
Therefore, the numbers printed are 0, 1, and 3.
Output
013
Scenario-Based Question
Write a C program to simulate an automated door system that opens
when a sensor detects a person and closes after a certain delay.
int main() {
int sensorInput;
printf("Enter sensor input (1 for person detected, 0 other
scanf("%d", &sensorInput);
if (sensorInput == 1) {
printf("Door opening...\n");
sleep(5); // Represents delay
printf("Door closing...\n");
} else {
printf("No person detected. Door remains closed.\n");
}
return 0; Module-2 Control and Loop statements 71/77
Embedded C Program for 8051 - LED Blinking
Program: LED Blinking on 8051
Control an LED connected to a port on the 8051 microcontroller.
Code Snippet
#include <reg51.h>
void delay() {
// Simple delay function
int i, j;
for(i=0; i<1000; i++) {
for(j=0; j<100; j++) {}
}
}
void main() {
while(1) {
P1 = 0xFF; // Turn ON all LEDs
delay();
P1 = 0x00; // Turn OFF all LEDs
delay();
}
}
Module-2 Control and Loop statements 72/77
Explanation of LED Blinking Program
Program Operation
The program continuously turns all LEDs on and off with a delay in
between. It uses port 1 (P1) of the 8051 to control the LEDs.
Expected Output
The connected LEDs will blink on and off indefinitely.
Code Snippet
#include <reg51.h>
void main() {
P1 = 0xFF; // Configure Port 1 as input port
while(1) {
if (P1 == 0xFE) { // Check if button pressed
P2 = 0xFF; // Turn ON LED on Port 2
} else {
P2 = 0x00; // Turn OFF LED
}
}
}
Module-2 Control and Loop statements 74/77
Explanation of Button Controlled LED Program
Program Operation
The program reads input from a button connected to Port 1. When the
button is pressed, it turns on an LED connected to Port 2.
Expected Output
The LED on Port 2 toggles its state based on the button press.
Program Operation
The program reads temperature from a sensor connected to Port 1.
Depending on the temperature reading, it controls the fan speed
connected to Port 2 using nested if-else statements.
Expected Output
The fan speed varies (off, medium, high) based on the temperature
reading.
Code Snippet
#include <reg51.h>
#define MAX_TEMP 30
#define MID_TEMP 20
void delay() {
int i, j;
for(i=0; i<1000; i++) {
for(j=0; j<100; j++) {}
}
}
void main() {
int temp;
while(1) {
temp = P1; // Assume temperature reading from sensor
if (temp > MAX_TEMP) {
P2 = 0x03; // High speed
} else if (temp > MID_TEMP) {
P2 = 0x01; // Medium speed
} else {
P2 = 0x00; // Fan off
}
delay();
}
}