[go: up one dir, main page]

0% found this document useful (0 votes)
3 views37 pages

ET4102 Answers

The document contains a series of programming exercises and explanations related to C and Python, including error identification, object-oriented programming merits and demerits, and the use of header files. It also covers concepts such as sentinel-controlled loops, bitwise operations, and the C development environment. Additionally, it discusses hardware delays, loop timeouts, and provides examples of code implementations for various programming tasks.

Uploaded by

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

ET4102 Answers

The document contains a series of programming exercises and explanations related to C and Python, including error identification, object-oriented programming merits and demerits, and the use of header files. It also covers concepts such as sentinel-controlled loops, bitwise operations, and the C development environment. Additionally, it discusses hardware delays, loop timeouts, and provides examples of code implementations for various programming tasks.

Uploaded by

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

PART A — (10 × 2 = 20 marks)

1. Identify the errors in the following statements and correct it

(a) printf("the value of e is %d\n", &num);

• Error: Using &num instead of num.

• Correction: printf("the value of e is %d\n", num);

(b) if(a>5); {printf("a is greater than 5\n");}

• Error: Semicolon after if(a>5) ends the condition.

• Correction: if(a > 5) { printf("a is greater than 5\n"); }

2. Under which situation sentinel controlled loop is used?

A sentinel controlled loop is used when the number of iterations is not known in
advance. It continues looping until a special value (sentinel) is encountered, which
signals the end of input (e.g., reading numbers until -1 is entered).

3. State the merits and demerits of object-oriented programming.

Merits:

• Encapsulation improves modularity.

• Inheritance promotes code reusability.

• Polymorphism allows flexibility and dynamic behavior.

• Easier maintenance and scalability.

Demerits:

• Slower execution compared to procedural programming.

• Requires more memory.

• Can be more complex for small/simple programs.

• Steeper learning curve.


4. How the problem in the statement while (switch_pin = = 0) is rectified?

• Error: There is an extra space in the comparison operator.

• Correction: while (switch_pin == 0)


(use == without space for comparison instead of assignment =)

5. The acc compiling options for Objective C:

• -fgnu-runtime:
Use the GNU Objective-C runtime instead of the NeXT runtime.

• -fno-nil-receivers:
Disables the assumption that sending messages to nil (null objects) is safe.
This makes the compiler generate more defensive code.

6. What is the purpose of GNU binary utilities?

GNU Binary Utilities (binutils) are a collection of tools for working with binary files.
They include:

• as: the assembler

• ld: the linker

• objdump: displays information about object files

• nm: lists symbols

• strip: removes symbols


Purpose: Used in compiling, debugging, and manipulating binary files in
development.

7. Show the result of the following operations:

Given:

python

CopyEdit

>>> p = 40 # Binary: 00101000

>>> p << 2 # Shift left by 2 bits: 10100000 => 160


>>> q = 80 # Binary: 01010000

>>> q >> 2 # Shift right by 2 bits: 00010100 => 20

>>> p | q # Bitwise OR: 00101000 | 01010000 => 01111000 => 120

Results:

• p << 2 = 160

• q >> 2 = 20

• p | q = 120

8. Given the following code:

python

CopyEdit

vegetables = ["tomato", "carrot", "beans", "cauliflower", "drumstick"]

tuple_1 = (1, 0, 4, 6)

tuple_2 = (5, 6, 7, 9)

Output:

python

CopyEdit

tuple_1 + tuple_2 => (1, 0, 4, 6, 5, 6, 7, 9)

vegetables[1:4:2] => ['carrot', 'cauliflower']

9. Differentiate between module and package in Python

• Module: A single Python file (.py) containing functions, classes, etc.

• Package: A collection of Python modules in a directory containing an __init__.py file.

10. Using the imaging library write a Python code to convert a color image to
grayscale image
python

CopyEdit

from PIL import Image

image = Image.open("color_image.jpg")

gray_image = image.convert("L")

gray_image.save("gray_image.jpg")

