Contains C programming tutorial for beginners with lot of examples explained. This tutorial contains each and every feature of C programming that will help you. C programming tutorial covering basic C Programming examples, data types, functions, loops, arrays, pointers, etc.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, comments, preprocessor directives, libraries and headers. It also covers pointers, arrays, passing command line arguments and standard header files in C. Examples of simple C programs are provided to illustrate various concepts.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, libraries, headers, and compilers. It also covers pointers, arrays, preprocessor directives, and macros. Examples are provided to illustrate basic C programs and common programming constructs in C.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like main functions, libraries, headers, source/header files. It also covers basic C concepts like data types, variables, operators, functions, pointers, arrays, comments and preprocessor directives. Examples of simple C programs are provided to illustrate these concepts.
The document describes the structure of a C++ program. It is divided into several key sections: documentation, link, namespaces, global definitions, main program, and subprograms. The main program section contains the main function which is called when the program executes. Subprogram sections contain user-defined functions. The document also discusses preprocessing directives, macros, file inclusion and other elements that make up the overall structure of a C++ program.
This document provides an overview of embedded systems programming. It discusses that embedded computers are used as part of larger systems to control physical devices. Reliability is often critical and resources are limited. Application areas include microcontrollers, real-time response requirements, and possible organization of embedded systems. C is discussed as a commonly used programming language for embedded systems due to its efficiency, ability to handle low-level activities, and ability to be compiled on different computers.
The document summarizes the C programming language. It discusses:
- The origins and evolution of C in the 1970s, influenced by other languages.
- How C was standardized in 1989 and updated in later standards.
- The basic elements of a C program including main(), functions, variables, libraries, and compilers/linkers.
- Key features of C like data types, operators, control flow, and standard libraries.
- How pointers and arrays work in C including memory layout and pointer arithmetic.
- The C preprocessor and how it is used for macros, conditional compilation, and file inclusion.
Brief introduction to the c programming languageKumar Gaurav
The document provides an introduction to the C programming language. It discusses that C was created in the 1970s and was influenced by other languages. It describes standardization of C in 1989 and later updates. It also covers basic elements of a C program like main functions, header files, simple programs, passing command line arguments, and pointers. The document uses examples to explain concepts like arrays, macros, and conditional compilation using the preprocessor.
The C programming language was designed in the early 1970s and influenced by other languages. It is traditionally used for systems programming but is also used for other applications. The document provides an introduction to C including its standardization, differences between C and C++, elements of a C program including main functions and return values, and use of header files. It also discusses pointers, arrays, preprocessor directives, and macros.
1. The document discusses object oriented programming concepts like classes, objects, inheritance, and polymorphism in C++.
2. It begins with an introduction to procedural programming and its limitations. Object oriented programming aims to overcome these limitations by emphasizing data over procedures and allowing for inheritance, polymorphism, and encapsulation.
3. The document then covers key OOP concepts like classes, objects, constructors, and static class members in C++. It provides examples of creating classes and objects.
This document provides an overview of data structures in C, including key elements like comments, preprocessor directives, the main function, data types, variable declarations, statements and expressions, functions, control structures, I/O functions, libraries, and the return statement. It explains that C is a procedural language with a basic structure consisting of elements and syntax rules. It also lists common data types in C like int, float, and char, and control structures such as if/else and while/for loops.
Programming with c language practical manualAnil Bishnoi
This document provides information about a practical work book for a programming with C-Language course. It contains 15 lab sessions covering topics such as the Turbo C++ IDE, C building blocks like data types and I/O functions, operators and expressions, looping constructs, decision making, functions, arrays, strings, pointers, hardware interfacing, structures, linked lists, graphics, and a final project. Each lab session describes the objectives, theory, examples, exercises, and outputs of the experiments covered in that session.
This document provides an introduction to the C programming language. It discusses fundamental C elements like data types, variables, constants, operators, and input/output functions. It explains how a basic C program is structured and compiled. Examples are provided to demonstrate simple C statements, arithmetic expressions, and how to write and run a first program that prints text. The key topics covered include basic syntax, program structure, data types, identifiers, operators, and input/output functions like printf() and scanf().
The document discusses the basics of C programming language including the structure of a C program, constants, variables, data types, operators, and expressions. It explains the different sections of a C program such as documentation, link, definition, global declaration, main function, and user-defined function sections. It also describes various data types in C like integer, floating point, character, and void. Furthermore, it covers various operators used in C like arithmetic, assignment, relational, logical, bitwise, ternary, and increment/decrement operators and provides examples.
The document discusses the structure and fundamentals of C programming. It describes the typical sections of a C program including documentation, preprocessor directives, global declarations, the main function, and local declarations. It also covers input/output functions like scanf and printf, and data types in C like constants, variables, keywords, and identifiers. Finally, it discusses variable scope and the differences between local and global variables.
This document provides an overview of C programming and covers basic C constructs including variables, data types, program structure, and input/output. It discusses the key components of a simple C program including preprocessor directives, input, computation, and output. The document also demonstrates a sample C program that converts miles to kilometers and explains how variables are stored and accessed in computer memory. Finally, it discusses common programming errors and provides guidance on programming style.
The document provides an overview of key C++ concepts including:
- C++ is an extension of C that adds object-oriented features like inheritance, polymorphism, encapsulation and abstraction.
- It discusses the differences between C and C++, data types, variables, arrays, strings, functions, and conditionals.
- The document concludes with examples of C++ programs and practice questions.
C is a programming language developed in the 1960s-1970s. It supports various data types, variables, operators, functions, arrays, pointers, and file handling. Some key elements of C include conditional statements like if/else and switch, loops like while, for, and do-while, comments, and escape sequences. Functions allow breaking programs into reusable blocks of code. Arrays and pointers allow working with groups of variables. Files can be opened, read from, and written to using file handling functions.
The document provides an overview of C programming basics including:
- A brief history of the C programming language and why it is commonly used in embedded systems.
- The basic structure of a C program including comments, header files, functions, and data types.
- How to declare and initialize variables in C including different data types.
- Operators and expressions in C including arithmetic, relational, logical, and bitwise operators.
- Decision making and control flow in C using if/else statements and switch cases.
- Instructions to ask questions and contact the instructor for help.
The document discusses preprocessor directives in C programming. It explains that the preprocessor processes the source code before it is passed to the compiler. Some key preprocessor directives discussed include #define for defining macros, #include for including header files, #line for renumbering source lines, and predefined macros like _ _DATE_ _ and _ _LINE_ _. It also discusses macros for logical and mathematical operations and identifies standard input/output streams.
Here is a recursive C function that solves the Tower of Hanoi problem:
#include <stdio.h>
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 0)
return;
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...VLSICS Design
This paper explores the use of macros and parameters in Hardware Description Language (HDL)
programming. Macros and parameters are powerful tools that allow for efficient and reusable code, yet
their full potential is often underutilized. By examining the advantages of macros and parameters, this
paper aims to demonstrate how these features can enhance the flexibility, readability, and maintainability
of HDL code. Additionally, the paper discusses the use cases of mixing macros and parameters in HDL
programming, highlighting their applicability in a range of scenarios. Furthermore, the paper addresses
the challenges that arise from the mix use of macros and parameters and provides best practices to
overcome these challenges. Overall, this paper aims to encourage HDL programmers to fully explore the
capabilities of macros and parameters in their code, leading to more efficient and effective hardware
designs and verification.
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...VLSICS Design
This paper explores the use of macros and parameters in Hardware Description Language (HDL) programming. Macros and parameters are powerful tools that allow for efficient and reusable code, yet their full potential is often underutilized. By examining the advantages of macros and parameters, this paper aims to demonstrate how these features can enhance the flexibility, readability, and maintainability of HDL code. Additionally, the paper discusses the use cases of mixing macros and parameters in HDL programming, highlighting their applicability in a range of scenarios. Furthermore, the paper addresses the challenges that arise from the mix use of macros and parameters and provides best practices to overcome these challenges. Overall, this paper aims to encourage HDL programmers to fully explore the capabilities of macros and parameters in their code, leading to more efficient and effective hardware designs and verification.
C is a structured programming language developed by Dennis Ritchie in 1973 at Bell Laboratories. It was created to implement the UNIX operating system. C has features like being simple, portable, structured programming, a rich library, memory management, speed, pointers, recursion, and is a middle-level language. The basic structure of a C program includes documentation, link, definition, global declaration, main, and subprogram sections. It uses tokens, semicolons, comments, identifiers, keywords, and whitespace to structure the code.
The document provides an introduction to algorithms and key concepts related to algorithms such as definition, features, examples, flowcharts, pseudocode. It also discusses different types of programming languages from first to fifth generation. Key points of structured programming approach and introduction to C programming language are explained including data types, variables, constants, input/output functions, operators, type conversion etc.
Brief introduction to the c programming languageKumar Gaurav
The document provides an introduction to the C programming language. It discusses that C was created in the 1970s and was influenced by other languages. It describes standardization of C in 1989 and later updates. It also covers basic elements of a C program like main functions, header files, simple programs, passing command line arguments, and pointers. The document uses examples to explain concepts like arrays, macros, and conditional compilation using the preprocessor.
The C programming language was designed in the early 1970s and influenced by other languages. It is traditionally used for systems programming but is also used for other applications. The document provides an introduction to C including its standardization, differences between C and C++, elements of a C program including main functions and return values, and use of header files. It also discusses pointers, arrays, preprocessor directives, and macros.
1. The document discusses object oriented programming concepts like classes, objects, inheritance, and polymorphism in C++.
2. It begins with an introduction to procedural programming and its limitations. Object oriented programming aims to overcome these limitations by emphasizing data over procedures and allowing for inheritance, polymorphism, and encapsulation.
3. The document then covers key OOP concepts like classes, objects, constructors, and static class members in C++. It provides examples of creating classes and objects.
This document provides an overview of data structures in C, including key elements like comments, preprocessor directives, the main function, data types, variable declarations, statements and expressions, functions, control structures, I/O functions, libraries, and the return statement. It explains that C is a procedural language with a basic structure consisting of elements and syntax rules. It also lists common data types in C like int, float, and char, and control structures such as if/else and while/for loops.
Programming with c language practical manualAnil Bishnoi
This document provides information about a practical work book for a programming with C-Language course. It contains 15 lab sessions covering topics such as the Turbo C++ IDE, C building blocks like data types and I/O functions, operators and expressions, looping constructs, decision making, functions, arrays, strings, pointers, hardware interfacing, structures, linked lists, graphics, and a final project. Each lab session describes the objectives, theory, examples, exercises, and outputs of the experiments covered in that session.
This document provides an introduction to the C programming language. It discusses fundamental C elements like data types, variables, constants, operators, and input/output functions. It explains how a basic C program is structured and compiled. Examples are provided to demonstrate simple C statements, arithmetic expressions, and how to write and run a first program that prints text. The key topics covered include basic syntax, program structure, data types, identifiers, operators, and input/output functions like printf() and scanf().
The document discusses the basics of C programming language including the structure of a C program, constants, variables, data types, operators, and expressions. It explains the different sections of a C program such as documentation, link, definition, global declaration, main function, and user-defined function sections. It also describes various data types in C like integer, floating point, character, and void. Furthermore, it covers various operators used in C like arithmetic, assignment, relational, logical, bitwise, ternary, and increment/decrement operators and provides examples.
The document discusses the structure and fundamentals of C programming. It describes the typical sections of a C program including documentation, preprocessor directives, global declarations, the main function, and local declarations. It also covers input/output functions like scanf and printf, and data types in C like constants, variables, keywords, and identifiers. Finally, it discusses variable scope and the differences between local and global variables.
This document provides an overview of C programming and covers basic C constructs including variables, data types, program structure, and input/output. It discusses the key components of a simple C program including preprocessor directives, input, computation, and output. The document also demonstrates a sample C program that converts miles to kilometers and explains how variables are stored and accessed in computer memory. Finally, it discusses common programming errors and provides guidance on programming style.
The document provides an overview of key C++ concepts including:
- C++ is an extension of C that adds object-oriented features like inheritance, polymorphism, encapsulation and abstraction.
- It discusses the differences between C and C++, data types, variables, arrays, strings, functions, and conditionals.
- The document concludes with examples of C++ programs and practice questions.
C is a programming language developed in the 1960s-1970s. It supports various data types, variables, operators, functions, arrays, pointers, and file handling. Some key elements of C include conditional statements like if/else and switch, loops like while, for, and do-while, comments, and escape sequences. Functions allow breaking programs into reusable blocks of code. Arrays and pointers allow working with groups of variables. Files can be opened, read from, and written to using file handling functions.
The document provides an overview of C programming basics including:
- A brief history of the C programming language and why it is commonly used in embedded systems.
- The basic structure of a C program including comments, header files, functions, and data types.
- How to declare and initialize variables in C including different data types.
- Operators and expressions in C including arithmetic, relational, logical, and bitwise operators.
- Decision making and control flow in C using if/else statements and switch cases.
- Instructions to ask questions and contact the instructor for help.
The document discusses preprocessor directives in C programming. It explains that the preprocessor processes the source code before it is passed to the compiler. Some key preprocessor directives discussed include #define for defining macros, #include for including header files, #line for renumbering source lines, and predefined macros like _ _DATE_ _ and _ _LINE_ _. It also discusses macros for logical and mathematical operations and identifies standard input/output streams.
Here is a recursive C function that solves the Tower of Hanoi problem:
#include <stdio.h>
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 0)
return;
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...VLSICS Design
This paper explores the use of macros and parameters in Hardware Description Language (HDL)
programming. Macros and parameters are powerful tools that allow for efficient and reusable code, yet
their full potential is often underutilized. By examining the advantages of macros and parameters, this
paper aims to demonstrate how these features can enhance the flexibility, readability, and maintainability
of HDL code. Additionally, the paper discusses the use cases of mixing macros and parameters in HDL
programming, highlighting their applicability in a range of scenarios. Furthermore, the paper addresses
the challenges that arise from the mix use of macros and parameters and provides best practices to
overcome these challenges. Overall, this paper aims to encourage HDL programmers to fully explore the
capabilities of macros and parameters in their code, leading to more efficient and effective hardware
designs and verification.
MIGHTY MACROS AND POWERFUL PARAMETERS: MAXIMIZING EFFICIENCY AND FLEXIBILITY ...VLSICS Design
This paper explores the use of macros and parameters in Hardware Description Language (HDL) programming. Macros and parameters are powerful tools that allow for efficient and reusable code, yet their full potential is often underutilized. By examining the advantages of macros and parameters, this paper aims to demonstrate how these features can enhance the flexibility, readability, and maintainability of HDL code. Additionally, the paper discusses the use cases of mixing macros and parameters in HDL programming, highlighting their applicability in a range of scenarios. Furthermore, the paper addresses the challenges that arise from the mix use of macros and parameters and provides best practices to overcome these challenges. Overall, this paper aims to encourage HDL programmers to fully explore the capabilities of macros and parameters in their code, leading to more efficient and effective hardware designs and verification.
C is a structured programming language developed by Dennis Ritchie in 1973 at Bell Laboratories. It was created to implement the UNIX operating system. C has features like being simple, portable, structured programming, a rich library, memory management, speed, pointers, recursion, and is a middle-level language. The basic structure of a C program includes documentation, link, definition, global declaration, main, and subprogram sections. It uses tokens, semicolons, comments, identifiers, keywords, and whitespace to structure the code.
The document provides an introduction to algorithms and key concepts related to algorithms such as definition, features, examples, flowcharts, pseudocode. It also discusses different types of programming languages from first to fifth generation. Key points of structured programming approach and introduction to C programming language are explained including data types, variables, constants, input/output functions, operators, type conversion etc.
Design of Variable Depth Single-Span Post.pdfKamel Farid
Hunched Single Span Bridge: -
(HSSBs) have maximum depth at ends and minimum depth at midspan.
Used for long-span river crossings or highway overpasses when:
Aesthetically pleasing shape is required or
Vertical clearance needs to be maximized
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry
With over eight years of experience, David Boutry specializes in AWS, microservices, and Python. As a Senior Software Engineer in New York, he spearheaded initiatives that reduced data processing times by 40%. His prior work in Seattle focused on optimizing e-commerce platforms, leading to a 25% sales increase. David is committed to mentoring junior developers and supporting nonprofit organizations through coding workshops and software development.
This research presents the optimization techniques for reinforced concrete waffle slab design because the EC2 code cannot provide an efficient and optimum design. Waffle slab is mostly used where there is necessity to avoid column interfering the spaces or for a slab with large span or as an aesthetic purpose. Design optimization has been carried out here with MATLAB, using genetic algorithm. The objective function include the overall cost of reinforcement, concrete and formwork while the variables comprise of the depth of the rib including the topping thickness, rib width, and ribs spacing. The optimization constraints are the minimum and maximum areas of steel, flexural moment capacity, shear capacity and the geometry. The optimized cost and slab dimensions are obtained through genetic algorithm in MATLAB. The optimum steel ratio is 2.2% with minimum slab dimensions. The outcomes indicate that the design of reinforced concrete waffle slabs can be effectively carried out using the optimization process of genetic algorithm.
Newly poured concrete opposing hot and windy conditions is considerably susceptible to plastic shrinkage cracking. Crack-free concrete structures are essential in ensuring high level of durability and functionality as cracks allow harmful instances or water to penetrate in the concrete resulting in structural damages, e.g. reinforcement corrosion or pressure application on the crack sides due to water freezing effect. Among other factors influencing plastic shrinkage, an important one is the concrete surface humidity evaporation rate. The evaporation rate is currently calculated in practice by using a quite complex Nomograph, a process rather tedious, time consuming and prone to inaccuracies. In response to such limitations, three analytical models for estimating the evaporation rate are developed and evaluated in this paper on the basis of the ACI 305R-10 Nomograph for “Hot Weather Concreting”. In this direction, several methods and techniques are employed including curve fitting via Genetic Algorithm optimization and Artificial Neural Networks techniques. The models are developed and tested upon datasets from two different countries and compared to the results of a previous similar study. The outcomes of this study indicate that such models can effectively re-develop the Nomograph output and estimate the concrete evaporation rate with high accuracy compared to typical curve-fitting statistical models or models from the literature. Among the proposed methods, the optimization via Genetic Algorithms, individually applied at each estimation process step, provides the best fitting result.
The use of huge quantity of natural fine aggregate (NFA) and cement in civil construction work which have given rise to various ecological problems. The industrial waste like Blast furnace slag (GGBFS), fly ash, metakaolin, silica fume can be used as partly replacement for cement and manufactured sand obtained from crusher, was partly used as fine aggregate. In this work, MATLAB software model is developed using neural network toolbox to predict the flexural strength of concrete made by using pozzolanic materials and partly replacing natural fine aggregate (NFA) by Manufactured sand (MS). Flexural strength was experimentally calculated by casting beams specimens and results obtained from experiment were used to develop the artificial neural network (ANN) model. Total 131 results values were used to modeling formation and from that 30% data record was used for testing purpose and 70% data record was used for training purpose. 25 input materials properties were used to find the 28 days flexural strength of concrete obtained from partly replacing cement with pozzolans and partly replacing natural fine aggregate (NFA) by manufactured sand (MS). The results obtained from ANN model provides very strong accuracy to predict flexural strength of concrete obtained from partly replacing cement with pozzolans and natural fine aggregate (NFA) by manufactured sand.
The TRB AJE35 RIIM Coordination and Collaboration Subcommittee has organized a series of webinars focused on building coordination, collaboration, and cooperation across multiple groups. All webinars have been recorded and copies of the recording, transcripts, and slides are below. These resources are open-access following creative commons licensing agreements. The files may be found, organized by webinar date, below. The committee co-chairs would welcome any suggestions for future webinars. The support of the AASHTO RAC Coordination and Collaboration Task Force, the Council of University Transportation Centers, and AUTRI’s Alabama Transportation Assistance Program is gratefully acknowledged.
This webinar overviews proven methods for collaborating with USDOT University Transportation Centers (UTCs), emphasizing state departments of transportation and other stakeholders. It will cover partnerships at all UTC stages, from the Notice of Funding Opportunity (NOFO) release through proposal development, research and implementation. Successful USDOT UTC research, education, workforce development, and technology transfer best practices will be highlighted. Dr. Larry Rilett, Director of the Auburn University Transportation Research Institute will moderate.
For more information, visit: https://aub.ie/trbwebinars
Lecture - 7 Canals of the topic of the civil engineeringMJawadkhan1
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
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
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