0% found this document useful (0 votes)
6 views62 pages

C Programming Basics for Robotics

The document provides an overview of C programming, covering essential topics such as basics, variable declaration, data types, operators, and compiling. It highlights the differences between C and Python, the structure of C programs, and the significance of keywords and constants. Additionally, it explains various data types, modifiers, and operations in C, along with examples and syntax for better understanding.

Uploaded by

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

C Programming Basics for Robotics

The document provides an overview of C programming, covering essential topics such as basics, variable declaration, data types, operators, and compiling. It highlights the differences between C and Python, the structure of C programs, and the significance of keywords and constants. Additionally, it explains various data types, modifiers, and operations in C, along with examples and syntax for better understanding.

Uploaded by

angelinageorgy1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Programming-A

quick overview

COE- Robotics & Drones


Ranjitha R
Assistant Professor,
Dept. of EEE, CMRIT, Bengaluru
Agenda

• Basics
• Header file inclusions
• Variable declaration
• Condition loops
• General library functions
• Operators & Bitwise Operators
• Compiling
• Execution
Most commonly • As of 2021, the 5.11 release of the Linux kernel had around
used language in 30.34 million lines of code.
Embedded • 90% of this code is written in C! (27 Million)
Key Differences Between Python and C
Aspect Python C

Language Type High-level, interpreted language Low-level, compiled language

Speed Slower due to interpretation Faster as it is compiled

Memory Management Automatic (Garbage Collection) Manual (Programmer controls memory)

Typing Dynamically typed Statically typed

Code Length Shorter and concise Longer due to explicit declarations

Portability Highly portable across platforms Portable but needs recompilation

Error Detection Errors occur at runtime Errors caught during compilation

Application Area Scripting, AI/ML, web development System programming, embedded systems

Execution Interpreted at runtime Compiled to machine code

Libraries Extensive standard libraries Limited standard libraries


Basics
• Compiler is a software tool that converts high-level language instructions into
assembly language instructions (Low-level language).( Two types-native
compilers & native compilers).

• Linker- In general, programs are divided into small chunks of computer


software components, where each component performs the specific
functionality of a program.

• Integrated development environment (IDE): The integrated development


environment is a software program that runs on the host machine.

E.g., Turbo C, Code Blocks

• Debug emulator is hardware that allows to load the executable into the target
machine.

• Keywords are unique words in the C language which give special meaning to
the compiler. The C language has 32 keywords.
keywords

C language is case sensitive, so keywords shall be used as it is specified in the above


table. All characters in a keyword are in lowercase.
keywords

C language is case sensitive, so keywords shall be used as it is specified in the above


table. All characters in a keyword are in lowercase.
keywords

C language is case sensitive, so keywords shall be used as it is specified in the above


table. All characters in a keyword are in lowercase.
Character constant ‘a’, ‘A’, ‘1’, ’$’(ASCII Value)
Integer constant: -4,-3,-2,- 1,0,1,2,3,4 (2’s complement
used for –ve value)
Integer constants Decimal format, Octal and
Hexadecimal format
String Constants “ 123 “, “abc” ( c will append the null
character at the end of the string in
memory as \0)

Constants-Constant can be defined as a value that never


changes at runtime (during execution).

C language has four types of constants ( character,


integer, float, and string type constants)
e.g. printf(“Hello World\n”);
Expressions - Variables, constants, and symbols
together form actions in C language; these actions are
called expressions.

EXPRESSION, Eg: c= a+b ;


Statements: An expression that ends with a semicolon
STATEMENTS & is called a statement.

COMMENTS E.g. a = b + c ;

Comments: Comments are programmer notes in a


program,
Single line comment: Single line comments start with
// and end with a newline character, i.e., ‘\n’.
E.g.,// this is a C program single-line comment
example.
Multiple line comment: Multiple line comments start
with /* end with */.
E.g. /* This is first-line comment . This is the second
line comment This is third line comment */
Variable is the name given to a memory location that
stores a value.
• The variable name shall start with a literal, i.e., a-z,
A-Z, or an underscore, i.e., _, and 2nd character
onwards the variable name can have literals or

VARIABLES & DATA digits or symbols.


• variable names are case sensitive, so variables with
TYPES the name ‘m’ and ‘M’ will be defined as two
different variables.

Data types: The data type defines the variable size in


bytes and the type of data it can store in its memory.
• C language has two types of data types, and those
are primitive data types and user-defined data
types.
Expressions - Variables, constants, and symbols
together form actions in C language; these actions are
called expressions.
Eg: c= a+b
EXPRESSION, Statements: An expression that ends with a semicolon
STATEMENTS & is called a statement.
E.g. a = b + c ;
COMMENTS Null statement: A statement with only a semicolon, i.e.,
; is called a null statement.
• Programmers use null statements in control blocks
where the program shall do nothing in certain
conditions.
Comments: Comments are programmer notes in a
program,
Single line comment: Single line comments start with
// and end with a newline character, i.e., ‘\n’.
E.g.,// this is a C program single-line comment
example.
Multiple line comment: Multiple line comments start
with /* end with */.
E.g. /* This is first-line comment . This is the second
line comment This is third line comment */
Expressions - Variables, constants, and symbols
together form actions in C language; these actions are
called expressions.
Eg: c= a+b
EXPRESSION, Statements: An expression that ends with a semicolon
STATEMENTS & is called a statement.
E.g. a = b + c ;
COMMENTS Null statement: A statement with only a semicolon, i.e.,
; is called a null statement.
• Programmers use null statements in control blocks
where the program shall do nothing in certain
conditions.
Comments: Comments are programmer notes in a
program,
Single line comment: Single line comments start with
// and end with a newline character, i.e., ‘\n’.
E.g.,// this is a C program single-line comment
example.
Multiple line comment: Multiple line comments start
with /* end with */.
E.g. /* This is first-line comment . This is the second
line comment This is third line comment */
EXPRESSION,
STATEMENTS &
COMMENTS
VARIABLES & DATA
TYPES
Primitive data types: C language supports 5 primitive data types; those are
char, int, float, double, and void .

Syntax: Datatype Variable name = Initial value;

• Char data type: Character data type variable


can store character values (ASCII value) in its
compiler-allocated memory.
E.g. char x = ‘B’; char y = 67;

the character variable can store values from

-128 to 127.
E.g. char z = -125;
Int data type: The integer data type variable can store integer
values in its compiler allocated memory.

• The integer data type variable size depends on the compiler.


• A 16-bit compiler allocates 2 bytes to an integer variable. In this case, the integer
variable can store values between -32768 to 32767.
Float data type:
• The float data type variable can store float values in its compiler allocated memory.

E.g. float p = 7.123569;

float q = -4.1327684743;

float r = 10;

The float data type variable size depends on the compiler.

16-bit compilers allocate 4bytes to float variable, and it can store real values with fraction
components up to 6decimal precision. In this case, the integer variable can store values
between -1.2e38 to 3.4e38
Void data type
• Void data type: Variables cannot be defined with the void data type, and
compilers throw an error if a program does so.

User-defined data types:


C language supports 4 user-defined data types, i.e., enumerations,
arrays, structures, and unions
Modifiers:

• The modifiers with primitive data types will increase the size and/or range of a
variable. C language supports 4 modifiers; those are signed, unsigned, short, and
long.
• *short qualifier makes the compiler allocate short int size less than or equal to int
size.
• ** long qualifier makes the compiler allocate long int size greater than or equal to
int size.
• short <= int <= long
signed:
• This modifier allows variables to store both positive and negative values.
E.g. signed int m1 = 10; int m2 = -40;
The modifier ‘signed’ is the default modifier, so if a variable is defined as just of
data type char or int, the variable will be treated as an assigned variable.
In the above example, both the variables m1 and m2 will be signed integers and
have equal capability in size and range
unsigned: This modifier makes the
sign bit of a variable to be used for
data storage

• The range of data that can be stored in a


variable is simply doubled.
• E.g. int m3 = 32769; /* Compiler throws
overflow warning */
• unsigned int m4 = 32769; /* Compiler does
not throw warning */
• In the above example, both the variables m3
and m4 are allocated with 2bytes in memory,
but m4 is of an unsigned type so that it can
use its sign bit field for data storage and able
to store the value 32769.
short: The modifier ‘short’ orders the
compiler to strictly allocate its size less
than or equal to ‘int’ datatype size

• In general, 32bit compilers allocate 4bytes to an


integer.
• If a variable is defined of short integer type, the
compiler allocates 2bytes to that variable and also
uses extra assembly instruction where the short
integer variable is involved in arithmetic
operations to restrict the result of arithmetic
operation to 2bytes. So, the programmer shall be
cautious in the use of short integers
long: The modifier ‘long’ orders the
compiler to strictly allocate its size
greater than or equal to ‘int’ data type
size.

• In general, the modifier ‘long’ will allocate 4bytes


to an integer type variable. If the modifier is
applied twice in integer variable definition, the
compiler allocates 8bytes to the variable.
Pointers

• Pointers “point” to another variable


• Contain “address” of the other variable, for example
• Int Xyz
• pXyz = & Xyz;
• Xyz = 1200 ; /* Normal way of initializing the integer variable */
• *pXyz = 1200; /* This is another way or writing same statement*/
OPERATORS & OPERANDS
• Operators are symbols that perform operations on
operands.
• C language has 3 types of operators based on
operators that operate on how many operands;
those are unary, binary, and ternary operators.
• Expression: Group of operators and operands
together is called an expression.
operators Symbol Description example

Unary + + an implicit operator in the +4, +100, +300. Both +4 and 4 are equal.
representation of a positive number

Unary - - representing negative numbers -4,-100 and -300.

Unary ++ ++ incrementing the given integer by 1(used • char ch = ‘b’;


only on integer and character variables) ch++; /* Value in ch will become ‘c’ */
• int m1 = 20; m1++; /* Value in m1 will
become 21 */
Unary -- -- decrementing the given integer by 1 char ch = ‘b’; ch--; /* Value at ch will become
‘a’ */
int m1 = 20; m1--; /* Value at m1 will become
19 */
Address & an address of an operand int x = 2
operator
(Unary &)
operators Symbol Description example

(Boolean ~
NOT)
( Bitwise !
NOT)
sizeof()

Assignmen = to initialize, assign a value or an int b = 10; int c; c = 10;


t operator: expression to a variable

int d = 10,b=200,c=40;
d=b + c; /*Value in d will become 240 */
d= b – c; /*Value in d will become 160*/
d = b * c; /*Value in d will become 8000 */
d = b / c; /*Value in d will become 5*/
d = b % c; /*Value in d will become 0*/
d= 14 % 4; /*d value will be +2. */ d=-14 % 4; /*d value will be -
2. */
operators Symbol Description example
Compariso == Relational operators return TRUE (1) or int b = 100;
n operator FALSE (0) based on the expression result int c, d;
c = ( b ==100 ); /* c will be set to TRUE (1)
because value in b is equal to 100 */
d = ( b ==200 ); /* d will be set to FALSE (0)
because value in b is not equal to 200
Compariso != If operand1 is not equal to operand2, the not
n operator equal comparison operator returns TRUE
otherwise returns FALSE.
Greater > If operand1 is greater than operand2, the
than greater than operator returns TRUE.
operator Otherwise, it returns FALSE
Less than < If operand1 is greater than equal to
operator operand2, the greater than or equal operator
returns TRUE otherwise returns FALSE.
Boolean (&&) Logical AND operations int b =10, c = 5, d = 0;
AND int m1, m2, m3;
m1 = b && c;
Boolean OR (||) Logical OR operations int b =10, d = 0, e = 0;
operation int m4, m5, m6;
m4 = b || d;
operators Symbol Description example
Boolean (!) Not operations int b =10, d = 0;
NOT int m7, m8, m9;
operation m7 = !b;

Boolean && C language bypasses boolean AND int a = 10, b =5, c = 20;
AND short expression evaluation when one of its int d;
circuit subexpressions from left is evaluated as d = (a !=10) && (b == 5); */d will be set to
evaluation FALSE and sets the whole expression value 0(FALSE)/*
to 0(FALSE)
Boolean OR || C language bypasses the Boolean OR int a = 10, b =5, c = 20;
short circuit expression evaluation when one of its int d;
evaluation subexpressions from left is evaluated as d = (a ==10) || (b != 5); */d will be set to
TRUE and sets the whole expression value to 0(FALSE) immediately after the expression ‘(a
1(TRUE) ==10)’ /*

Bitwise left (<<) operator shifts out the n most significant bits int c ;
shift in the given operand at the left side c = b <<1;

Bitwise (>>) operator shifts out the n most significant bits int c ;
Right shift in the given operand at the right side c = b >>1;
COERCION & TYPE
CASTING
• Storing a big data type value into a small
data type variable is called narrowing,
whereas in narrowing, the big type value will
be truncated to fit in small type, data loss
will happen in this process, so the
programmer must explicitly specify the Eg: int q = -5;
conversion data type in narrowing; this is int p = 10;
called type casting. float f = 20.2354;
float g = 35.1345;
• Storing a small data type value into a big f = p; /* Coercion: automatic conversion
data type variable is called widening. The by compiler, value in f will become
widening will promote small type value to big 10.000000 because of widening */
type, and no data loss will happen in this q= (int) g; /* Type casting: explicit
process, so widening is implicit in C conversion by the programmer, value in q will
language; this is called coercion become 35 because of narrowing */
Block
• A set of statements enclosed in brackets { and } is
called Block.
• In C language, related statements in a program
will be kept in a block.
E.g., sum two variables and store them in a variable
{ int a = 10,b =20,c;
c = a + b; }
SIMPLE C PROGRAM
• One of the best simple programs in the world is
‘Hello World’, so we will learn the Hello world
program first.
#include “stdio.h”
int main(void)
{ printf(“Hello World”);
return 1; }
CONTROL STRUCTURES
• Control structures are decision-making statements in the program. C has
the following types of control structures: if ,if-else, if-else if ,if-else if-else
,switch, while ,do-while and for.
• The control structures if, if-else, if-else if, if-else if-else and switch are single
sequential pass conditional decision control statements.
• The control structures while, do-while, and for are loop conditional decision
control statements
If control structure
• The if control structure
evaluates the input
condition.
. Syntax: if( condition ) { } e.g.
• If the condition value is Check the given number is even number
TRUE (nonzero), program #include “stdio.h”
execution control will be int main()
passed to the block { int n = 100;
associated with the if
condition if( n%2 == 0)
{
printf(“Yes, it is even number”);
}
return 1;
}
if-else control structure
The if-else control structure
evaluates the input Syntax: if( condition ) { } else { }
condition, and if the e.g., Find the given number is even, or odd number
condition value is TRUE #include “stdio.h”
(nonzero), program int main()
execution control will be { int n = 101;
passed to the block if( n%2 == 0)
associated with if condition { printf(“It is even number”);
else to the block }
associated with else. else
{ printf(“It is odd number”);
}
return 1;
}
If-else if Control structure:
• The if-else if control structure Syntax:
evaluates the input condition if( condition1 ) { }
associated with if condition if the else if(Condition2) { }
condition value is TRUE (nonzero), E.g., Find the given number is even, or odd number
program execution control will be #include “stdio.h”
passed to the block associated int main()
with if condition else to the block { int n = 101; I
associated with else if condition f( n%2 == 0)
and then the else if structure { printf(“It is even number”); }
evaluates the condition and pass else if( n%2 != 0)
the control to block associated { printf(“It is odd number”);
with it if the condition value is }
TRUE.
return 1;
}
If-else if-else Control
structure:
• The if-else if-else control structure
evaluates the input condition Find the given number is divisible by 4 or 7 .
associated with the if condition if the #include “stdio.h”
condition value is TRUE (nonzero), int main()
program execution control will be {
passed to the block associated with if
condition else to the block int n = 15;
associated with else if condition, if if( n%4 == 0)
the else if condition value is TRUE { printf
(nonzero), program execution control (“It is divisible by 4”);
will be passed to block associated } else if( n%7 == 0)
with else if condition else to the block { printf(“It is divisible by 7”);
associated with else
} else
{ printf(“It is not divisible by both 4 and 7”);
} return 1;
}
Switch case : void main()
{ int var_a = 0;
printf(“Enter a value”);
• The switch control structure scanf(“%d”, &var_a);
evaluates the input expression and switch(var_a)
checks whether the expression { case 1: printf("CASE 1 MATCHED");
value matches with any of its case break;
constant expression values. If it case 2: printf("CASE 2 MATCHED");
matches, all the statements after break;
the matched case statement will be case 3: printf("CASE 3 MATCHED");
executed until the break statement case 4: printf("CASE 4 MATCHED");
or end of the switch block; else, the break;
statements after the default case default: printf("Default MATCHED");
will be executed until the break break; } return; }
statement or end of the switch If the user enters value 1, the program prints: CASE 1
block. MATCHED
If the user enters value 3, the program prints: CASE 3
MATCHED
If the user enters any value other than 1,2,3,4, the program
While Control structure:
• The while control structure
evaluates the input condition, if
the condition value is TRUE
(nonzero), the block associated
with the while loop will be Print Integer numbers from 1 to a given number
executed, the control will reach #include “stdio.h”
to while condition again, if the int main()
condition value is TRUE again, { int n = 10; int i=1;
the block associated with while while( i <= n )
loop will be executed again, this { printf(“%d ”, i);
process will be repeated until the
condition become FALSE i++;
}
return 1;
}
Do-while Control structure:
• The do-while control
structure works exactly
as while control
structure, only the Print numbers from 1 to a given number
difference is it executes #include “stdio.h”
the block associated with int main()
do-while first and then { int n = 10; i=1;
evaluates the condition. do{
printf(“%d ”, i);
i++;
}
while( i <= n );
return 1;
}
For Control structure:
• The for control structure executes initial
expressions and then evaluates the
input condition. If the condition value is
TRUE (nonzero), the block associated
with for loop will be executed, and then
post expressions will be executed, that Print numbers from 1 to a given number
control will reach to for condition again, #include “stdio.h”
if the condition value is TRUE again, the int main()
block associated with for loop and post
expression will be executed again, this { int n = 10; int i;
process will repeat until the condition for( i=1;( i <= n ); i++)
becomes FALSE. {
printf(“%d ”, i);
• Syntax: for( Initial expression; condition; }
Post expression ) { }
return 1;
}
Nested Control structures:
• C language allows nested control
structures on all types of control
structures,
e.g., an if condition can be written in Print even values between 1 and a given number
another if condition, a while loop can be
written in another while loop and if #include “stdio.h”
condition can be written in a while loop and int main()
vice versa. { int n = 10;
int i;
Syntax: if(Condition 1)
for( i=1;( i <= n ); i++)
{ if(Condition 2) { if(i%2 == 0)
{ printf(“%d ”, i);
{} }
} return 1;
} }
Continue:
• Once the program execution control reaches to
continue statement, it will stop the execution of
the rest of the statements in the block and
transfers the execution control to the condition of
the loop control structure. In the case of for loop,
the control will be transferred to post expression
and then to condition in the loop.
• Syntax: while( condition ) { - - - - - - - - - - -;
continue; - - - - - - - - - - -; }
for (Initial expression; condition; Post expression)
{ - - - - - - - - - - -; continue; - - - - - - - - - - -; }
goto: The keyword goto can transfer program
execution control to any specified statement
through a label in a function.

• Here label is a special identifier


that can mark the instruction
address (location) of a statement
in a function. Once the program
execution control reaches to goto
statement, it will transfer the
execution control to the address
associated with the label.
FUNCTIONS:Function is a
self-contained block of
statements.

• Functions play a vital role in C programming. These


basic blocks together achieve what a program wants to
do.
• Every program(Project) in C must have one function
named ‘main’. The C program execution starts from the
'main' function.
• The programs can have any number of functions that
implement different features.
Function in C has the following:
• Function Name • Function Parameters(arguments) •
Function Return Data Type • Function Body • Function
Return Value
IO FUNCTIONS

• IO (Input and output) functions are predefined functions in C language that helps
to read and write data from and to Consoles (Keyboard, Mouse, Monitor, Printers,
etc.) and Disk (Hard disk, USB Drive…etc.) devices.
• The IO functions are classified into two categories, Console and Disk IO
functions. In each category, two kinds of functions are there, unformatted and
formatted functions.
Scanf(): The scanf function
allows users to input data from
the keyboard in a specific
userdefined format.

• Syntax: int scanf(“Format string”, Address of


Parameters)
• The format string can be in the format
%{{*}{ width}} Format type specifier.
• The scanf function returns the number of
total parameters scanned by the function.
Printf(): The printf functions allow
the user to output data on the
monitor in a user-defined format