PART B — (5 × 13 = 65 marks)

11. (a) (i) Block Diagram of C Development Environment (Expanded Explanation)

The C development process consists of multiple steps:

1. Editor

• Used to write and edit source code.

• Files saved with .c extension.

• Example: Notepad++, VS Code, Turbo C, etc.

2. Preprocessor

• Handles all preprocessor directives like #include, #define.

• Output: expanded source code.

3. Compiler

• Converts preprocessed code into assembly language.

• Detects syntax and semantic errors.

4. Assembler

• Converts assembly code into machine code (object file .o or .obj).

5. Linker
• Combines all object files and libraries into a final executable (.exe or .out).

6. Debugger

• Tools like GDB used for breakpoints, memory inspection, and stepwise
execution.

Diagram:

pgsql

CopyEdit

+---------+ +---------------+ +------------+ +------------+ +---------+

| Editor | --> | Preprocessor | --> | Compiler | --> | Assembler | --> | Linker |

+---------+ +---------------+ +------------+ +------------+ +---------+

+-------+

| Debug |

+-------+

11. (a) (ii) C Program Using switch and do...while

Rewritten with functions and better formatting:

CopyEdit

#include <stdio.h>

void menu() {

printf("\nMenu:\n");

printf("1. Addition\n");

printf("2. Subtraction\n");

printf("3. Exit\n");
}

