Est102 Module 2
Est102 Module 2
Est102 Module 2
Overview of C Language
Features of C language
It is a robust language with rich set of built-in functions and operators that can
be used to write any complex program.
The C compiler combines the capabilities of an assembly language with features
of a high-level language.
Programs Written in C are efficient and fast. This is due to its variety of data type
and powerful operators.
It is many time faster than BASIC.
C is highly portable this means that programs once written can be run on another
machines with little or no modification.
Another important feature of C program, is its ability to extend itself.
A C program is basically a collection of functions that are supported by C library.
We can also create our own function and add it to C library.
C language is the most widely used language in operating systems and embedded
system development today.
1
Different parts of C program
Pre-processor
Header file
Function
Variables
Statements & expressions
Comments
Pre-processor
Syntax/Description
Preprocessor
Syntax: #define
This macro defines constant value and can be
Macro any of the basic data types.
Syntax: #include <file_name>
The source code of the file “file_name” is
Header file included in the main program at the specified
inclusion place.
2
Syntax: #ifdef, #endif, #if, #else, #ifndef
Set of commands are included or excluded in
Conditional source program before compilation with respect
compilation to the condition.
Syntax: #undef, #pragma
#undef is used to undefine a defined macro
variable. #Pragma is used to call a function
Other directives before and after main function in a C program.
Header file
With time, you will have a clear picture of what header files are, as of now consider
as a readymade piece of function which comes packaged with the C language and
you can use them without worrying about how they work, all you have to do is
include the header file in your program.
To use any of the standard functions, the appropriate header file must be included.
This is done at the beginning of the C source file.
For example, to use the printf() function in a program, which is used to display
anything on the screen, the line #include <stdio.h> is required because the header
file stdio.h contains the printf() function. All header files will have an extension .h
3
main() function
Comments
We can add comments in our program to describe what we are doing in the program.
These comments are ignored by the compiler and are not executed.
To add a single line comment, start it by adding two forward slashses // followed by
the comment.
To add multiline comment, enclode it between /* .... */, just like in the program
above.
All the C programs can be written and edited in normal text editors like Notepad or
Notepad++ and must be saved with a file name with extension as .c
4
If you do not add the extension .c then the compiler will not recognize it as a C
language program file.
The rule specify how the character sequence will be grouped together, to
form tokens. A smallest individual unit in C program is known as C Token. Tokens
are either keywords, identifiers, constants, variables or any symbol which has some
meaning in C language. A C program can also be called as a collection of various
tokens.
printf("Hello,World");
Semicolon ;
Semicolon ; is used to mark the end of a statement and beginning of another
statement. Absence of semicolon at the end of any statement, will mislead the
5
compiler to think that this statement is not yet finished and it will add the next
consecutive statement after it, which may lead to compilation(syntax) error.
Comments
Comments are plain simple text in a C program that are not compiled by the
compiler. We write comments for better understanding of the program. Though
writing comments is not compulsory, but it is recommended to make your program
more descriptive. It make the code more readable.
6
names because that would try to change the existing meaning of the keyword, which
is not allowed. There are total 32 keywords in C language.
do if static while
7
Rules for an Identifier
1. An Identifier can only have alphanumeric characters (a-z , A-Z , 0-9) and
underscore(_).
2. The first character of an identifier can only contain alphabet (a-z , A-Z) or
underscore (_).
3. Identifiers are also case sensitive in C. For example name and Name are two
different identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma
are permitted to be used in or as Identifier.
OPERATORS IN C LANGUAGE
C language supports a rich set of built-in operators. An operator is a symbol that tells
the compiler to perform a certain mathematical or logical manipulation. Operators
are used in programs to manipulate data and variables.
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
8
Special operators
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.
Operator Description
% remainder of division
9
Relational operators
The following table shows all relation operators supported by C.
Operator Description
> Check if operand on the left is greater than operand on the right
Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,
|| Logical OR (a || b) is true
10
! Logical NOT (!a) is false
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied
to float or double
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
11
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value
to be shifted and the right operand specifies the number of positions that the bits in
the value have to be shifted. Both operands have the same precedence.
Assignment Operators
Assignment operators supported by C language are as follows.
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result a+=b is same as
to left a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b
*= mutiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b
12
%= calculate modulus using two operands and assign the result a%=b is same as
to left operand a=a%b
Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using
conditional operator, we turn the if condition statement into a short and simple
operator.
Explanation:
13
Special operator
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
14
2. Derived data types
Derived data types are nothing but primary datatypes but a little twisted or
grouped together like array, stucture, union and pointer. These are discussed
in details later.
Data type determines the type of data a variable will hold. If a variable x is declared
as int. it means x can hold only integer values. Every variable which is used in the
program must be declared as what data-type it is.
15
Integer type
Integers are used to store whole numbers.
16
double 8 1.7E-308 to 1.7E+308
Character type
Character types are used to store characters value.
void type
void type means no value. This is usually used to specify the type of functions which
returns nothing. We will get acquainted to this datatype as we start learning more
advanced topics in C language, like functions, pointers etc.
VARIABLES IN C LANGUAGE
When we want to store any information (data) on our computer/laptop, we store it
in the computer's memory space. Instead of remembering the complex address of
that memory space where we have stored our data, our operating system provides us
17
with an option to create folders, name them, so that it becomes easier for us to find
it and access it.
Similarly, in C language, when we want to use some data value in our program, we
can store it in a memory space and name the memory space so that it becomes easier
to access it.
Datatype of Variable
A variable in C language must be given a type, which defines what type of data the
variable will hold.
It can be:
C programming language provides many built-in functions to read any given input
and to display data on screen when there is a need to output the result.
19
scanf() and printf() functions
The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to take
input from user respectively.
%d inside the scanf() or printf() functions. It is known as format string and this
informs the scanf() function, what type of input to expect and in printf() it is used to
give a heads up to the compiler, what type of output to expect.
We can also limit the number of digits or characters that can be input or output,
by adding a number with the format string specifier, like "%1d" or "%3s", the first
one means a single numeric digit and the second one means 3 characters, hence if
you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the
case for output.
20
a loop in case you want to read more than one character. The putchar() function
displays the character passed to it on the screen and returns the same character. This
function too displays only a single character at a time. In case you want to display
more than one characters, use putchar() method in a loop.
If you enter name as Study Tonight using scanf() it will only read and
store Study and will leave the part after space. But gets() function will read it
completely.
CONTROL STATEMENTS
Selection statements
Jumping statements
21
Decision making with if statement
The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are,
1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. Using else if statement
Simple if statement
if(expression)
statement inside;
statement outside;
Example:
#include <stdio.h>
void main( )
int x, y;
x = 15;
22
y = 13;
if (x > y )
x is greater than y
if...else statement
if(expression)
statement block1;
else
statement block2;
23
Example:
#include <stdio.h>
void main( )
int x, y;
x = 15;
y = 18;
if (x > y )
else
y is greater than x
24
Nested if....else statement
if( expression )
if( expression1 )
statement block1;
else
statement block2;
else
statement block3;
25
Example:
#include <stdio.h>
void main( )
int a, b, c;
printf("Enter 3 numbers...");
if(a > b)
if(a > c)
else
else
26
if(b > c)
else
else if ladder
if(expression1)
statement block1;
else if(expression2)
statement block2;
27
else if(expression3 )
statement block3;
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as
a true condition is found, the statement associated with it is executed.
Example :
#include <stdio.h>
void main( )
int a;
printf("Enter a number...");
scanf("%d", &a);
else if(a%8 == 0)
28
{
printf("Divisible by 8");
else if(a%5 == 0)
printf("Divisible by 5");
else
printf("Divisible by none");
Points to Remember
int a = 5;
if(a > 4)
printf("success");
29
2. No curly braces are required in the above case, but if we have more than one
statement inside ifcondition, then we must enclose them inside curly braces.
3. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not
comparison.
4. Other than 0(zero), all other values are considered as true.
if(27)
printf("hello");
Switch statement is a control statement that allows us to choose only one choice
among the many given choices. The expression in switch evaluates to return an
integral value, which is then compared to the values present in different cases. It
executes that block of code which matches the case value. If there is no match,
then default block is executed(if present). The general form of switch statement is,
switch(expression)
case value-1:
block-1;
30
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
1. The expression (after switch keyword) must yield an integer value i.e the
expression should be an integer or a variable or an expression that evaluates to
an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
31
4. The next line, after the case statement, can be any valid C statement.
Points to Remember
1. We don't use those expressions to evaluate switch case, which may return floating
point values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to
use break after each block, but if you do not use it, then all the consecutive blocks
of code will get executed after the matching block.
int i = 1;
switch(i)
case 1:
printf("A"); // No break
case 2:
printf("B"); // No break
case 3:
printf("C");
break;
ABC
32
The output was supposed to be only A because only the first case matches, but
as there is no break statement after that block, the next blocks are executed too,
until it a break statement in encountered or the execution reaches the end of
the switch block.
#include<stdio.h>
void main( )
int a, b, c, choice;
while(choice != 3)
33
printf("\n Enter your choice");
scanf("%d", &choice);
switch(choice)
case 1:
printf("Enter 2 numbers");
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
c = a - b;
printf("%d", c);
break;
default:
34
}
Looping Statements
Types of Loop
There are 3 types of Loop in C language, namely:
1. while loop
2. for loop
3. do while loop
while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.
35
Variable increment or decrement ( x++ or x-- or x = x + 2 )
Syntax :
variable initialization;
while(condition)
statements;
#include<stdio.h>
void main( )
int x;
x = 1;
printf("%d\t", x);
36
x++;
1 2 3 4 5 6 7 8 9 10
for loop
for loop is used to execute a set of statements repeatedly until a particular condition
is satisfied. We can say it is an open ended loop.. General format is,
statement-block;
In for loop we have exactly two semicolons, one after initialization and second after
the condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. But it can have only
one condition.
37
4. Then it evaluate the increment/decrement condition and again follows from step
2.
5. When the condition expression becomes false, it exits the loop.
#include<stdio.h>
void main( )
int x;
printf("%d\t", x);
1 2 3 4 5 6 7 8 9 10
38
Nested for loop
We can also have nested for loops, i.e one for loop inside another for loop. Basic
syntax is,
statement ;
#include<stdio.h>
void main( )
int i, j;
printf("\n");
39
/* second for loop inside the first */
printf("%d", j);
21
321
4321
54321
do while loop
In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-
while loop. do statement evaluates the body of the loop first and at the end, the
condition is checked using while statement. It means that the body of the loop will
be executed at least once, even though the starting condition inside while is
initialized to be false. General syntax is,
40
do
.....
.....
while(condition)
#include<stdio.h>
void main()
int a, i;
a = 5;
i = 1;
do
printf("%d\t", a*i);
i++;
41
5 10 15 20 25 30 35 40 45 50
Jumping Statements
Sometimes, while executing a loop, it becomes necessary to skip a part of the loop
or to leave the loop as soon as certain condition becomes true. This is known as
jumping out of loop.
1) break statement
When break statement is encountered inside a loop, the loop is immediately exited
and the program continues with the statement immediately following the loop.
42
2) continue statement
It causes the control to go directly to the test-condition and then continue the loop
process. On encountering continue, cursor leave the current cycle of loop, and starts
with the next cycle.
43