0% found this document useful (0 votes)
34 views

UNIT 1 - Basic C Programming

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

UNIT 1 - Basic C Programming

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Dr.T.

Senthilkumar, AP/EEE EE3071-EMBEDDED 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:

1.1 TYPICAL C PROGRAM-DEVELOPMENT ENVIRONMENT

C systems generally consist of several parts: a program-development


environment, the language and the C standard library. The following discussion
explains the typical C development environment.

C programs typically go through six phases to be executed—edit, preprocess,


Compile, link, load and execute.

1.1.1 Phase 1: Creating a Program

Phase 1 (in the following diagram) consists of editing a file in an editor


program:

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.

1.1.2 Phases 2: Preprocessing a C Program

In Phase 2 (Fig 2 shown in the following diagram), you give the command
to compile the program:

The compiler translates the C program into machine-language code (also


referred to as object code). In a C system, the compilation command invokes a
preprocessor program before the compiler’s translation phase begins. The C
preprocessor obeys special commands called preprocessor directives, which
perform text manipulations on a program’s source-code files. These manipulations
consist of inserting the contents of other files and various text replacements.

Fig 1.1.2

1.1.3 Phases 3: Compiling a C Program

In Phase 3 (Fig 3 shown in the following diagram), the compiler translates


the C program into machine-language code:

Fig 1.1.3

A syntax error occurs when the compiler cannot recognize a statement


because it violates the language rules. The compiler issues an error message to help
you locate and fix the incorrect statement. The C standard does not specify the
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
wording for error messages issued by the compiler, so the messages you see on
your system may differ from those on other systems. Syntax errors are also called
compile errors or compile time errors.

1.1.4 Phase 4: Linking

The next phase (Fig 4 shown in the following diagram) is called linking:

Fig 1.1.4

C programs typically use functions defined elsewhere, such as in the


standard libraries, open-source libraries or private libraries of a particular project.
The object code produced by the C compiler typically contains “holes” due to these
missing parts. A linker links a program’s object code with the code for the missing
functions to produce an executable image (with no missing pieces). On a typical
Linux system, the command to compile and link a program is gcc (the GNU C
compiler).

To compile and link a program named welcome.c using the latest C standard
(C18), type

gcc -std=c18 welcome.c

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.

1.1.5 Phase 5: Loading

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.

1.1.6 Phase 6: Execution

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

1.1.7 Problems That May Occur at Execution Time

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.

1.1.8 Standard Input, Standard Output and Standard Error Streams

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

1.2 INTRODUCTION TO C PROGRAMMING

Any programming Language can be divided in to two categories.

 Problem oriented (High level language)


 Machine oriented (Low level language)

But C is considered as a Middle level Language.

C is modular, portable, reusable.

1.2.1. Feature of C Program


 Structured language
 It has the ability to divide and hide all the information and instruction.
 Code can be partitioned in C using functions or code block.
 C is a well structured language compare to other.
 General purpose language
 Make it ideal language for system programming.
 It can also be used for business and scientific application.
 ANSI established a standard for c in 1983.
 The ability of c is to manipulate bits, byte and addresses.
 It is adopted in later 1990.
 Portability
 By modification or no modification.
 Code Re-usability & Ability to customize and extend
 A programmer can easily create his own function
 It can be used repeatedly in different application
 C program basically collection of function
 The function are supported by 'c' library
 Function can be added to 'c' library continuously
 Limited Number of Key Word
 There are only 32 keywords in 'C'
 27 keywords are given by ritchie
 5 is added by ANSI
 The strength of 'C' is lies in its in-built function
 Unix system provides as large number of C function
 Some functions are used in operation.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

1.2.2 C program structure

The components of the structure are:

Fig 1.2.1 Basic structure of C program

 Header Files Inclusion:

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.

 Some of C Header files:

stddef.h – Defines several useful types and macros.


stdint.h – Defines exact width integer types.
stdio.h – Defines core input and output functions
stdlib.h – Defines numeric conversion functions, pseudo-random network
generator, memory allocation
string.h – Defines string handling functions
math.h – Defines common mathematical functions

 Main Method Declaration:

The next part of a C program is to declare the main () function.


The syntax to declare the main function is:
Syntax to Declare main method:
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
int main()
{}

 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

The solution to any computing problem involves executing a series of


actions in a specific order. An algorithm is a procedure for solving a problem in
terms of
1. the actions to execute, and
2. the order in which these actions should execute.

1.3.2 Pseudocode

 Pseudocode is an informal artificial language similar to everyday English


that helps you develop algorithms before converting them to structured C
programs. Pseudocode is convenient and user friendly. It helps you “think
out” a program before writing it in a programming language. Computers do
not execute Pseudocode. Pseudocode consists purely of characters, so you
may type it in any text editor. Often, converting carefully prepared
Pseudocode to C is as simple as replacing a Pseudocode statement with its C
equivalent.

Pseudocode describes the actions and decisions that will execute once you
convert the Pseudocode to C and run the program.

Definitions are not executable statements— they’re simply messages to the


compiler.
For example, the definition
int i = 0;
tells the compiler variable i’s type, instructs the compiler to reserve space in
memory for the variable and initializes it to 0. But this definition does not perform
an action when the program executes, such as input, output, a calculation or a
comparison. So, some programmers do not include definitions in their Pseudocode.
Others choose to list each variable and briefly mention its purpose.

In a 'C' program are executed sequentially. This happens when there is no


condition around the statements. If you put some condition for a block of
statements the flow of execution might change based on the result evaluated by the
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
condition. This process is referred to as decision making in 'C.' The decision-
making statements are also called as control statements.

1.3.3 Conditional statements

In 'C' programming conditional statements are possible with the help of the
following two constructs:

1. If statement
2. If-else statement

It is also called as branching as a program decides which statement to execute


based on the result of the evaluated condition.

 If statement
 Relational Operators
 The If-Else statement
 Conditional Expressions
 Nested If-else Statements
 Nested Else-if statements

 If statement

It is one of the powerful conditional statement. If statement is responsible for


modifying the flow of execution of a program. If statement is always used with a
condition. The condition is evaluated first before executing any statement inside
the body of If. The syntax for if statement is as follows:

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 { }.

Following program illustrates the use of if construct in 'C' programming:

#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:

num1 is smaller than num2

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

Keep in mind that a condition that evaluates to a non-zero value is considered as


true.

For example:

int present = 1;
if (present)
printf("There is someone present in the classroom \n");

Output :

There is someone present in the classroom


Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
 The If-Else statement

Fig 2.2 if else statement

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

Following programs illustrate the use of the if-else construct:

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:

The value is greater than 10


Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING
1. We have initialized a variable with value 19. We have to find out whether
the number is bigger or smaller than 10 using a 'C' program. To do this, we
have used the if-else construct.
2. Here we have provided a condition num<10 because we have to compare
our value with 10.
3. As you can see the first block is always a true block which means, if the
value of test-expression is true then the first block which is If, will be
executed.
4. The second block is an else block. This block contains the statements which
will be executed if the value of the test-expression becomes false. In our
program, the value of num is greater than ten hence the test-condition
becomes false and else block is executed. Thus, our output will be from an
else block which is "The value is greater than 10". After the if-else, the
program will terminate with a successful result.

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

There is another way to express an if-else statement is by introducing


the ?: operator. In a conditional expression the ?: operator has only one statement
associated with the if and the else.

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

 Nested If-else Statements

When a series of decision is required, nested if-else is used. Nesting means using
one if-else construct within another one.

Let's write a program to illustrate the use of nested if-else.

#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 value is:1

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.

 Nested Else-if statements

Nested else-if is used when multipath decisions are required.

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.

Let us see the actual working with the help of a program.

#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

1. We have initialized a variable with marks. In the else-if ladder structure, we


have provided various conditions.
2. The value from the variable marks will be compared with the first condition
since it is true the statement associated with it will be printed on the output
screen.
3. If the first test condition turns out false, then it is compared with the second
condition.
4. This process will go on until the all expression is evaluated otherwise
control will go out of the else-if ladder, and default statement will be printed.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

1.4 DATA TYPES AND OPERATORS

'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.

1.4.1 Data types

Following are the three data types:

1. Primitive data types


2. Derived data types
3. User-defined data types

There are five primary fundamental data types,

1. int for integer data


2. char for character data
3. float for floating point numbers
4. double for double precision floating point numbers
5. void

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.

Data type Size in bytes Range

Char or signed char 1 -128 to 127

Unsigned char 1 0 to 255

int or signed int 2 -32768 to 32767

Unsigned int 2 0 to 65535

Short int or Unsigned short int 2 0 to 255

Signed short int 2 -128 to 127

Long int or Signed long int 4 -2147483648 to 2147483647


Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

Unsigned long int 4 0 to 4294967295

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

Long double 10 3.4E-4932 to 1.1E+4932

Note: In C, there is no Boolean data type.

 Integer 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.

An integer typically is of 2 bytes which means it consumes a total of 16 bits in


memory. A single integer value takes 2 bytes of memory. An integer data type is
further divided into other data types such as short int, int, and long int.

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.

 Floating point data type

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.

While using a floating point number a keyword float/double/long double must be


placed before an identifier. The valid examples are,

float division;
double BankBalance;

 Character data type

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;

 Void data type

A void data type doesn't contain or return any value. It is mostly used for defining
functions in 'C'.
Example,
void displayData()

 Type declaration of a variable

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

This is a symbol use to perform some operation on variables, operands or


with the constant. Some operator required 2 operand to perform operation or some
required single operation.

Several operators are there those are, arithmetic operator, assignment,


increment, decrement, logical, conditional, comma, size of, bitwise and others.

 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

 Increment and Decrement


The Unary operator ++, --, is used as increment and decrement which acts
upon single operand. Increment operator increases the value of variable by
one .Similarly decrement operator decrease the value of the variable by one. And
these
operator can only used with the variable, but can’t use with expression and
constant as ++6 or ++(x+y+z).

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.

 Logical or Boolean Operator


Operator used with one or more operand and return either value zero (for false) or
one (for true). The operand may be constant, variables or expressions. And the
expression that combines two or more expressions is termed as logical expression.

C has three logical operators:

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.

1.5.1 for Iteration Statement

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).

 for Statement Header Components


The following diagram takes a closer look 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.

 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

for (int counter = 1; counter <= 5; ++counter) {

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

 for Statement Header Components

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

 For statement flow chart

Example Summing the Even Integers from 2 to 100


Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

1.5.2 do….. while Iteration Statement

The do…while iteration statement is similar to the while statement. The


while statement tests its loop-continuation condition before executing the loop
body. The do…while statement tests its loop-continuation condition after
executing the loop body, so the loop body always executes at least once. When a
do…while terminates, execution continues with the statement after the while
clause. Figure uses a do…while statement to display the numbers from 1 through
5. We chose to pre increment the control variable counter in the loop-continuation
test (line 10).

1.5.3 do…while Statement Flowchart

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.

There are the following advantages of C functions.


 By using functions, we can avoid rewriting same logic/code again and again
in a program.
 We can call C functions any number of times in a program and from any
place in a program.
 We can track a large C program easily when it is divided into multiple
functions.
 Reusability is the main achievement of C functions.
 However, Function calling is always a overhead in a C program.

1.6.1 Function Aspects

There are three aspects of a C function.

 Function declaration A function must be declared globally in a c program


to tell the compiler about the function name, function parameters, and return
type.

 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.

 Function definition It contains the actual statements which are to be


executed. It is the most important aspect to which the control comes when
the function is called. Here, we must notice that only one value can be
returned from the function.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

S.No C function Syntax


aspects

1 Function return_type function_name (argument list);


declaration

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function


body;}

The syntax of creating function in c language is given below:


return_type function_name(data_type parameter...)
{
//code to be executed
}

1.6.2 Types of Functions

There are two types of functions in C programming:

 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

1.6.3 Return Value

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.

Example without return value:


void hello(){
printf("hello c");
}
If you want to return any value from the function, you need to use any data type
such as int, long, char, etc. The return type depends on the value to be returned
from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:


int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If
you want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use
float as the return type of the method.
float get(){
return 10.2;
}
Now, you need to call the function, to get the value of the function.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

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.

S.No Header Description


file

1 stdio.h This is a standard input/output header file. It contains all the


library functions regarding standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(),


puts(),etc.

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.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header
file.

10 setjmp.h This file contains all the jump functions.


Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

1.7 INTRODUCTION TO ARRAY

Array is the collection of similar data types or collection of similar entity


stored in contiguous memory location. Array of character is a string. Each data
item of an array is called an element. And each element is unique and located in
separated memory location. Each of elements of an array share a variable but each
element having different index no. known as subscript.
An array can be a single dimensional or multi-dimensional and number of
subscripts determines its dimension. And number of subscript is always starts with
zero. One dimensional array is known as vector and two dimensional arrays are
known as matrix.

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];

1.7.1 Declaration of an Array:

Its syntax is :

Data type array name [size];


int arr[100];
int mark[100];
int a[5]={10,20,30,100,5}
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

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;

1.7.2 Initialization of an Array:

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

Data type array name [size] = {value1, value2, value3…}

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.

So if i & j are not variable then the valid subscript are


ar [i*7],ar[i*i],ar[i++],ar[3];

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.

Example : if an array declared is:


int [20];
Total byte= 2 * 20 =40 byte.
Dr.T.Senthilkumar, AP/EEE EE3071-EMBEDDED C PROGRAMMING

1.7.3 Accessing of Array Element:

/*Write a program to input values into an array and display them*/


#include<stdio.h>
int main()
{
int arr[5],i;
for(i=0;i<5;i++)
{
printf(“enter a value for arr[%d] \n”,i);
scanf(“%d”,&arr[i]);
printf(“the array elements are: \n”);
for (i=0;i<5;i++)
{
printf(“%d\t”,arr[i]);
}
return 0;
}
OUTPUT:
Enter a value for arr[0] = 12
Enter a value for arr[1] =45
Enter a value for arr[2] =59
Enter a value for arr[3] =98
Enter a value for arr[4] =21
The array elements are 12 45 59 98 21

**************************************************************

You might also like