int main() {

int a, b, choice;

do {

menu();

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

printf("Sum = %d\n", a + b);

break;

case 2:

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

printf("Difference = %d\n", a - b);

break;

case 3:

printf("Exiting program.\n");

break;
default:

printf("Invalid choice.\n");

} while (choice != 3);

return 0;

12. (a)

(i) Explain the need for Project Header and Port Header files

In C/C++ development, header files are crucial for organizing code and enabling
reuse. A project header file (.h) defines the interface for a project's components,
while a port header file, often named port.h, contains platform-specific code, often
targeting specific hardware or operating systems.

Project Header File (.h):

• Interface Definition:

Project header files define the functions, structures, classes, and other elements that
other parts of the project can use. They provide a contract for interacting with the
project's components.

• Organization:

They help organize code by grouping related functionalities into logical units, making
it easier to manage large projects.

• Reusability:

By clearly defining interfaces, header files enable code to be reused across different
modules and even different projects.

• Example:

A header file might define functions for interacting with a database, a user interface,
or a networking library.

Port Header File (port.h or similar):


• Platform Abstraction:

Port header files provide platform-specific code that can be used to adapt the project
to different environments, hardware, or operating systems.

• Conditional Compilation:

They often use #ifdef and #ifndef preprocessor directives to conditionally include
platform-specific code.

• Targeting Hardware:

In embedded systems development, port headers might contain definitions for


hardware registers, peripherals, and platform-specific APIs.

• Example:

A port header might contain code for interacting with a specific microcontroller, a
specific operating system API, or different hardware interfaces.

Benefits of Using Header Files:

• Code Reusability:

Header files allow for the reuse of code across different modules and even different
projects.

• Improved Organization:

They help organize code, making it easier to manage and maintain large projects.

• Enhanced Maintainability:

By clearly defining interfaces, header files make it easier to modify and update code
without affecting other parts of the project.

• Reduced Compilation Time:

Using header files can significantly reduce compilation time, especially in large
projects.

In summary: Project header files define the interface of a project, while port header
files provide platform-specific code, making them essential for organizing and
adapting projects to different environments.

(ii) How is hardware delay implemented using timer and interrupt?


Hardware delays, using timers and interrupts, are implemented by configuring a
hardware timer to count down or up for a specified duration and then triggering an
interrupt when the timer reaches a specific value. This interrupt then signals to the
system that the delay has elapsed, allowing the microcontroller to continue executing
other tasks while waiting for the delay.

Elaboration:

1. 1. Timer Configuration:

• The timer is typically configured with a desired resolution and a


prescaler value to determine the rate at which it counts.

• The timer is loaded with a value representing the desired delay


duration.

• The timer is then started, and the interrupt is enabled.

2. 2. Interrupt Handling:

• When the timer reaches the programmed value (or overflows), it


generates an interrupt signal to the microcontroller.

• The microcontroller then suspends its current execution and transfers


control to an interrupt service routine (ISR).

3. 3. ISR Implementation:

• The ISR is responsible for handling the timer interrupt and any
necessary actions upon the delay completion.

• This might include updating global variables, triggering other actions,


or returning control to the main program.

• After the ISR completes, the microcontroller returns to where it was


interrupted.

4. 4. Benefits:

• Precise Timing: Hardware timers offer better precision and accuracy


compared to software-based delays, according to ScienceDirect topics.

• Efficient Multitasking: By using interrupts, the microcontroller can


perform other tasks while the timer counts down, enhancing efficiency
and responsiveness according to DeepBlueMbedded.

• Non-Blocking: Unlike software delays, which can tie up the CPU while
waiting, hardware delays allow the microcontroller to continue
executing other tasks while the timer runs in the background.
(b) With suitable example explain the creation of loop time out and hardware time
out?

Loop Timeout

• Definition: A loop timeout is a mechanism that limits how long a loop can
execute. If the loop doesn't complete within the specified time, it's terminated,
preventing the program from getting stuck in an infinite loop.

• Implementation: Loop timeouts are typically implemented by checking the


elapsed time within the loop. Before the loop starts, the current time is
recorded. Inside the loop, the current time is compared with the start time. If
the difference exceeds the timeout duration, the loop is exited.

• Example:

#include <stdio.h>
#include <time.h>

int main() {
time_t startTime = time(NULL);
time_t timeout = 5; // Timeout of 5 seconds

while (1) {
// Code to be executed in the loop
printf("Looping...\n");
if (time(NULL) - startTime > timeout) {
printf("Loop timed out!\n");
break; // Exit the loop
}
}
return 0;
}

Hardware Timeout

• Definition: A hardware timeout is a delay mechanism that is built into


hardware devices, such as microcontrollers or communication interfaces. It is
used to ensure that the device does not get stuck waiting indefinitely for a
response or an event.

• Implementation: Hardware timeouts are typically managed by a timer within


the hardware device. When a timeout period is started, the timer counts
down. If the expected event or response does not occur before the timer
reaches zero, a timeout signal is generated.

• Example:

#include "stm32f4xx.h" // Assuming STM32 microcontroller

void configure_timeout(uint32_t timeout_ms) {


SysTick->LOAD = (SystemCoreClock / 1000 * timeout_ms) - 1;
SysTick->VAL = 0;
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_ENABLE_Msk;
}

int check_timeout() {
return (SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) != 0;
}

Key Differences

• Scope:

Loop timeouts are implemented in software, while hardware timeouts are


implemented in hardware.

• Purpose:

Loop timeouts are used to prevent indefinite loops in software, while hardware
timeouts are used to prevent indefinite waits in hardware devices.

• Granularity:

Loop timeouts can be configured with relatively fine-grained control, while hardware
timeouts may have limited configuration options.

• Accuracy:

Hardware timeouts are generally more accurate and reliable than software-based
loop timeouts.

When to Use Which

• Use loop timeouts when you need to limit the execution time of a loop in your
software.
• Use hardware timeouts when you are working with hardware devices and
need to ensure that the device does not wait indefinitely for a response.

11. (a)

(i) C Development Environment

The C development environment consists of several key components that work


together to create, compile, and debug C programs:

1. Editor: This is where you write your source code. Popular editors include
Visual Studio Code, Sublime Text, and Notepad++.

2. Preprocessor: The preprocessor processes directives before the actual


compilation begins. It handles directives like #include, #define, and
conditional compilation.

3. Compiler: The compiler translates the source code into object code. GCC (GNU
Compiler Collection) is a widely used compiler for C.

4. Linker: The linker combines multiple object files into a single executable file.
It resolves references between different object files.

5. Debugger: The debugger helps you find and fix errors in your code. GDB (GNU
Debugger) is a common tool used for debugging C programs.

(ii) Case and Do While Statements

• Case Statement: The case statement is part of the switch-case construct, which
allows you to execute one block of code among many based on the value of a
variable.

• Do While Statement: The do-while loop is similar to the while loop, but it
guarantees that the loop body is executed at least once before the condition is
checked.

11. (b)

(i) Function to Find Minimum of Three Numbers

To find the minimum of three numbers, you can write a function like this:

• Call by Value: When a function is called by value, a copy of the actual


parameter is passed to the function. Changes made to the parameter inside
the function do not affect the original value.

• Call by Reference: When a function is called by reference, the address of the


actual parameter is passed to the function. Changes made to the parameter
inside the function affect the original value.
(ii) Manipulations in Two-Dimensional Array

Two-dimensional arrays can be manipulated in various ways, such as accessing and


modifying elements:

12. (a)

(i) Project Header and Port Header

• Project Header: The project header file contains project-specific definitions


and includes. It helps in organizing the code and making it modular.

• Port Header: The port header file contains hardware-specific definitions and
includes. It is used to define ports and other hardware-related configurations.

(ii) Creating Hardware Delays Using Timers and Interrupts

• Timers: Hardware timers can be configured to create precise delays. The


timer is set up to generate an interrupt after a specified period.

• Interrupts: Interrupts can be used to handle timing events. When the timer
reaches the specified period, it generates an interrupt, and the interrupt
handler executes the delay logic.

12. (b)

Loop Timeout and Hardware Timeout

• Loop Timeout: A loop timeout can be implemented by decrementing a counter


within a loop. If the counter reaches zero, the loop exits.

• Hardware Timeout: Hardware timers can be configured to generate a timeout.


The timer is set up to count down from a specified value, and when it reaches
zero, it generates an interrupt.

13. (a)

(i) Debugging with GDB

GDB (GNU Debugger) is a powerful tool for debugging C programs. It allows you to set
breakpoints, step through code, inspect variables, and more.

• Start GDB: gdb ./a.out

• Set Breakpoint: break main

• Run Program: run

• Step Through Code: next or step


• Inspect Variables: print var_name

(ii) Compilation Stages

The compilation process in C involves several stages:

1. Preprocessing: The preprocessor handles directives


like #include and #define. It generates an intermediate file with expanded
macros and included files.

2. Compilation: The compiler translates the preprocessed code into assembly


language.

3. Assembly: The assembler converts the assembly code into machine code,
generating object files.

4. Linking: The linker combines multiple object files into a single executable file,
resolving references between different object files.

3. (b) (i) Features of GCC (GNU Compiler Collection)

GCC (GNU Compiler Collection) is an open-source, high-performance compiler system


developed by the GNU Project. It is a key component of the GNU toolchain and serves
as the default compiler for many Unix-like systems, including Linux.

Key Features of GCC:

1. Multi-language Support:

o GCC supports compilation of multiple programming languages:

▪ C (GCC’s core language),

▪ C++, Objective-C, Fortran, Ada, Go, D.

o Enables development in mixed-language environments.

2. Cross-platform and Cross-compilation:

o GCC can generate machine code for different platforms (ARM, x86,
PowerPC).

o Cross-compilation is especially useful in embedded systems, where


code is compiled on a desktop and run on microcontrollers.

3. Standards Compliance:

o GCC supports the latest international language standards (e.g., C11,


C17, C++17, C++20).
o Ensures portability and modern programming practices.

4. Extensive Optimization Options:

o Improves runtime performance, reduces size, and speeds up execution.

o Optimization flags:

▪ -O0: No optimization

▪ -O1, -O2, -O3: Increasing levels of optimization

▪ -Os: Optimize for size

▪ -flto: Link Time Optimization

▪ -fprofile-generate/use: Profile-guided optimization

5. Diagnostic and Debugging Support:

o Provides detailed warnings and errors (-Wall, -Wextra).

o Generates debug info (-g) compatible with GDB.

6. Modular and Extensible Architecture:

o Easy to add new language frontends and backend targets.

o Used as a backend in other tools like Clang, LLVM.

7. Free and Open Source:

o Distributed under the GNU GPL.

o Actively developed and maintained by a global community.

o Allows users to inspect and modify source code.

8. Wide Adoption:

o Default compiler for Linux distributions.

o Supported by many IDEs and build systems (e.g., Eclipse, Make,


CMake).

13. (b) (ii) GNU Configure and Build System

The GNU Build System, also known as Autotools, is a set of utilities used to create
portable software packages that can be compiled on various UNIX-like systems.
Components of the GNU Build System:

1. Autoconf:

o Generates a configure script using templates.

o Checks system features, compilers, libraries, and functions.

o Creates appropriate headers and makefiles.

2. Automake:

o Generates Makefile.in from high-level Makefile.am.

o Simplifies the process of writing platform-independent makefiles.

3. Libtool:

o Helps create portable shared and static libraries.

o Abstracts the complexity of different system’s library mechanisms.

4. Configure Script:

o End-user runs ./configure to detect system settings.

o Produces customized Makefile and header files (config.h).

5. Make:

o Processes the Makefile.

o Manages compiling and linking of source files.

6. Standardization:

o ./configure, make, make install is the standard build/install flow.

o Used by major open-source projects like GNOME, GIMP, and GNU tools.

7. Portability:

o Ensures software compiles correctly on multiple systems with minimal


changes.

o Detects system-specific features at compile time.

14. (a) Python Indentation, Type Conversion, and Exception Handling


1. Indentation in Python

• Python uses indentation to define code blocks instead of curly braces {}.

• All statements within a control structure (like if, while, def) must be
consistently indented.

Importance:

• Mandatory, not optional.

• IndentationError is raised for incorrect indentation.

Example:

python

CopyEdit

def greet():

print("Hello") # Properly indented block

2. Type Conversion in Python

Implicit Conversion:

• Python automatically converts smaller data types to larger ones.

python

CopyEdit

x=5

y = 2.5

print(x + y) # Result is 7.5 (int → float)

Explicit Conversion:

• Programmer manually converts data using type casting functions:

o int(), float(), str(), list(), tuple()

Example:

python
CopyEdit

a = "100"

b = int(a) # string to integer

3. Exception Handling

Python uses try-except-finally blocks to handle run-time errors gracefully.

Syntax:

python

CopyEdit

try:

x = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero.")

finally:

print("Done.")

• try: Contains risky code.

• except: Catches and handles exceptions.

• finally: Executes always (even if error occurs).

14. (b) Functions, Dictionaries, Tuples, If-Else

Functions in Python

• Used to encapsulate logic for reuse.

• Defined using def keyword.

python

CopyEdit

def add(x, y):


return x + y

Dictionaries

• Store key-value pairs.

• Keys must be unique and immutable.

python

CopyEdit

student = {"name": "Alice", "marks": 90}

Tuples

• Ordered, immutable sequences.

• Defined using () brackets.

python

CopyEdit

dimensions = (1920, 1080)

If-Else Statements

Used for decision-making.

python

CopyEdit

x = 10

if x > 0:

print("Positive")

else:

print("Non-positive")
15. (a) Python Modules, Packages, GUI, Networking

Modules and Packages

• Module: A .py file containing reusable code.

python

CopyEdit

# mymodule.py

def hello():

return "Hello"

• Package: A directory with __init__.py and modules.

bash

CopyEdit

mypackage/

__init__.py

tools.py

GUI Libraries in Python

1. Tkinter: Default GUI in Python; simple applications.

2. PyQt: Advanced features, cross-platform.

3. Kivy: Used for mobile app GUIs.

Networking Libraries

1. socket: Low-level TCP/UDP communication.

2. requests: Simplified HTTP communication.

3. twisted: Event-driven networking for complex apps.

15. (b) Imaging and Plotting Libraries


Imaging Libraries

1. Pillow (PIL):

o Open and manipulate image files.

python

CopyEdit

from PIL import Image

img = Image.open("img.jpg")

img.show()

2. OpenCV:

o Real-time image/video processing.

o Used in AI and computer vision.

Numerical Plotting: Matplotlib

• Used to create 2D plots, charts, and graphs.

• Compatible with NumPy for scientific data.

Example:

python

CopyEdit

import matplotlib.pyplot as plt

x = [1, 2, 3]

y = [10, 20, 30]

plt.plot(x, y)

plt.title("Sample Graph")

plt.show()

6. (a) Structured Code to Count the Number of Goats Passing a Milk Parlour Using
Embedded C
Theory + Code Explanation:

In an embedded system, we can count the number of goats using a sensor-based


approach (like an IR sensor) at the gate of a milk parlour. Every time a goat passes
through and breaks the beam, a counter is incremented.

We simulate this with a structured C program using:

• A counter variable,

• Interrupt Service Routine (ISR) or polling mechanism (simulated in C),

• Debouncing/delay logic to avoid multiple counts.

Embedded C Code:

CopyEdit

#include <stdio.h>

#include <stdbool.h>

#include <stdint.h>

// Simulate sensor input: 1 when goat is present, 0 otherwise

bool read_sensor() {

static int pass_count = 0;

pass_count++;

if (pass_count % 5 == 0) // simulate goat every 5 calls

return true;

return false;

void delay() {

// Simulated delay to debounce or avoid multiple triggers

for (volatile long i = 0; i < 100000; i++);


}

int main() {

uint16_t goat_count = 0;

bool last_state = false;

printf("Goat Counter System Started...\n");

for (int t = 0; t < 1000; t++) { // simulate 1000 time units

bool sensor = read_sensor();

// Count only on rising edge (goat just entered)

if (sensor && !last_state) {

goat_count++;

printf("Goat Passed! Total Count = %d\n", goat_count);

delay(); // debounce delay

last_state = sensor;

printf("Final Goat Count: %d\n", goat_count);

return 0;

16. (b) Airline Seat Assignment Program in C


Theory:

• Flight has 20 seats.

o 1–10: Business class

o 11–20: Economy class

• Passengers select preferred class.

• If full, prompt to reassign or wait for next flight.

• Show boarding pass for assigned seat.

C Code with Structured Menu:

CopyEdit

#include <stdio.h>

#define TOTAL_SEATS 20

#define BUSINESS_END 10

int seats[TOTAL_SEATS] = {0}; // 0 - available, 1 - booked

void print_boarding_pass(int seat_num) {

if (seat_num <= 10)

printf("Boarding Pass: Seat #%d - Business Class\n", seat_num);

else

printf("Boarding Pass: Seat #%d - Economy Class\n", seat_num);

int assign_seat(int start, int end) {

for (int i = start - 1; i < end; i++) {


if (seats[i] == 0) {

seats[i] = 1;

return i + 1;

return -1; // No seat available

int main() {

int choice;

while (1) {

printf("\nPlease type 1 for Business Class\n");

printf("Please type 2 for Economy Class\n");

printf("Enter your choice (0 to exit): ");

scanf("%d", &choice);

if (choice == 0)

break;

if (choice == 1) {

int seat = assign_seat(1, 10);

if (seat != -1) {

print_boarding_pass(seat);

} else {
printf("Business class is full. Do you want Economy class instead? (1 = Yes, 0 =
No): ");

int opt;

scanf("%d", &opt);

if (opt == 1) {

seat = assign_seat(11, 20);

if (seat != -1)

print_boarding_pass(seat);

else

printf("All seats full. Next flight in 3 hours.\n");

} else {

printf("Next flight will leave in 3 hours.\n");

} else if (choice == 2) {

int seat = assign_seat(11, 20);

if (seat != -1) {

print_boarding_pass(seat);

} else {

printf("Economy class is full. Do you want Business class instead? (1 = Yes, 0 =


No): ");

int opt;

scanf("%d", &opt);

if (opt == 1) {

seat = assign_seat(1, 10);

if (seat != -1)

print_boarding_pass(seat);
else

printf("All seats full. Next flight in 3 hours.\n");

} else {

printf("Next flight will leave in 3 hours.\n");

} else {

printf("Invalid input. Please try again.\n");

return 0;

ET4102: Software for Embedded Systems - PART B (6 x 13 = 78 Marks)

11. (a) C Program to Check Credit Limit Exceeded

This program helps a department store determine whether a customer's credit limit
has been exceeded. The necessary input includes:

1. Account number

2. Beginning balance of the month

3. Total charges made during the month

4. Total credits applied

5. Allowed credit limit

Theory Explanation:

• The program computes the new balance as:

• new_balance = beginning_balance + charges - credits


• If the new balance exceeds the allowed credit limit, the program displays a
warning message.

• This process is part of financial monitoring systems in embedded applications


used in point-of-sale terminals or account validation systems.

Structured C Code:

#include <stdio.h>

int main() {

int accountNumber;

float beginningBalance, totalCharges, totalCredits, creditLimit, newBalance;

printf("Enter account number: ");

scanf("%d", &accountNumber);

printf("Enter beginning balance: ");

scanf("%f", &beginningBalance);

printf("Enter total charges: ");

scanf("%f", &totalCharges);

printf("Enter total credits: ");

scanf("%f", &totalCredits);

printf("Enter credit limit: ");

scanf("%f", &creditLimit);

newBalance = beginningBalance + totalCharges - totalCredits;


printf("\nAccount Number: %d", accountNumber);

printf("\nNew Balance: %.2f", newBalance);

printf("\nCredit Limit: %.2f", creditLimit);

if (newBalance > creditLimit) {

printf("\nCredit limit exceeded.\n");

} else {

printf("\nWithin the credit limit.\n");

return 0;

11. (b) Decision Control Statements in C

1. if Statement:
Executes a block of code if a specified condition is true.

if (age > 18) {

printf("Eligible to vote.\n");

2. if-else Statement:
Used when a condition has two outcomes.

if (marks >= 50) {

printf("Pass\n");

} else {

printf("Fail\n");

3. switch Statement:
Used to execute one block of code among many alternatives.
int grade = 2;

switch (grade) {

case 1: printf("Excellent\n"); break;

case 2: printf("Good\n"); break;

case 3: printf("Average\n"); break;

default: printf("Invalid Grade\n");

Decision control statements are essential in embedded systems for managing


execution flow based on sensor values, user inputs, or system status.

12. (a) Project Header and Port Header Files

Project Header Files:


These define project-wide constants, macros, and function declarations that are
reused across multiple source files.

Example: project.h

#define LED_ON 1

#define LED_OFF 0

void init_system();

Purpose:

• Provides consistency

• Reduces redundancy

• Easy maintenance

Port Header Files:


They define the mapping of hardware-specific pins to logical names.

Example: port.h

#define PORTA_DIR (*(volatile unsigned char *)0x1234)

#define PORTA_OUT (*(volatile unsigned char *)0x1235)

Purpose:
• Hardware abstraction

• Helps in porting code to other microcontrollers by modifying only this file.

12. (b) Timeout Mechanism and Loop Timeout

Need for Timeout:

• Prevents endless waiting due to communication failure

• Ensures real-time responsiveness

• Required in communication protocols and device waiting scenarios

Loop Timeout Implementation:


Use a counter or timer variable to break out of a loop after a certain time or number
of attempts.

Example:

int timeout = 1000;

while (!device_ready()) {

if (--timeout == 0) {

printf("Timeout occurred\n");

break;

Instances in Embedded Systems:

• Waiting for sensor readiness

• Data transmission timeouts

• Device initialization

13. (a) GCC and Common Commands

GCC (GNU Compiler Collection):


A standard open-source compiler supporting languages like C, C++, etc.

Features:
• Multilanguage support

• Platform independence

• Extensive optimization options

• Standards compliant

• Modular and extensible

Common GCC Commands:

1. Compile a program:

gcc program.c -o output

2. Compile with debugging:

gcc -g program.c -o output

3. Enable optimization:

gcc -O2 program.c -o output

4. Generate assembly:

gcc -S program.c

5. Compile only:

gcc -c file.c

13. (b) (i) Profiling with gprof

gprof:
A performance analysis tool for applications compiled with GCC.

Steps:

1. Compile with -pg flag:

gcc -pg program.c -o prog

2. Run the program:

./prog

3. Analyze:

gprof prog gmon.out > analysis.txt


Outputs:

• Time spent in each function

• Call graph information

(ii) GNU C Library (glibc):


A core part of the GNU system that provides system call wrappers and standard C
library functions.

Features:

• Memory handling (malloc, free)

• Input/output (printf, scanf)

• String manipulation (strcpy, strcat)

• Process control (fork, exec)

• Signal handling

14. (a) Python Functions

Definition:
Functions are reusable blocks of code.

Syntax:

def greet(name):

print("Hello,", name)

greet("Alice")

Types:

• Built-in: len(), type()

• User-defined

Advantages:

• Code reuse

• Easy debugging
• Modular design

14. (b) Python List Operations

i. Creating List:

fruits = ["apple", "banana", "cherry"]

ii. Accessing Values:

print(fruits[1]) # banana

iii. Updating List:

fruits[1] = "orange"

iv. Deleting Elements:

del fruits[2]

15. (a) Python Modules and Packages

Module:
A Python file with functions/classes.

# mymodule.py

def add(a, b): return a + b

Package:
A directory with __init__.py file containing modules.

Usage:

from mypackage import mymodule

print(mymodule.add(2, 3))

15. (b) Python Libraries and GUI Libraries

General Purpose Libraries:

• math: math functions

• datetime: date/time operations

• random: random numbers

GUI Libraries:
• Tkinter: built-in GUI toolkit

• PyQt: powerful widget-based GUI

• Kivy: multi-touch GUI for mobile and desktop

Example:

import tkinter as tk

root = tk.Tk()

root.title("GUI Example")

root.mainloop()

PART C (1 x 15 = 15 marks)

16. (a) C Program to Analyze Exam Results

This problem involves analyzing test results of students who took a licensing
examination. The objective is to:

1. Input the test results for 10 students.

2. Count how many students passed and failed.

3. Display the summary.

4. If more than 8 students passed, display a bonus message.

Theoretical Explanation:

• Arrays and counters are used to collect and analyze test results.

• A loop inputs 10 results from the user.

• Conditions are used to count pass/fail outcomes.

• Decision logic checks for the bonus criteria.

C Code:

#include <stdio.h>

int main() {
int result, pass = 0, fail = 0;

for (int i = 1; i <= 10; i++) {

printf("Enter result (1 = pass, 2 = fail) for student %d: ", i);

scanf("%d", &result);

if (result == 1)

pass++;

else if (result == 2)

fail++;

else {

printf("Invalid input. Try again.\n");

i--;

printf("\nSummary of Results:\n");

printf("Passed: %d\n", pass);

printf("Failed: %d\n", fail);

if (pass > 8) {

printf("Bonus to instructor!\n");

return 0;

16. (b) Python Program for Set Operations


This program demonstrates core set operations in Python:

1. Intersection – common elements

2. Union – all elements

3. Difference – elements in one but not in other

4. Symmetric Difference – elements in either but not both

Theoretical Explanation:

• Sets are used to store unique elements.

• Python provides built-in methods to perform set theory operations.

Python Code:

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

print("Set A:", A)

print("Set B:", B)

print("Intersection:", A & B)

print("Union:", A | B)

print("Difference (A - B):", A - B)

print("Symmetric Difference:", A ^ B)

These operations are widely used in data processing, filtering, and logic comparisons.

End of Part B and Part C Answers

You might also like