SlideShare a Scribd company logo
Embedded C Programming
Module-1: Introduction to C
Dr. Markkandan S
School of Electronics Engineering (SENSE)
Vellore Institute of Technology
Chennai
Dr. Markkandan S (School of Electronics Engineering (SENSE)Vellore Institute of Technology Chennai)
Embedded C Programming Module-1: Introduction to C 1 / 62
C Programming - Overview
General purpose programming language
Developed by Dennis Ritchie
Strengths - flexibility, efficiency, widespread use
Used for embedded systems, OS, applications
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 2/62
Features of C Language
Structured programming approach
Direct low-level hardware access
Rich set of built-in operators and functions
Example Program:
#include <stdio.h>
int main() {
printf("Hello World n");
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 3/62
Introduction to Embedded C
Program for embedded devices/control, robotics etc.
Programming for microcontrollers/MCU
Tightly constrained resource usage
Low level control of hardware
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 4/62
Difference: C vs Embedded C
C Language:
High level language
Large standard library
Platform independent
Dynamic memory allocation
Embedded C:
Tightly constrained
No standard library
Platform specific
Static allocation
Key constraints while programming for embedded systems.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 5/62
Basic C Program Structure
Structure:
1 Include necessary header
files
2 Declare global variables
3 Define functions
4 Implement the main
function
#include <stdio.h>
// Declare global variables
int globalVar = 10;
// Function declaration
void myFunction();
int main() {
// Implementation of main function
printf("Hello, C Programming!");
return 0;
}
// Function definition
void myFunction() {
// Implementation of myFunction
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 6/62
Basic C Program Structure
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 7/62
Embedded C Program Structure
Interaction with hardware
Memory considerations
Real-time constraints
#include <avr/io.h>
// Declare global variables
volatile uint8_t sensorValue;
// Function declaration
void initializeSensor();
int main() {
// Implementation of main function
initializeSensor();
while(1) {
// Real-time processing
sensorValue = readSensor();
}
}
void initializeSensor() {
// Hardware initialization
}
uint8_t readSensor() {
// Read data from sensor
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 8/62
Find the Output
#include <stdio.h>
int main() {
int x = 5, y = 3;
printf("%d", x + y);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 9/62
Find the Output
#include <stdio.h>
int main() {
int x = 5, y = 3;
printf("%d", x + y);
return 0;
}
Answer
The output of the code is 8.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 9/62
Introduction to Compilation Process
Pre-processing
Compilation
Assembly
Linking
#include <stdio.h>
#define MAX 10
int main() {
int i = MAX;
printf("Maximum value is: %d", i);
return 0;
}
The compilation process converts source code to executable machine code.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 10/62
Compilation Process
Preprocessor handles directives (like ‘include‘),
compiler translates C to Assembly, assembler to
machine code, linker resolves references.
Tools: C Compiler (e.g., gcc), Assembler (e.g.,
as), Linker (e.g., ld).
Terminal or GCC Compilation
gcc -E main.c -o main.i # Preprocessing
gcc -S main.i -o main.s # Compilation to assembly
as main.s -o main.o # Assembly to object code
ld main.o -o main # Linking object code to
executable
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 11/62
Compilation Process
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 12/62
Comments
Single Line Comment
Used to provide descriptions and explanations in code.
Format: // Comments
Example
#include <stdio.h>
int main(){
// Print statement
printf("Hello World!");
return 0;
}
Comments help document the code functionality and are ignored by
compiler.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 13/62
Multi-line Comments
Syntax
Used to comment multiple lines or blocks of code.
Format:
/* This is a
multi-line
comment */
Example
/* Comments message
across multiple
lines */
printf("Hello World!");
printf("From C program");
Multi-line comments are convenient for commenting code sections.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 14/62
Identifiers
Naming Rules
Start with letter or underscore
Can have letters, digits, underscores
Case sensitive index ̸= INDEX
No whitespaces allowed
Example
#include <stdio.h>
int main() {
int final_count; // valid
int 123Invalid; // invalid
return 0;
}
Identifiers refer to user defined names for variables, functions etc. in C.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 15/62
Variables
Declaring Variables
Specify data type and name: datatype name;
int count;
float price;
char code;
Initializing Variables
Assign initial value: datatype name = value;
int sum = 0;
float pie = 3.14;
char grade = ’A’;
Variables represent memory locations to store program data.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 16/62
In-depth Variable Types and Storage Classes
Global Variables: Accessible throughout the program. Example: int globalVar;
Local Variables: Accessible only within the function. Example: void func() { int
localVar; }
Static Variables: Retains value between function calls. Example: static int
staticVar;
Register Variables: Stored in CPU register for faster access. Example: register int
loopCounter;
// Global Variable
int globalVar;
void function() {
// Local Variable
int localVar;
// Static Variable
static int staticVar = 0;
staticVar++;
// Register Variable
for(register int i = 0; i < 10; i++) {
// Fast access within loop
}
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 17/62
Header Files
# include
Includes external library contents in program:
#include <stdio.h>
#include "myutils.h"
Commonly used library headers in C:
stdio.h - standard I/O functions
math.h - mathematical operations
string.h - string handling
Header files contain reusable code functionalities.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 18/62
Data Types
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 19/62
Data Types
Primitive types
int, float, double
char
Derived types
Array, pointer
Structure, union
#include <stdio.h>
int main() {
// Primitive types
int num = 10;
float pi = 3.14;
double height = 79.234;
char x = ’A’;
// Derived types
int arr[5];
struct student {
int id;
char name[20];
} s1;
int* ptr = #
union data {
int i;
float f;
} val;
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 20/62
Data Types
Character Types % Format Size Range
unsigned char %c 1 byte 0 to 255
char %c 1 byte -128 to 127
signed char %c 1 byte -128 to 127
Integer Types
unsigned short int %hu 2 bytes 0 to 65,535
short int %hd 2 bytes -32,768 to 32,767
signed short int %hd 2 bytes -32,768 to 32,767
unsigned int %u 2/4 bytes 0 to 65,535 or 0 to 4,294,967,295
int %d 2/4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
signed int %d 2/4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
long int %ld 4/8 bytes -2,147,483,648 to 2,147,483,647
unsigned long int %lu 4/8 bytes 0 to 4,294,967,295 or 0 to 18,446,744,073,709,551,615
signed long int %ld 4/8 bytes -2,147,483,648 to 2,147,483,647
long long int %lld 8 bytes -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
unsigned long long int %llu 8 bytes 0 to 18,446,744,073,709,551,615
Float Types
float %f 4 bytes ± 1.2E-38 to ± 3.4E+38
double %lf 8 bytes ± 2.3E-308 to ± 1.7E+308
long double %Lf 12 bytes ± 3.4E–4932 to ± 1.1E+4932
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 21/62
Exploring Data Types and Sizes
#include <stdio.h>
int main() {
printf("Size of int: %lu bytesn", sizeof(int));
printf("Size of char: %lu byten", sizeof(char));
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 22/62
Exploring Data Types and Sizes
#include <stdio.h>
int main() {
printf("Size of int: %lu bytesn", sizeof(int));
printf("Size of char: %lu byten", sizeof(char));
return 0;
}
Question
What will be the output of this program?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 22/62
Exploring Data Types and Sizes
#include <stdio.h>
int main() {
printf("Size of int: %lu bytesn", sizeof(int));
printf("Size of char: %lu byten", sizeof(char));
return 0;
}
Question
What will be the output of this program?
Answer
The output will display the size of ’int’ and ’char’ in bytes. Typically, it
will be ”Size of int: 4 bytes” and ”Size of char: 1 byte”, but this can vary
depending on the system architecture.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 22/62
Arithmetic Operators
+ − ∗ / %
Arithmetic Operators
x = y + 2; // Addition
z = p − 5; // S u b t r a c t i o n
area = l e n g t h ∗ breadth ; // M u l t i p l i c a t i o n
q = a / b ; // D i v i s i o n
r = 15 % 4; // Modulus
Precedence
Follows order - Exponential > Multiplicative > Additive
a = b + ( c ∗ 2 ) ; // precedence
z = 3 ∗ x / 5;
i n t num = 15;
f l o a t v a l = num ; // t y p e c a s t i n g
num + v a l ;
Typecasting allows same operands to be treated as different types.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 23/62
Relational Operators
> < >= <= ! =
Chaining Relational Operators
i f ( a > 50) // Greater than
p r i n t f ( ”a i s big ” ) ;
i f ( b < 20) // Less than
p r i n t f ( ”b i s s m a l l ” ) ;
i f ( s t r == ” t e s t ” ) // Equal to
p r i n t f ( ” S t r i n g s matched” ) ;
i f ( i != 10) // Not equal to
p r i n t ( ” i i s not 10” ) ;
i f ( age >= 18) // Greater than equal to
p r i n t f ( ” E l i g i b l e ” ) ;
i f ( marks <= 35) // Less than equal to
p r i n t f ( ” F a i l e d ” ) ;
// M u l t i p l e c o n d i t i o n a l checks can be chained :
i f ( x > 5 && x < 10) {
. . .
}
Relational operators can be combined using logical operators.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 24/62
Logical Operators
Used to combine multiple logical
conditions:
&& - Logical AND
|| - Logical OR
! - Logical NOT
int a = 5;
int b = 10;
if(a < 8 && b >= 10) {
printf("AND condition met");
}
if(a < 8 || b < 5) {
printf("OR condition met");
}
if(!(b == 15)) {
printf("NOT condition met");
}
Logical operators are used to implement conditional logic.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 25/62
Bitwise Operators
Used to manipulate individual bits:
& - Bitwise AND : Compares bits
| - Bitwise OR : Makes bits 1 if set in either
b- Bitwise XOR : Makes bits 1 if different
∼ - Bitwise NOT : Inverts all bits
int a = 12; // 0000 1100
int b = 25; // 0001 1001
int c = a & b; // 0000 1000
int d = a | b; // 0001 1101
int e = a ^ 5; // 0000 1101
int f = ~a; // 1111 0011
Bitwise operators perform operations directly on binary representations.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 26/62
Other Operators
Some other operators in C:
sizeof() - size of type/variable
& - Address of variable
? : - Ternary conditional
, - Comma separates expressions
int a;
float b;
printf("Size of int is %d", sizeof(a));
printf("Address of b is %x", &b);
int x = 5;
int res = (x > 2) ? 10 : 0; // Ternary operator
int y = 1, z = 15; // Comma separates
C provides special operators for certain usage contexts.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 27/62
Complex Challenge: Data Types and Operators
#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %sn", x > y ? "True" : "False");
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 28/62
Complex Challenge: Data Types and Operators
#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %sn", x > y ? "True" : "False");
return 0;
}
Question
What will be the output of this code and why?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 28/62
Complex Challenge: Data Types and Operators
#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %sn", x > y ? "True" : "False");
return 0;
}
Question
What will be the output of this code and why?
Answer
The output is ”False”. This is because when comparing an unsigned int
with an int, the int is implicitly converted to unsigned int. So, -8 is
converted to a large unsigned int value 8, which is greater than 5.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 28/62
Type Promotion and Arithmetic Operations
#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %dn", b);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 29/62
Type Promotion and Arithmetic Operations
#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %dn", b);
return 0;
}
Question
What will be the output, and why is this output observed?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 29/62
Type Promotion and Arithmetic Operations
#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %dn", b);
return 0;
}
Question
What will be the output, and why is this output observed?
Answer
The output is -32768. In the expression ’a + 1’, ’a’ is first promoted to an
int and then added to 1. The result overflows the range of short, and when
it is stored back in ’b’, it wraps around to the minimum value for a short.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 29/62
Order of Operations and Associativity
Operator Order (Highest to Lowest) Associativity
() [] -> . 1st Level Left to Right
! ++ -- + (type) - (type) * 2nd Level Right to Left
* / % 3rd Level Left to Right
+ - 4th Level Left to Right
<< >> 5th Level Left to Right
< <= > >= 6th Level Left to Right
== != 7th Level Left to Right
& 8th Level Left to Right
^ 9th Level Left to Right
| 10th Level Left to Right
&& 11th Level Left to Right
|| 12th Level Left to Right
?: 13th Level Right to Left
= += -= *= /= %= &= ^= |= <<= >>= 14th Level Right to Left
, 15th Level Left to Right
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 30/62
Order of Operations - Example Codes
Example 1:
int x = 5;
int y = x + 3 * 2; // y = 11, not 16
Example 2:
int a = 5;
int b = a++ + 2; // b = 7, a becomes 6
Example 3:
int m = 3;
int n = 2 * ++m; // n = 8, m becomes 4
Example 4:
bool p = true;
bool q = !p; // q = false
Example 5:
int i = 4; int j = 5;
int k = i * (j - 2) + 6 / 2 - 3; // k = 4 * (5 - 2) + 3 - 3 = 12
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 31/62
Debugging Challenge: Order of operation
#include <stdio.h>
int main() {
int a = 10, b = 5, c = 5;
int result = a / b * c;
printf("Result: %dn", result);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 32/62
Debugging Challenge: Order of operation
#include <stdio.h>
int main() {
int a = 10, b = 5, c = 5;
int result = a / b * c;
printf("Result: %dn", result);
return 0;
}
Answer
The output of the code is ”Result: 10”.
The expression is evaluated as (a / b) * c = (10 / 5) * 5 = 2 * 5 = 10.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 32/62
Debugging Question: Operators
#include <stdio.h>
int main() {
int i = 5;
printf("%d %d %dn", i++, i, ++i);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 33/62
Debugging Question: Operators
#include <stdio.h>
int main() {
int i = 5;
printf("%d %d %dn", i++, i, ++i);
return 0;
}
Answer
The output of this code is undefined due to the sequence point rule in C.
The order of evaluation of expressions involving post-increment and
pre-increment operators in the same statement is not defined, which leads
to undefined behavior.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 33/62
Find the Output: Operators Challenge
#include <stdio.h>
int main() {
int x = 2, y = 3, z = 4;
int result = x + y * z / x - y;
printf("Result: %dn", result);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 34/62
Find the Output: Operators Challenge
#include <stdio.h>
int main() {
int x = 2, y = 3, z = 4;
int result = x + y * z / x - y;
printf("Result: %dn", result);
return 0;
}
Answer
The output of the code is 5. The expression is evaluated as follows: -
Multiplication and division have higher precedence than addition and
subtraction and are evaluated from left to right. - So, y * z / x is
evaluated first to get 6, then x + 6 - y results in 5.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 34/62
Format Specifiers
Syntax
Used with printf() and scanf() for formatted I/O:
printf("Format string", var1, var2);
scanf("Format string", &var1, &var2);
Some commonly used specifiers:
%c - character
%d - integer
%f - float
%s - string
Format specifiers allow displaying outputs in the desired format.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 35/62
Format Specifiers
Some additional specifiers:
%ld - long integer
%lf - double float
%Lf - long double
%x - hex integer
%o - octal integer
#include <stdio.h>
int main() {
int num = 10;
long int lnum = 15000000;
float flt = 1.234567;
double dbl = 1.23456789;
printf("Integer: %dn", num);
printf("Long Integer: %ldn", lnum);
printf("Float: %fn", flt);
printf("Double: %lfn", dbl);
printf("Hexadecimal: %xn", num);
printf("Octal: %on", num);
return 0;
}
Format specifiers provide flexibility to print different data types.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 36/62
Format Specifiers
Format specifiers provide fine grained control over textual output.
Customizing and formatting output:
width and precision
padding and signs
#include <stdio.h>
int main() {
printf("Padding: %-6dn", 12);
printf("Precision: %.4fn", 123.4567);
printf("Width: %6dn", 1234);
printf("Sign: %+d | %+dn", 10, -10);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 37/62
Understanding Format Specifiers Challenge
#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %en", num, num);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 38/62
Understanding Format Specifiers Challenge
#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %en", num, num);
return 0;
}
Question
What will be the output of this code, considering the format specifiers
used?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 38/62
Understanding Format Specifiers Challenge
#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %en", num, num);
return 0;
}
Question
What will be the output of this code, considering the format specifiers
used?
Answer
The output will be ”Output: 12345.68 and 1.234568e+04”. The first
specifier ’formats the float in scientific notation.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 38/62
Escape Sequences
Escape sequences allow inserting special characters.Used with printf() and
character arrays:
Common Escape Codes
n - new line - Used for new line
t - tab - Used for tab spacing
” - single quote - Prints double quotes
’ - double quote - Prints single quote
#include <stdio.h>
int main() {
printf("Hello n World n");
printf("Name:tJohnn");
printf(""Quotation" marksn");
char line[] = "Backslashescaped";
printf("%sn", line);
return 0;
}
Figure: Output
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 39/62
Console I/O
scanf() and printf() are used for formatted console I/O.
Input
scanf(”format”, var address);
Output
printf(”format”, var);
#include <stdio.h>
int main() {
int age;
float salary;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter salary: ");
scanf("%f", &salary);
printf("Age: %d n", age);
printf("Salary: %0.2f n", salary);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 40/62
Enhanced I/O Operations
Formatted I/O:
printf("Value: %d", a);
and scanf("%d", &a);
Unformatted I/O:
getchar(); and putchar();
Common Pitfalls:
Buffer overflow, improper
format specifiers.
Figure: Output
#include <stdio.h>
int main() {
int number;
char str[100];
// Formatted Input
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %dn", number);
// Formatted Output
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %sn", str);
// Unformatted I/O
char ch;
ch = getchar(); // Reads a character
putchar(ch); // Writes a character
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 41/62
Unformatted I/O Operations in C
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads a character from the standard input
printf("Character entered: ");
putchar(ch); // Writes a character to the standard output
return 0;
}
getchar(): Reads a single character from standard input. Waits for
input if not available.
getch(): Similar to getchar() but does not echo the character to the
console. Often used in DOS-based systems.
putchar(): Writes a single character to standard output.
putch(): Similar to putchar() but used in DOS-based systems.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 42/62
Best Practices and Coding Standards in C
Readability: Use clear and meaningful variable names, consistent
indentation.
Modularity: Break down large problems into smaller, manageable
functions.
Comments: Document the code with necessary comments for better
understanding.
Error Handling: Implement comprehensive error handling for
robustness.
Memory Management: Avoid memory leaks by proper allocation
and deallocation.
Code Reusability: Write reusable code to enhance maintainability.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 43/62
Best Practices and Coding Standards in C
#include <stdio.h>
int main() {
// Good practice: clear variable names
int totalItems = 10;
int processedItems = 0;
// Good practice: modular code
while (processedItems < totalItems) {
// process each item
processedItems++;
}
// Good practice: error checks and memory management
// Implement necessary checks and memory management
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 44/62
Best Practices Question
Question
Why is it considered a best practice to initialize all variables in C before
using them? Provide an example.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 45/62
Best Practices Question
Question
Why is it considered a best practice to initialize all variables in C before
using them? Provide an example.
Answer
Initializing variables prevents undefined behavior due to usage of
uninitialized memory.
For example, without initialization, int x; printf(”% d”, x); might print any
random value. Initializing with int x = 0; ensures ’x’ has a defined,
predictable value.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 45/62
Common Errors and Troubleshooting in C
Syntax errors: Issues with the code’s structure, often caught by the compiler.
Runtime errors: Errors that occur during the execution of the program, such as division by
zero.
Logic errors: Flaws in the program’s logic leading to incorrect output despite successful
compilation.
Debugging tips: Use of debugger tools, reading compiler warnings, and code reviews.
#include <stdio.h>
int main() {
int a = 10, b = 0;
int result;
// Runtime error example: division by zero
if (b != 0) {
result = a / b;
} else {
printf("Error: Division by zeron");
}
// Logic error example: incorrect condition
if (a = 10) { // Should be ’==’, not ’=’
printf("a is 10n");
}
return 0;
} Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 46/62
C Programs: Re-usability
Small reusable programs demonstrate language features:
Math and prime
checks
String operations
Sorting
algorithms
File handling
#include <stdio.h>
int factorial(int num) {
int f = 1;
for(int i=1; i<=num; i++) {
f *= i;
}
return f;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int result = factorial(num);
printf("The factorial of %d is %d", num, result);
return 0;
}
Modular programs effectively showcase constructs and libraries.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 47/62
C Programs : Modularization
Header files modularize functionality:
int add(int , int);
int factorial(int);
#include "math.h"
int main () {
int s = add(5, 10);
int f = factorial (5);
}
Header files and libraries enable code reuse across source files.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 48/62
Function Call Challenge
#include <stdio.h>
void update(int x) {
x = x + 10;
}
int main() {
int a = 5;
update(a);
printf("a: %dn", a);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 49/62
Function Call Challenge
#include <stdio.h>
void update(int x) {
x = x + 10;
}
int main() {
int a = 5;
update(a);
printf("a: %dn", a);
return 0;
}
Question
What is the value of ’a’ after the function call and why?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 49/62
Function Call Challenge
#include <stdio.h>
void update(int x) {
x = x + 10;
}
int main() {
int a = 5;
update(a);
printf("a: %dn", a);
return 0;
}
Question
What is the value of ’a’ after the function call and why?
Answer
The value of ’a’ remains 5 after the function call. In C, function parameters are
passed by value. Therefore, the function ’update’ modifies a copy of ’a’, not ’a’
itself.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 49/62
Function Call Challenge: Update with Pointer
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int a = 5;
update(&a);
printf("a: %dn", a);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 50/62
Function Call Challenge: Update with Pointer
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int a = 5;
update(&a);
printf("a: %dn", a);
return 0;
}
Question
What is the value of ’a’ after the function call now?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 50/62
Function Call Challenge: Update with Pointer
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int a = 5;
update(&a);
printf("a: %dn", a);
return 0;
}
Question
What is the value of ’a’ after the function call now?
Answer
Now the value of ’a’ is 15 after the function call. The function ’update’
uses a pointer to directly modify the value of ’a’.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 50/62
File I/O
File handling allows data persistence across executions.
Opening and closing files
Reading and writing data
Text vs Binary modes
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("file.txt","w");
fprintf(fptr,"Hello World!");
fclose(fptr);
fptr = fopen("file.txt","r");
char buffer[100];
fscanf(fptr,"%s", buffer);
printf("Data: %s", buffer);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 51/62
Basic File Operations in C
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fprintf(fp, "Hello, world!n");
fclose(fp);
return 0;
}
Opening a File: Use ‘fopen()‘ to open a file. Modes include ”r”, ”w”, ”a”.
Reading from a File: Use ‘fscanf()‘ or ‘fgets()‘ for reading.
Writing to a File: Use ‘fprintf()‘ or ‘fputs()‘ for writing.
Closing a File: Always close a file using ‘fclose()‘.
Error Handling: Check the return value of file operations for errors.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 52/62
Debugging Challenge: File I/O
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 53/62
Debugging Challenge: File I/O
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}
Question
What is the content of ”example.txt” after executing this program?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 53/62
Debugging Challenge: File I/O
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}
Question
What is the content of ”example.txt” after executing this program?
Answer
The content of ”example.txt” will be ”5 10 15”. The program writes these
three integers to the file separated by spaces using fprintf.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 53/62
Preprocessors
Preprocessors handle meta programming logic.
Directives evaluated before compilation
#include, #define, #ifdef etc.
Macro expansions
File inclusion
Conditional compilation
#include <stdio.h>
#define PRINT printf
#define SQUARE(x) x*x
int main() {
PRINT("In main functionn");
int num=5;
PRINT("Square of %d is %d", num, SQUARE(num));
eturn 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 54/62
Preprocessors : File Inclusion
Preprocessors insert contents of file during compilation.
include < file > - Search built-in
directories
include ”file” - Search current
directory
include < file.h > - Header files
convention
#include <stdio.h>
int main() {
printf("Standard library");
#include "userdefs.h"
printcustom();
return 0;
}
This demonstrates:
Inclusion of stdio.h from built-in folders
Inclusion of userdefs.h from current folder
Calling custom function after inclusion
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 55/62
Preprocessors: Macro Arguments
Macros can make code more readable and maintainable.
Define macros accepting parameters:
# define MACRO (arg1, arg2)
(arg1 + arg2)
#include <stdio.h>
#define MIN(x,y) ((x) < (y) ? (x) : (y))
int main() {
int a = 10, b = 5;
int small = MIN(a, b); //Macro invocation
printf("Minimum of %d & %d is: %d", a, b, small);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 56/62
Understanding Macros
#include <stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a = 4, b = 2;
int result = SQUARE(a + b);
printf("Result: %dn", result);
return 0;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 57/62
Understanding Macros
#include <stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a = 4, b = 2;
int result = SQUARE(a + b);
printf("Result: %dn", result);
return 0;
}
Question
What is the output of this program and why?
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 57/62
Understanding Macros
#include <stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a = 4, b = 2;
int result = SQUARE(a + b);
printf("Result: %dn", result);
return 0;
}
Question
What is the output of this program and why?
Answer
The output is 14, not 36. The macro expands to (a + b * a + b), which
is equivalent to (4 + 2 * 4 + 2) due to macro substitution leading to
unexpected results without proper parentheses.
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 57/62
Preprocessors: #if − #else − #endif
Conditionally include code sections during compilation.
{#if CONDITION
//code A
else
//code B
#endif }
This shows:
DEBUG macro definition as flag
Code inside if block prints when
defined
Alternate code in else prints
when not defined
#define DEBUG
int main() {
#if DEBUG
printf("In debug moden");
#else
printf("Debug disabledn");
#endif
// Rest of code
}
#endif
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 58/62
Predefined Macros
Commonly available predefined macros are:
FILE - Current filename
LINE - Current line number
DATE - Compilation date
TIME - Compilation time
#include <stdio.h>
int main() {
printf("Compiled at line %d of file %s n", LINE, FILE );
printf("On date: %s time: %sn", DATE, TIME);
return 0;
}
FILE and LINE for displaying context
DATE and TIME for compilation timestamps
Other interesting predefined macros are:
STDC - Conformance level indicator
FUNCTION- Prints function name
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 59/62
Sequential Statements
Modular program structure
Functions, headers, libraries
Sequence of statements execute
top to bottom
Code blocks, conditionals
Input, process, output, style
Program structure best practices
Statements execute sequentially
Overall program flow and stages
Systematic sequence of steps
solve problem.
#include <stdio.h>
// Function declaration
void readInput();
int main() {
// Initialize
int num;
// Read input
readInput();
// Process
num = num * 2;
// Display output
printf("%d", num);
return 0;
}
// Define function
void readInput() {
scanf("%d", &num);
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 60/62
Modular Programs
Functions follow calling conventions for parameter passing.
Functions encapsulate logic:
Declaration in header file
Definition with logic
Call from multiple places
This demonstrates:
Function declaration in header
Calling declared function from
main()
Definition separate from usage
// In header.h
int add(int, int);
// In main.c
#include "header.h"
int main() {
int sum = add(5, 10);
printf("Sum=%d",sum);
}
// In add.c
int add(int a, int b) {
return a+b;
}
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 61/62
Version Control Basics
Version control systems track changes to files over time.
Git is a distributed version control system widely used in software
development.
Key operations: ‘git init‘, ‘git add‘, ‘git commit‘, ‘git push‘.
Benefits: Collaboration, backup, history, and branch management.
// Command l i n e s n i p p e t s that show b a s i c Git commands
// Example : I n i t i a l i z i n g a new Git r e p o s i t o r y
g i t i n i t
// Adding a f i l e to the s t a g i n g area
g i t add f i l e n a m e . c
// Committing changes with a message
g i t commit −m ” I n i t i a l commit”
// Pushing changes to a remote r e p o s i t o r y
g i t push o r i g i n main
Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 62/62
Ad

More Related Content

Similar to Embedded C Programming Module1 Presentation.pdf (20)

Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
Kumar Gaurav
 
C introduction by piyushkumar
C introduction by piyushkumarC introduction by piyushkumar
C introduction by piyushkumar
piyush Kumar Sharma
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
Data Structure Using C.pptx
Data Structure Using C.pptxData Structure Using C.pptx
Data Structure Using C.pptx
ssuser5610081
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
Anil Bishnoi
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
RSathyaPriyaCSEKIOT
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptx
PragatheshP
 
Unit3 overview of_c_programming
Unit3 overview of_c_programmingUnit3 overview of_c_programming
Unit3 overview of_c_programming
Capuchino HuiNing
 
Report on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for studyReport on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for study
HetalVasava9
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
AnkurSingh656748
 
cuptopointer-180804092048-190306091149 (2).pdf
cuptopointer-180804092048-190306091149 (2).pdfcuptopointer-180804092048-190306091149 (2).pdf
cuptopointer-180804092048-190306091149 (2).pdf
YashwanthCse
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
Mohamed Fawzy
 
Unit-IV.pptx
Unit-IV.pptxUnit-IV.pptx
Unit-IV.pptx
Mehul Desai
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
karmuhtam
 
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
VLSICS Design
 
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
VLSICS Design
 
2.Overview of C language.pptx
2.Overview of C language.pptx2.Overview of C language.pptx
2.Overview of C language.pptx
Vishwas459764
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
Kumar Gaurav
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
Data Structure Using C.pptx
Data Structure Using C.pptxData Structure Using C.pptx
Data Structure Using C.pptx
ssuser5610081
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
Anil Bishnoi
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
RSathyaPriyaCSEKIOT
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptx
PragatheshP
 
Unit3 overview of_c_programming
Unit3 overview of_c_programmingUnit3 overview of_c_programming
Unit3 overview of_c_programming
Capuchino HuiNing
 
Report on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for studyReport on Flutter.docx prasentation for study
Report on Flutter.docx prasentation for study
HetalVasava9
 
cuptopointer-180804092048-190306091149 (2).pdf
cuptopointer-180804092048-190306091149 (2).pdfcuptopointer-180804092048-190306091149 (2).pdf
cuptopointer-180804092048-190306091149 (2).pdf
YashwanthCse
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
karmuhtam
 
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
VLSICS Design
 
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...
VLSICS Design
 
2.Overview of C language.pptx
2.Overview of C language.pptx2.Overview of C language.pptx
2.Overview of C language.pptx
Vishwas459764
 

Recently uploaded (20)

seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Uses of drones in civil construction.pdf
Uses of drones in civil construction.pdfUses of drones in civil construction.pdf
Uses of drones in civil construction.pdf
surajsen1729
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation RateModeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Journal of Soft Computing in Civil Engineering
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Uses of drones in civil construction.pdf
Uses of drones in civil construction.pdfUses of drones in civil construction.pdf
Uses of drones in civil construction.pdf
surajsen1729
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Ad

Embedded C Programming Module1 Presentation.pdf

  • 1. Embedded C Programming Module-1: Introduction to C Dr. Markkandan S School of Electronics Engineering (SENSE) Vellore Institute of Technology Chennai Dr. Markkandan S (School of Electronics Engineering (SENSE)Vellore Institute of Technology Chennai) Embedded C Programming Module-1: Introduction to C 1 / 62
  • 2. C Programming - Overview General purpose programming language Developed by Dennis Ritchie Strengths - flexibility, efficiency, widespread use Used for embedded systems, OS, applications Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 2/62
  • 3. Features of C Language Structured programming approach Direct low-level hardware access Rich set of built-in operators and functions Example Program: #include <stdio.h> int main() { printf("Hello World n"); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 3/62
  • 4. Introduction to Embedded C Program for embedded devices/control, robotics etc. Programming for microcontrollers/MCU Tightly constrained resource usage Low level control of hardware Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 4/62
  • 5. Difference: C vs Embedded C C Language: High level language Large standard library Platform independent Dynamic memory allocation Embedded C: Tightly constrained No standard library Platform specific Static allocation Key constraints while programming for embedded systems. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 5/62
  • 6. Basic C Program Structure Structure: 1 Include necessary header files 2 Declare global variables 3 Define functions 4 Implement the main function #include <stdio.h> // Declare global variables int globalVar = 10; // Function declaration void myFunction(); int main() { // Implementation of main function printf("Hello, C Programming!"); return 0; } // Function definition void myFunction() { // Implementation of myFunction } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 6/62
  • 7. Basic C Program Structure Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 7/62
  • 8. Embedded C Program Structure Interaction with hardware Memory considerations Real-time constraints #include <avr/io.h> // Declare global variables volatile uint8_t sensorValue; // Function declaration void initializeSensor(); int main() { // Implementation of main function initializeSensor(); while(1) { // Real-time processing sensorValue = readSensor(); } } void initializeSensor() { // Hardware initialization } uint8_t readSensor() { // Read data from sensor } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 8/62
  • 9. Find the Output #include <stdio.h> int main() { int x = 5, y = 3; printf("%d", x + y); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 9/62
  • 10. Find the Output #include <stdio.h> int main() { int x = 5, y = 3; printf("%d", x + y); return 0; } Answer The output of the code is 8. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 9/62
  • 11. Introduction to Compilation Process Pre-processing Compilation Assembly Linking #include <stdio.h> #define MAX 10 int main() { int i = MAX; printf("Maximum value is: %d", i); return 0; } The compilation process converts source code to executable machine code. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 10/62
  • 12. Compilation Process Preprocessor handles directives (like ‘include‘), compiler translates C to Assembly, assembler to machine code, linker resolves references. Tools: C Compiler (e.g., gcc), Assembler (e.g., as), Linker (e.g., ld). Terminal or GCC Compilation gcc -E main.c -o main.i # Preprocessing gcc -S main.i -o main.s # Compilation to assembly as main.s -o main.o # Assembly to object code ld main.o -o main # Linking object code to executable Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 11/62
  • 13. Compilation Process Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 12/62
  • 14. Comments Single Line Comment Used to provide descriptions and explanations in code. Format: // Comments Example #include <stdio.h> int main(){ // Print statement printf("Hello World!"); return 0; } Comments help document the code functionality and are ignored by compiler. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 13/62
  • 15. Multi-line Comments Syntax Used to comment multiple lines or blocks of code. Format: /* This is a multi-line comment */ Example /* Comments message across multiple lines */ printf("Hello World!"); printf("From C program"); Multi-line comments are convenient for commenting code sections. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 14/62
  • 16. Identifiers Naming Rules Start with letter or underscore Can have letters, digits, underscores Case sensitive index ̸= INDEX No whitespaces allowed Example #include <stdio.h> int main() { int final_count; // valid int 123Invalid; // invalid return 0; } Identifiers refer to user defined names for variables, functions etc. in C. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 15/62
  • 17. Variables Declaring Variables Specify data type and name: datatype name; int count; float price; char code; Initializing Variables Assign initial value: datatype name = value; int sum = 0; float pie = 3.14; char grade = ’A’; Variables represent memory locations to store program data. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 16/62
  • 18. In-depth Variable Types and Storage Classes Global Variables: Accessible throughout the program. Example: int globalVar; Local Variables: Accessible only within the function. Example: void func() { int localVar; } Static Variables: Retains value between function calls. Example: static int staticVar; Register Variables: Stored in CPU register for faster access. Example: register int loopCounter; // Global Variable int globalVar; void function() { // Local Variable int localVar; // Static Variable static int staticVar = 0; staticVar++; // Register Variable for(register int i = 0; i < 10; i++) { // Fast access within loop } } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 17/62
  • 19. Header Files # include Includes external library contents in program: #include <stdio.h> #include "myutils.h" Commonly used library headers in C: stdio.h - standard I/O functions math.h - mathematical operations string.h - string handling Header files contain reusable code functionalities. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 18/62
  • 20. Data Types Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 19/62
  • 21. Data Types Primitive types int, float, double char Derived types Array, pointer Structure, union #include <stdio.h> int main() { // Primitive types int num = 10; float pi = 3.14; double height = 79.234; char x = ’A’; // Derived types int arr[5]; struct student { int id; char name[20]; } s1; int* ptr = # union data { int i; float f; } val; return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 20/62
  • 22. Data Types Character Types % Format Size Range unsigned char %c 1 byte 0 to 255 char %c 1 byte -128 to 127 signed char %c 1 byte -128 to 127 Integer Types unsigned short int %hu 2 bytes 0 to 65,535 short int %hd 2 bytes -32,768 to 32,767 signed short int %hd 2 bytes -32,768 to 32,767 unsigned int %u 2/4 bytes 0 to 65,535 or 0 to 4,294,967,295 int %d 2/4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 signed int %d 2/4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 long int %ld 4/8 bytes -2,147,483,648 to 2,147,483,647 unsigned long int %lu 4/8 bytes 0 to 4,294,967,295 or 0 to 18,446,744,073,709,551,615 signed long int %ld 4/8 bytes -2,147,483,648 to 2,147,483,647 long long int %lld 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 unsigned long long int %llu 8 bytes 0 to 18,446,744,073,709,551,615 Float Types float %f 4 bytes ± 1.2E-38 to ± 3.4E+38 double %lf 8 bytes ± 2.3E-308 to ± 1.7E+308 long double %Lf 12 bytes ± 3.4E–4932 to ± 1.1E+4932 Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 21/62
  • 23. Exploring Data Types and Sizes #include <stdio.h> int main() { printf("Size of int: %lu bytesn", sizeof(int)); printf("Size of char: %lu byten", sizeof(char)); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 22/62
  • 24. Exploring Data Types and Sizes #include <stdio.h> int main() { printf("Size of int: %lu bytesn", sizeof(int)); printf("Size of char: %lu byten", sizeof(char)); return 0; } Question What will be the output of this program? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 22/62
  • 25. Exploring Data Types and Sizes #include <stdio.h> int main() { printf("Size of int: %lu bytesn", sizeof(int)); printf("Size of char: %lu byten", sizeof(char)); return 0; } Question What will be the output of this program? Answer The output will display the size of ’int’ and ’char’ in bytes. Typically, it will be ”Size of int: 4 bytes” and ”Size of char: 1 byte”, but this can vary depending on the system architecture. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 22/62
  • 26. Arithmetic Operators + − ∗ / % Arithmetic Operators x = y + 2; // Addition z = p − 5; // S u b t r a c t i o n area = l e n g t h ∗ breadth ; // M u l t i p l i c a t i o n q = a / b ; // D i v i s i o n r = 15 % 4; // Modulus Precedence Follows order - Exponential > Multiplicative > Additive a = b + ( c ∗ 2 ) ; // precedence z = 3 ∗ x / 5; i n t num = 15; f l o a t v a l = num ; // t y p e c a s t i n g num + v a l ; Typecasting allows same operands to be treated as different types. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 23/62
  • 27. Relational Operators > < >= <= ! = Chaining Relational Operators i f ( a > 50) // Greater than p r i n t f ( ”a i s big ” ) ; i f ( b < 20) // Less than p r i n t f ( ”b i s s m a l l ” ) ; i f ( s t r == ” t e s t ” ) // Equal to p r i n t f ( ” S t r i n g s matched” ) ; i f ( i != 10) // Not equal to p r i n t ( ” i i s not 10” ) ; i f ( age >= 18) // Greater than equal to p r i n t f ( ” E l i g i b l e ” ) ; i f ( marks <= 35) // Less than equal to p r i n t f ( ” F a i l e d ” ) ; // M u l t i p l e c o n d i t i o n a l checks can be chained : i f ( x > 5 && x < 10) { . . . } Relational operators can be combined using logical operators. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 24/62
  • 28. Logical Operators Used to combine multiple logical conditions: && - Logical AND || - Logical OR ! - Logical NOT int a = 5; int b = 10; if(a < 8 && b >= 10) { printf("AND condition met"); } if(a < 8 || b < 5) { printf("OR condition met"); } if(!(b == 15)) { printf("NOT condition met"); } Logical operators are used to implement conditional logic. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 25/62
  • 29. Bitwise Operators Used to manipulate individual bits: & - Bitwise AND : Compares bits | - Bitwise OR : Makes bits 1 if set in either b- Bitwise XOR : Makes bits 1 if different ∼ - Bitwise NOT : Inverts all bits int a = 12; // 0000 1100 int b = 25; // 0001 1001 int c = a & b; // 0000 1000 int d = a | b; // 0001 1101 int e = a ^ 5; // 0000 1101 int f = ~a; // 1111 0011 Bitwise operators perform operations directly on binary representations. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 26/62
  • 30. Other Operators Some other operators in C: sizeof() - size of type/variable & - Address of variable ? : - Ternary conditional , - Comma separates expressions int a; float b; printf("Size of int is %d", sizeof(a)); printf("Address of b is %x", &b); int x = 5; int res = (x > 2) ? 10 : 0; // Ternary operator int y = 1, z = 15; // Comma separates C provides special operators for certain usage contexts. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 27/62
  • 31. Complex Challenge: Data Types and Operators #include <stdio.h> int main() { unsigned int x = 5; int y = -8; printf("Result: %sn", x > y ? "True" : "False"); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 28/62
  • 32. Complex Challenge: Data Types and Operators #include <stdio.h> int main() { unsigned int x = 5; int y = -8; printf("Result: %sn", x > y ? "True" : "False"); return 0; } Question What will be the output of this code and why? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 28/62
  • 33. Complex Challenge: Data Types and Operators #include <stdio.h> int main() { unsigned int x = 5; int y = -8; printf("Result: %sn", x > y ? "True" : "False"); return 0; } Question What will be the output of this code and why? Answer The output is ”False”. This is because when comparing an unsigned int with an int, the int is implicitly converted to unsigned int. So, -8 is converted to a large unsigned int value 8, which is greater than 5. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 28/62
  • 34. Type Promotion and Arithmetic Operations #include <stdio.h> int main() { short a = 32767; // Max value for short short b = a + 1; printf("Result: %dn", b); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 29/62
  • 35. Type Promotion and Arithmetic Operations #include <stdio.h> int main() { short a = 32767; // Max value for short short b = a + 1; printf("Result: %dn", b); return 0; } Question What will be the output, and why is this output observed? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 29/62
  • 36. Type Promotion and Arithmetic Operations #include <stdio.h> int main() { short a = 32767; // Max value for short short b = a + 1; printf("Result: %dn", b); return 0; } Question What will be the output, and why is this output observed? Answer The output is -32768. In the expression ’a + 1’, ’a’ is first promoted to an int and then added to 1. The result overflows the range of short, and when it is stored back in ’b’, it wraps around to the minimum value for a short. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 29/62
  • 37. Order of Operations and Associativity Operator Order (Highest to Lowest) Associativity () [] -> . 1st Level Left to Right ! ++ -- + (type) - (type) * 2nd Level Right to Left * / % 3rd Level Left to Right + - 4th Level Left to Right << >> 5th Level Left to Right < <= > >= 6th Level Left to Right == != 7th Level Left to Right & 8th Level Left to Right ^ 9th Level Left to Right | 10th Level Left to Right && 11th Level Left to Right || 12th Level Left to Right ?: 13th Level Right to Left = += -= *= /= %= &= ^= |= <<= >>= 14th Level Right to Left , 15th Level Left to Right Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 30/62
  • 38. Order of Operations - Example Codes Example 1: int x = 5; int y = x + 3 * 2; // y = 11, not 16 Example 2: int a = 5; int b = a++ + 2; // b = 7, a becomes 6 Example 3: int m = 3; int n = 2 * ++m; // n = 8, m becomes 4 Example 4: bool p = true; bool q = !p; // q = false Example 5: int i = 4; int j = 5; int k = i * (j - 2) + 6 / 2 - 3; // k = 4 * (5 - 2) + 3 - 3 = 12 Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 31/62
  • 39. Debugging Challenge: Order of operation #include <stdio.h> int main() { int a = 10, b = 5, c = 5; int result = a / b * c; printf("Result: %dn", result); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 32/62
  • 40. Debugging Challenge: Order of operation #include <stdio.h> int main() { int a = 10, b = 5, c = 5; int result = a / b * c; printf("Result: %dn", result); return 0; } Answer The output of the code is ”Result: 10”. The expression is evaluated as (a / b) * c = (10 / 5) * 5 = 2 * 5 = 10. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 32/62
  • 41. Debugging Question: Operators #include <stdio.h> int main() { int i = 5; printf("%d %d %dn", i++, i, ++i); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 33/62
  • 42. Debugging Question: Operators #include <stdio.h> int main() { int i = 5; printf("%d %d %dn", i++, i, ++i); return 0; } Answer The output of this code is undefined due to the sequence point rule in C. The order of evaluation of expressions involving post-increment and pre-increment operators in the same statement is not defined, which leads to undefined behavior. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 33/62
  • 43. Find the Output: Operators Challenge #include <stdio.h> int main() { int x = 2, y = 3, z = 4; int result = x + y * z / x - y; printf("Result: %dn", result); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 34/62
  • 44. Find the Output: Operators Challenge #include <stdio.h> int main() { int x = 2, y = 3, z = 4; int result = x + y * z / x - y; printf("Result: %dn", result); return 0; } Answer The output of the code is 5. The expression is evaluated as follows: - Multiplication and division have higher precedence than addition and subtraction and are evaluated from left to right. - So, y * z / x is evaluated first to get 6, then x + 6 - y results in 5. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 34/62
  • 45. Format Specifiers Syntax Used with printf() and scanf() for formatted I/O: printf("Format string", var1, var2); scanf("Format string", &var1, &var2); Some commonly used specifiers: %c - character %d - integer %f - float %s - string Format specifiers allow displaying outputs in the desired format. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 35/62
  • 46. Format Specifiers Some additional specifiers: %ld - long integer %lf - double float %Lf - long double %x - hex integer %o - octal integer #include <stdio.h> int main() { int num = 10; long int lnum = 15000000; float flt = 1.234567; double dbl = 1.23456789; printf("Integer: %dn", num); printf("Long Integer: %ldn", lnum); printf("Float: %fn", flt); printf("Double: %lfn", dbl); printf("Hexadecimal: %xn", num); printf("Octal: %on", num); return 0; } Format specifiers provide flexibility to print different data types. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 36/62
  • 47. Format Specifiers Format specifiers provide fine grained control over textual output. Customizing and formatting output: width and precision padding and signs #include <stdio.h> int main() { printf("Padding: %-6dn", 12); printf("Precision: %.4fn", 123.4567); printf("Width: %6dn", 1234); printf("Sign: %+d | %+dn", 10, -10); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 37/62
  • 48. Understanding Format Specifiers Challenge #include <stdio.h> int main() { float num = 12345.6789; printf("Output: %.2f and %en", num, num); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 38/62
  • 49. Understanding Format Specifiers Challenge #include <stdio.h> int main() { float num = 12345.6789; printf("Output: %.2f and %en", num, num); return 0; } Question What will be the output of this code, considering the format specifiers used? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 38/62
  • 50. Understanding Format Specifiers Challenge #include <stdio.h> int main() { float num = 12345.6789; printf("Output: %.2f and %en", num, num); return 0; } Question What will be the output of this code, considering the format specifiers used? Answer The output will be ”Output: 12345.68 and 1.234568e+04”. The first specifier ’formats the float in scientific notation. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 38/62
  • 51. Escape Sequences Escape sequences allow inserting special characters.Used with printf() and character arrays: Common Escape Codes n - new line - Used for new line t - tab - Used for tab spacing ” - single quote - Prints double quotes ’ - double quote - Prints single quote #include <stdio.h> int main() { printf("Hello n World n"); printf("Name:tJohnn"); printf(""Quotation" marksn"); char line[] = "Backslashescaped"; printf("%sn", line); return 0; } Figure: Output Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 39/62
  • 52. Console I/O scanf() and printf() are used for formatted console I/O. Input scanf(”format”, var address); Output printf(”format”, var); #include <stdio.h> int main() { int age; float salary; printf("Enter age: "); scanf("%d", &age); printf("Enter salary: "); scanf("%f", &salary); printf("Age: %d n", age); printf("Salary: %0.2f n", salary); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 40/62
  • 53. Enhanced I/O Operations Formatted I/O: printf("Value: %d", a); and scanf("%d", &a); Unformatted I/O: getchar(); and putchar(); Common Pitfalls: Buffer overflow, improper format specifiers. Figure: Output #include <stdio.h> int main() { int number; char str[100]; // Formatted Input printf("Enter a number: "); scanf("%d", &number); printf("You entered: %dn", number); // Formatted Output printf("Enter a string: "); scanf("%s", str); printf("You entered: %sn", str); // Unformatted I/O char ch; ch = getchar(); // Reads a character putchar(ch); // Writes a character return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 41/62
  • 54. Unformatted I/O Operations in C #include <stdio.h> int main() { char ch; printf("Enter a character: "); ch = getchar(); // Reads a character from the standard input printf("Character entered: "); putchar(ch); // Writes a character to the standard output return 0; } getchar(): Reads a single character from standard input. Waits for input if not available. getch(): Similar to getchar() but does not echo the character to the console. Often used in DOS-based systems. putchar(): Writes a single character to standard output. putch(): Similar to putchar() but used in DOS-based systems. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 42/62
  • 55. Best Practices and Coding Standards in C Readability: Use clear and meaningful variable names, consistent indentation. Modularity: Break down large problems into smaller, manageable functions. Comments: Document the code with necessary comments for better understanding. Error Handling: Implement comprehensive error handling for robustness. Memory Management: Avoid memory leaks by proper allocation and deallocation. Code Reusability: Write reusable code to enhance maintainability. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 43/62
  • 56. Best Practices and Coding Standards in C #include <stdio.h> int main() { // Good practice: clear variable names int totalItems = 10; int processedItems = 0; // Good practice: modular code while (processedItems < totalItems) { // process each item processedItems++; } // Good practice: error checks and memory management // Implement necessary checks and memory management return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 44/62
  • 57. Best Practices Question Question Why is it considered a best practice to initialize all variables in C before using them? Provide an example. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 45/62
  • 58. Best Practices Question Question Why is it considered a best practice to initialize all variables in C before using them? Provide an example. Answer Initializing variables prevents undefined behavior due to usage of uninitialized memory. For example, without initialization, int x; printf(”% d”, x); might print any random value. Initializing with int x = 0; ensures ’x’ has a defined, predictable value. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 45/62
  • 59. Common Errors and Troubleshooting in C Syntax errors: Issues with the code’s structure, often caught by the compiler. Runtime errors: Errors that occur during the execution of the program, such as division by zero. Logic errors: Flaws in the program’s logic leading to incorrect output despite successful compilation. Debugging tips: Use of debugger tools, reading compiler warnings, and code reviews. #include <stdio.h> int main() { int a = 10, b = 0; int result; // Runtime error example: division by zero if (b != 0) { result = a / b; } else { printf("Error: Division by zeron"); } // Logic error example: incorrect condition if (a = 10) { // Should be ’==’, not ’=’ printf("a is 10n"); } return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 46/62
  • 60. C Programs: Re-usability Small reusable programs demonstrate language features: Math and prime checks String operations Sorting algorithms File handling #include <stdio.h> int factorial(int num) { int f = 1; for(int i=1; i<=num; i++) { f *= i; } return f; } int main() { int num; printf("Enter a number: "); scanf("%d", &num); int result = factorial(num); printf("The factorial of %d is %d", num, result); return 0; } Modular programs effectively showcase constructs and libraries. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 47/62
  • 61. C Programs : Modularization Header files modularize functionality: int add(int , int); int factorial(int); #include "math.h" int main () { int s = add(5, 10); int f = factorial (5); } Header files and libraries enable code reuse across source files. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 48/62
  • 62. Function Call Challenge #include <stdio.h> void update(int x) { x = x + 10; } int main() { int a = 5; update(a); printf("a: %dn", a); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 49/62
  • 63. Function Call Challenge #include <stdio.h> void update(int x) { x = x + 10; } int main() { int a = 5; update(a); printf("a: %dn", a); return 0; } Question What is the value of ’a’ after the function call and why? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 49/62
  • 64. Function Call Challenge #include <stdio.h> void update(int x) { x = x + 10; } int main() { int a = 5; update(a); printf("a: %dn", a); return 0; } Question What is the value of ’a’ after the function call and why? Answer The value of ’a’ remains 5 after the function call. In C, function parameters are passed by value. Therefore, the function ’update’ modifies a copy of ’a’, not ’a’ itself. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 49/62
  • 65. Function Call Challenge: Update with Pointer #include <stdio.h> void update(int *x) { *x = *x + 10; } int main() { int a = 5; update(&a); printf("a: %dn", a); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 50/62
  • 66. Function Call Challenge: Update with Pointer #include <stdio.h> void update(int *x) { *x = *x + 10; } int main() { int a = 5; update(&a); printf("a: %dn", a); return 0; } Question What is the value of ’a’ after the function call now? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 50/62
  • 67. Function Call Challenge: Update with Pointer #include <stdio.h> void update(int *x) { *x = *x + 10; } int main() { int a = 5; update(&a); printf("a: %dn", a); return 0; } Question What is the value of ’a’ after the function call now? Answer Now the value of ’a’ is 15 after the function call. The function ’update’ uses a pointer to directly modify the value of ’a’. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 50/62
  • 68. File I/O File handling allows data persistence across executions. Opening and closing files Reading and writing data Text vs Binary modes #include <stdio.h> int main() { FILE *fptr; fptr = fopen("file.txt","w"); fprintf(fptr,"Hello World!"); fclose(fptr); fptr = fopen("file.txt","r"); char buffer[100]; fscanf(fptr,"%s", buffer); printf("Data: %s", buffer); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 51/62
  • 69. Basic File Operations in C #include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); if (fp == NULL) { perror("Error opening file"); return -1; } fprintf(fp, "Hello, world!n"); fclose(fp); return 0; } Opening a File: Use ‘fopen()‘ to open a file. Modes include ”r”, ”w”, ”a”. Reading from a File: Use ‘fscanf()‘ or ‘fgets()‘ for reading. Writing to a File: Use ‘fprintf()‘ or ‘fputs()‘ for writing. Closing a File: Always close a file using ‘fclose()‘. Error Handling: Check the return value of file operations for errors. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 52/62
  • 70. Debugging Challenge: File I/O #include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); fprintf(fp, "%d %d %d", 5, 10, 15); fclose(fp); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 53/62
  • 71. Debugging Challenge: File I/O #include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); fprintf(fp, "%d %d %d", 5, 10, 15); fclose(fp); return 0; } Question What is the content of ”example.txt” after executing this program? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 53/62
  • 72. Debugging Challenge: File I/O #include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); fprintf(fp, "%d %d %d", 5, 10, 15); fclose(fp); return 0; } Question What is the content of ”example.txt” after executing this program? Answer The content of ”example.txt” will be ”5 10 15”. The program writes these three integers to the file separated by spaces using fprintf. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 53/62
  • 73. Preprocessors Preprocessors handle meta programming logic. Directives evaluated before compilation #include, #define, #ifdef etc. Macro expansions File inclusion Conditional compilation #include <stdio.h> #define PRINT printf #define SQUARE(x) x*x int main() { PRINT("In main functionn"); int num=5; PRINT("Square of %d is %d", num, SQUARE(num)); eturn 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 54/62
  • 74. Preprocessors : File Inclusion Preprocessors insert contents of file during compilation. include < file > - Search built-in directories include ”file” - Search current directory include < file.h > - Header files convention #include <stdio.h> int main() { printf("Standard library"); #include "userdefs.h" printcustom(); return 0; } This demonstrates: Inclusion of stdio.h from built-in folders Inclusion of userdefs.h from current folder Calling custom function after inclusion Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 55/62
  • 75. Preprocessors: Macro Arguments Macros can make code more readable and maintainable. Define macros accepting parameters: # define MACRO (arg1, arg2) (arg1 + arg2) #include <stdio.h> #define MIN(x,y) ((x) < (y) ? (x) : (y)) int main() { int a = 10, b = 5; int small = MIN(a, b); //Macro invocation printf("Minimum of %d & %d is: %d", a, b, small); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 56/62
  • 76. Understanding Macros #include <stdio.h> #define SQUARE(x) (x*x) int main() { int a = 4, b = 2; int result = SQUARE(a + b); printf("Result: %dn", result); return 0; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 57/62
  • 77. Understanding Macros #include <stdio.h> #define SQUARE(x) (x*x) int main() { int a = 4, b = 2; int result = SQUARE(a + b); printf("Result: %dn", result); return 0; } Question What is the output of this program and why? Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 57/62
  • 78. Understanding Macros #include <stdio.h> #define SQUARE(x) (x*x) int main() { int a = 4, b = 2; int result = SQUARE(a + b); printf("Result: %dn", result); return 0; } Question What is the output of this program and why? Answer The output is 14, not 36. The macro expands to (a + b * a + b), which is equivalent to (4 + 2 * 4 + 2) due to macro substitution leading to unexpected results without proper parentheses. Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 57/62
  • 79. Preprocessors: #if − #else − #endif Conditionally include code sections during compilation. {#if CONDITION //code A else //code B #endif } This shows: DEBUG macro definition as flag Code inside if block prints when defined Alternate code in else prints when not defined #define DEBUG int main() { #if DEBUG printf("In debug moden"); #else printf("Debug disabledn"); #endif // Rest of code } #endif Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 58/62
  • 80. Predefined Macros Commonly available predefined macros are: FILE - Current filename LINE - Current line number DATE - Compilation date TIME - Compilation time #include <stdio.h> int main() { printf("Compiled at line %d of file %s n", LINE, FILE ); printf("On date: %s time: %sn", DATE, TIME); return 0; } FILE and LINE for displaying context DATE and TIME for compilation timestamps Other interesting predefined macros are: STDC - Conformance level indicator FUNCTION- Prints function name Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 59/62
  • 81. Sequential Statements Modular program structure Functions, headers, libraries Sequence of statements execute top to bottom Code blocks, conditionals Input, process, output, style Program structure best practices Statements execute sequentially Overall program flow and stages Systematic sequence of steps solve problem. #include <stdio.h> // Function declaration void readInput(); int main() { // Initialize int num; // Read input readInput(); // Process num = num * 2; // Display output printf("%d", num); return 0; } // Define function void readInput() { scanf("%d", &num); } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 60/62
  • 82. Modular Programs Functions follow calling conventions for parameter passing. Functions encapsulate logic: Declaration in header file Definition with logic Call from multiple places This demonstrates: Function declaration in header Calling declared function from main() Definition separate from usage // In header.h int add(int, int); // In main.c #include "header.h" int main() { int sum = add(5, 10); printf("Sum=%d",sum); } // In add.c int add(int a, int b) { return a+b; } Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 61/62
  • 83. Version Control Basics Version control systems track changes to files over time. Git is a distributed version control system widely used in software development. Key operations: ‘git init‘, ‘git add‘, ‘git commit‘, ‘git push‘. Benefits: Collaboration, backup, history, and branch management. // Command l i n e s n i p p e t s that show b a s i c Git commands // Example : I n i t i a l i z i n g a new Git r e p o s i t o r y g i t i n i t // Adding a f i l e to the s t a g i n g area g i t add f i l e n a m e . c // Committing changes with a message g i t commit −m ” I n i t i a l commit” // Pushing changes to a remote r e p o s i t o r y g i t push o r i g i n main Dr. Markkandan S Embedded C Programming Module-1: Introduction to C 62/62
  翻译: