UNIT 1 - Basic C Programming
UNIT 1 - Basic C Programming
INTRODUCTION
C evolved from two earlier languages, BCPL26 and B27. BCPL was
developed in 1967 by Martin Richards as a language for writing operating systems
and compilers. Ken Thompson modeled many features in his B language after their
counterparts in BCPL, and in 1970 he used B to create early versions of the UNIX
operating system at Bell Laboratories.
The C language was evolved from B by Dennis Ritchie at Bell Laboratories and
was originally implemented in 1972. C initially became widely known as the
development language of the UNIX operating system. Many of today’s leading
operating systems are written in C and/or C++. C is mostly hardware-independent
—with careful design, it’s possible to write C programs that are portable to most
computers.
C is widely used to develop systems that demand performance, such as operating
systems, embedded systems, real-time systems and communications systems:
Fig 1.1.1
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
Two editors widely used on Linux systems are vi and emacs. C and C++ integrated
development environments (IDEs) such as Microsoft Visual Studio and Apple
Xcode have integrated editors. You type a C program in the editor, make
corrections if necessary, then store the program on a secondary storage device such
as a hard disk. C program filenames should end with the .c extension.
In Phase 2 (Fig 2 shown in the following diagram), you give the command
to compile the program:
Fig 1.1.2
Fig 1.1.3
The next phase (Fig 4 shown in the following diagram) is called linking:
Fig 1.1.4
To compile and link a program named welcome.c using the latest C standard
(C18), type
at the Linux prompt and press the Enter key (or Return key). Linux commands are
case sensitive. If the program compiles and links correctly, the compiler produces a
file named a.out (by default), which is welcome.c’s executable image.
The next phase (Fig 5 shown in the following diagram) is called loading:
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
Fig 1.1.5
Before a program can execute, the operating system must load it into memory. The
loader takes the executable image from disk and transfers it to memory. Additional
components from shared libraries that support the program also are loaded.
Finally, in the last phase (shown in the following diagram), the computer,
under the control of its CPU, executes the program one instruction at a time:
Fig 1.1.6
To load and execute the program on a Linux system, type. /a.out at the Linux
prompt and press Enter.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
Programs do not always work on the first try. Each of the preceding phases
can fail because of various errors that we’ll discuss. For example, an executing
program might attempt to divide by zero (an illegal operation on computers just as
in arithmetic). This would cause the computer to display an error message. You
would then return to the edit phase, make the necessary corrections and proceed
through the remaining phases again to determine that the corrections work
properly.
Errors such as division-by-zero that occur as programs run are called runtime
errors or execution-time errors. Divide-by-zero is generally a fatal error that causes
the program to terminate immediately without successfully performing its job.
Nonfatal errors allow programs to run to completion, often producing incorrect
results.
Most C programs input and/or output data. Certain C functions take their
input from stdin (the standard input stream), which is normally the keyboard. Data
is often output to stdout (the standard output stream), which is normally the
computer screen. When we say that a program prints a result, we normally mean
that the result is displayed on a screen. Data also may be output to devices such as
disks and printers. There’s also a standard error stream referred to as stderr, which
is normally connected to the screen and used to display error messages. It’s
common to route regular output data, i.e., stdout, to a device other than the screen
while keeping stderr assigned to the screen so that the user can be immediately
informed of errors.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
The first and foremost component is the inclusion of the Header files in a C
program.
A header file is a file with extension .h which contains C function declarations and
macro definitions to be shared between several source files.
Variable Declaration:
The next part of any C program is the variable declaration. It refers to the
variables that are to be used in the function. Please note that in the C program, no
variable can be used without being declared. Also in a C program, the variables are
to be declared before any operation in the function.
Example:
int main()
{
int a;
}
Body:
Body of a function in C program, refers to the operations that are performed in the
functions. It can be anything like manipulations, searching, sorting, printing, etc.
Example:
int main()
{
int a;
printf("%d", a);
}
Return Statement:
The last part in any C program is the return statement. The return statement refers
to the returning of the values from a function. This return statement and return
value depend upon the return type of the function. For example, if the return type is
void, then there will be no return statement. In any other case, there will be a return
statement and the return value will be of the type of the specified return type.
Example:
int main()
{
int a;
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
printf("%d", a);
return 0;
}
1.3 STRUCTURED PROGRAM DEVELOPMENT IN C
1.3.1 Algorithms
1.3.2 Pseudocode
Pseudocode describes the actions and decisions that will execute once you
convert the Pseudocode to C and run the program.
In 'C' programming conditional statements are possible with the help of the
following two constructs:
1. If statement
2. If-else statement
If statement
Relational Operators
The If-Else statement
Conditional Expressions
Nested If-else Statements
Nested Else-if statements
If statement
if (condition)
instruction;
The condition evaluates to either true or false. True is always a non-zero value, and
false is a value that contains zero. Instructions can be a single instruction or a code
block enclosed by curly braces { }.
#include<stdio.h>
int main()
{
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}
Output:
The above program illustrates the use of if construct to check equality of two
numbers.
1. In the above program, we have initialized two variables with num1, num2
with value as 1, 2 respectively.
2. Then, we have used if with a test-expression to check which number is the
smallest and which number is the largest. We have used a relational
expression in if construct. Since the value of num1 is smaller than num2, the
condition will evaluate to true.
3. Thus it will print the statement inside the block of If. After that, the control
will go outside of the block and program will be terminated with a
successful result.
Relational Operators
C has six relational operators that can be used to formulate a Boolean expression
for making a decision and testing conditions, which returns true or false :
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Notice that the equal test (==) is different from the assignment operator (=)
because it is one of the most common problems that a programmer faces by mixing
them up.
For example:
int x = 41;
x =x+ 1;
if (x == 42) {
printf("You succeed!");}
Output :
You succeed
For example:
int present = 1;
if (present)
printf("There is someone present in the classroom \n");
Output :
The if-else is statement is an extended version of If. The general form of if-else is
as follows:
if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;
n this type of a construct, if the value of test-expression is true, then the true block
of statements will be executed. If the value of test-expression if false, then the false
block of statements will be executed. In any case, after the execution, the control
will be automatically transferred to the statements appearing outside the block of
If.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
We will initialize a variable with some value and write a program to determine if
the value is less than ten or greater than ten.
Let's start.
#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
In 'C' programming we can use multiple if-else constructs within each other which
are referred to as nesting of if-else statements.
Conditional Expressions
For example:
#include <stdio.h>
int main() {
int y;
int x = 2;
y = (x >= 6) ? 6 : x;/* This is equivalent to: if (x >= 5) y = 5; else y = x; */
printf("y =%d ",y);
return 0;}
Output :
y =2
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
When a series of decision is required, nested if-else is used. Nesting means using
one if-else construct within another one.
#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output:
The above program checks if a number is less or greater than 10 and prints the
result using nested if-else construct.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
1. Firstly, we have declared a variable num with value as 1. Then we have used
if-else construct.
2. In the outer if-else, the condition provided checks if a number is less than
10. If the condition is true then and only then it will execute the inner loop.
In this case, the condition is true hence the inner block is processed.
3. In the inner block, we again have a condition that checks if our variable
contains the value 1 or not. When a condition is true, then it will process the
If block otherwise it will process an else block. In this case, the condition is
true hence the If a block is executed and the value is printed on the output
screen.
4. The above program will print the value of a variable and exit with success.
The general syntax of how else-if ladders are constructed in 'C' programming is as
follows:
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;
This type of structure is known as the else-if ladder. This chain generally looks like
a ladder hence it is also called as an else-if ladder. The test-expressions are
evaluated from top to bottom. Whenever a true test-expression if found, statement
associated with it is executed. When all the n test-expressions becomes false, then
the default else statement is executed.
#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}
Output:
First class
The above program prints the grade as per the marks scored in a test. We have used
the else-if ladder construct in the above program.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
'C' provides various data types to make it easy for a programmer to select a
suitable data type as per the requirements of an application.
Array, functions, pointers, structures are derived data types. 'C' language provides
more extended versions of the above mentioned primary data types. Each data type
differs from one another in size and range. Following table displays the size and
range of each data type.
Integer is nothing but a whole number. The range for an integer data type varies
from machine to machine. The standard range for an integer data type is -32768 to
32767.
Each data type differs in range even though it belongs to the integer data type
family. The size may not change for each data type of integer family.
The short int is mostly used for storing small numbers, int is used for storing
averagely sized integer values, and long int is used for storing large integer values.
Whenever we want to use an integer data type, we have place int before the
identifier such as,
int age;
Here, age is a variable of an integer data type which can be used to store integer
values.
Like integers, in 'C' program we can also make use of floating point data types.
The 'float' keyword is used to represent the floating point data type. It can hold a
floating point value which means a number is having a fraction and a decimal part.
A floating point value is a real number that contains a decimal point. Integer data
type doesn't store the decimal part hence we can use floats to store decimal part of
a value.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
Generally, a float can hold up to 6 precision values. If the float is not sufficient,
then we can make use of other data types that can hold large floating point values.
The data type double and long double are used to store real numbers with precision
up to 14 and 80 bits respectively.
float division;
double BankBalance;
Character data types are used to store a single character value enclosed in single
quotes.
A character data type takes up-to 1 byte of memory space.
Example,
Char letter;
A void data type doesn't contain or return any value. It is mostly used for defining
functions in 'C'.
Example,
void displayData()
int main() {
int x, y;
float salary = 13.48;
char letter = 'K';
x = 25;
y = 34;
int z = x+y;
printf("%d \n", z);
printf("%f \n", salary);
printf("%c \n", letter);
return 0;}
Output:
59
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
13.480000
K
We can declare multiple variables with the same data type on a single line by
separating them with a comma. Also, notice the use of format specifiers
in printf output function float (%f) and char (%c) and int (%d).
1.4.2 Operator
Arithmetic Operator
This operator used for numeric calculation. These are of either Unary
arithmetic operator, Binary arithmetic operator. Where Unary arithmetic operator
required only one operand such as +,-, ++, --, !, tiled. And these operators are
addition, subtraction, multiplication, division. Binary arithmetic operator on other
hand required two operand and its operators are + (addition), - (subtraction),
*(multiplication), / (division), %( modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c. Unary (+) and
Unary (-) is different from addition and subtraction. When the operands are integer
then it is called integer arithmetic and the result is always integer. When both the
operand are floating point then it is called floating arithmetic and when operand is
of integer and floating point then it is called mix type or mixed mode arithmetic.
Assignment Operator
A value can be stored in a variable with the use of assignment operator. The
assignment operator (=) is used in assignment statement and assignment
expression. Operand on the left hand side should be variable and the operand on
the right hand side should be variable or constant or any expression. When variable
on the left hand side is occur on the right hand side then we can avoid by writing
the compound statement.
For example,
int x= y;
int Sum=x+y+z;
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
In the prefix the value of the variable is incremented 1st, and then the new
value is used, where as in postfix the operator is written after the operand (such as
m++, m--).
EXAMPLE
let
y=12;
z= ++y;
y= y+1;
z= y;
Similarly in the postfix increment and decrement operator is used in the operation .
And then increment and decrement is perform.
EXAMPLE
let
x= 5;
y= x++;
y=x;
x= x+1;
Relational Operator
It is use to compared value of two expressions depending on their relation.
Expression that contain relational operator is called relational expression. Here the
value is assign according to true or false value.
a.(a>=b) || (b>20)
b.(b>a) && (e>b)
c. 0(b!=7)
Conditional Operator
It sometimes called as ternary operator. Since it required three expressions as
operand and it is represented as (? , :).
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
SYNTAX
exp1 ? exp2 :exp3
Here exp1 is first evaluated. It is true then value return will be exp2 .
If false then
exp3.
EXAMPLE
Void main ()
{
int a=10, b=2
int s= (a>b) ? a:b;
printf(“value is:%d”);
}
Output:
Value is:10
Comma Operator
Comma operator is use to permit different expression to be appear in a situation
where only one expression would be used. All the expression are separator by
comma and are evaluated from left to right.
EXAMPLE
int i, j, k, l;
for(i=1,j=2;i<=5;j<=10;i++;j++)
Size of Operator
Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier. Generally it is used make portable program (program that can be run on
different machine) . It determines the length of entities, arrays and structures when
their sizes are not known to the programmer. It is also use to allocate size of
memory dynamically during execution of the program.
EXAMPLE
main( )
{
int sum;
float f;
printf( "%d%d" ,size of(f), size of (sum) );
printf("%d%d", size of(235 L), size of(A));
}
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
Bitwise Operator
Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are
one's complement (~)
bitwise AND (&)
bitwise OR (|)
bitwise XOR (^)
left shift (<<)
right shift (>>)
These operators can operate on integer and character value but not on float and
double. In bitwise operator the function showbits( ) function is used to display the
binary representation of any integer or character value.
In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits. As the bitwise OR operator is used to set on a
particular bit in a number. Bitwise AND the logical AND.
It operate on 2operands and operands are compared on bit by bit basic. And hence
both the operands are of same type.
Operator Meaning
&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical
AND gives result true if both the conditions are true, otherwise result is false. And
logial OR gives result false if both the condition false, otherwise result is true.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
Table of operators
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
1.5 C PROGRAM CONTROL
Use the for and do…while iteration statements to execute statements repeatedly.
Understand multiple selection using the switch selection statement.
Use the break and continue statements to alter the flow of control.
Use logical operators to form complex conditions in control statements.
The for iteration statement (lines 8–10) handles all the details of counter controlled
iteration. For readability, try to fit the for statement’s header (line 8) on one line.
The for statement executes as follows:
When it begins executing, the for statement defines the control variable
counter and initializes it to 1.
Next, it tests its loop-continuation condition counter <= 5. The initial value
of counter is 1, so the condition is true, and the for statement executes its
printf statement (line 9) to display counter’s value, namely 1.
Next, the for statement increments the control variable counter using the
expression ++counter, then re-tests the loop-continuation condition. The control
variable is now equal to 2, so the condition is still true, and the for statement
executes its printf statement again.
• This process continues until the control variable counter becomes 6. At this point,
the loop-continuation condition is false and iteration terminates.
The program continues executing with the first statement after the for (line 12).
Control Variables Defined in a for Header Exist Only Until the Loop
Terminates
When you define the control variable in the for header before the first semicolon
(;),as in line 8
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
example :
1 // ****
2 // Counter-controlled iteration with the for statement.
3 #include <stdio.h>
4
5 int main(void) {
6 // initialization, iteration condition, and increment
7 // are all included in the for statement header.
8 for (int counter = 1; counter <= 5; ++counter) {
9 printf("%d ", counter);
10 }
11
12 puts(""); // outputs a newline
13 }
output 1 2 3 4 5
The following diagram takes a closer look at for statement, which specifies
each of the items needed for counter-controlled iteration. If there’s more than one
statement in the for’s body, braces are required. As with the other control
statements, always place a for statement’s body in braces, even if it has only one
statement.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
The following do…while statement flowchart makes it clear that the loop-
ontinuation condition does not execute until after the loop’s action is performed the
first time:
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
1.6 C FUNCTIONS
In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity to the
C program. In other words, we can say that the collection of functions creates a
program. The function is also known as procedure or subroutine in other
programming languages.
Function call Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration.
We must pass the same number of functions as it is declared in the function
declaration.
Library Functions: are the functions which are declared in the C header
files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity
of a big program and optimizes the code.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
A C function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the
function.
Let's see a simple example of C function that returns int value from the function.
Library functions are the inbuilt function in C that are grouped and placed at a
common place called the library. Such functions are used to perform some specific
operations. For example, printf is a library function used to print on the console.
The library functions are created by the designers of compilers. All C standard
library functions are defined inside the different header files saved with the
extension .h. We need to include these header files in our program to make use of
the library functions defined in such header files. For example, To use the library
functions such as printf/scanf we need to include stdio.h in our program which is a
header file that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
4 stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related
functions like sqrt(), pow(), etc.
9 signal.h All the signal handling functions are defined in this header
file.
Array variable can store more than one value at a time where other variable can
store one value at a time.
Example:
int arr[100];
int mark[100];
Its syntax is :
The declaration of an array tells the compiler that, the data type, name of the array,
size of the array and for each element it occupies memory space. Like for int data
type, it occupies 2 bytes for each element and for float it occupies 4 byte for each
element etc. The size of the array operates the number of elements that can be
stored in an array and it may be a int constant or constant int expression. We can
represent individual array as :
int ar[5];
ar[0], ar[1], ar[2], ar[3], ar[4];
Symbolic constant can also be used to specify the size of the array as:
#define SIZE 10;
After declaration element of local array has garbage value. If it is global or static
array then it will be automatically initialize with zero. An explicitly it can be
initialize that
Example:
in ar[5]={20,60,90, 100,120}
Array subscript always start from zero which is known as lower bound and upper
value is known as upper bound and the last subscript value is one less than the size
of array. Subscript can be an expression i.e. integer value. It can be any integer,
integer constant, integer variable, integer expression or return value from
functional call that yield integer value.
The array elements are standing in continuous memory locations and the amount of
storage required for hold the element depend in its size & type. Total size in byte
for 1D array is:
Total bytes=size of (data type) * size of array.
**************************************************************