Syntax: int printf(“Format string”,


Parameter arguments);
The format string can be in the format
%{{#}{+/-}{Width}}Format specifier.
The printf function returns the number
of total characters printed by the
function.
STORAGE CLASSES: Storage classes define the
scope and life of a variable.

• The scope means how far the variable can


be accessed in a program; the life means
how long the variable holds valid value in its
allocated memory location.
• The following are 4types of storage classes
in the C language:
• Register
• Automatic
• Static
• Extern/Global
COMPILER’S DATA CACHE
OPTIMISATION
TECHNIQUE:
• If a variable is defined without a volatile qualifier,
the compiler fetches the variable value from RAM
and temporarily stores it in CPU registers; it uses
the value in the CPU register for all the statements
where the variable is read with in the module. This
technique will reduce RAM read access latency
time; Compilers generally apply this time
optimization technique on frequently used
variables to reduce the variable's access time and
improve program execution speed. Note:
Accessing data from CPU registers is faster than
accessing data from RAM
PRE-PROCESSING
DIRECTIVES
• Pre-processor is a software program that
processes the given program before
compilation. The pre-processor program
understands the preprocessing directives.
• When it sees a pre-processing directive in a
program, it expands the directive and provides
an intermediate file with all pre-processing
directives resolved, and the intermediate file
can be passed as an input to a compiler for
compilation.
ENUMERATION:
Enumeration is a user-
defined datatype.
• The programmer can define its own set of integer constants using
enumeration.
• Syntax: enum enum_name { Enumeration item1 name = item1 value,
Enumeration item2 name = item2 value, . . Enumeration item n name
= Itemn value; };
• The enumeration item value is in the integer range. On 16bit
machines, the range is from -32768 to 32767.
• Programmers can define a variable for defined enumeration type as
below:
• enum enum_name enum_variable_name = Enumeration item name;
The enumeration variable shall be initialized and assigned with
enumeration item names of that enum type. If a program fails to do
so, the compiler will throw a warning.
ARRAYS: An array is a name given to a collection of
similar data type elements stored in consecutive memory
locations. All the elements in the array can be accessed
using a single array name
Strings: A string can be defined as an array of
characters stored in the consecutive memory
location and ended with a null character, i.e.,
‘\0’. The null character ASCI value is 0.

char str[15];
scanf(“%s”,str);
Problems to be solved:
• C Program to Check for Even
or Odd Number (Using Bitwise .
AND Operator or shift)
• Convert Big Endian number to
Little Endian number

Thank you
Double data type:
• A double data type variable can store float values in its compiler-allocated
memory. The double-type variables can store float values with more precision
than the float data type variables.
E.g. double p = 7.12356989123456;
double q = -4.132768; double q = 10;
• The double data type variable’s size depends on the compiler.
• The 16-bit compilers allocate 8bytes to double variables, and it can store real
values with fraction components up to 15decimal points precision.
• In this case, double variable can store values between -2.2e308 to 1.7e308
getchar: The getchar takes input
from the keyboard until it gets the
Enter key, but it only returns the
first character.
getche:
• The getche takes input from the keyboard
and returns the character immediately,
and it does not wait for the Enter key to be
pressed by the user; as and when the user
entered a character, it takes immediately.
• The user entered character is visible on
the monitor screen with the getche
function.

You might also like