Est102 Module 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

EST102 MODULE 2

Overview of C Language

C is a structured programming language developed by Dennis Ritchie in 1973 at Bell


Laboratories. It is one of the most popular computer languages today because of its
structure, high-level abstraction, machine independent feature etc. C language was
developed to write the UNIX operating system, hence it is strongly associated with
UNIX, which is one of the most popular network operating system in use today.

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

#include is the first word of any C program. It is also known as a pre-processor.


The task of a pre-processor is to initialize the environment of the program, i.e to link
the program with the header files required.

So, when we say #include <stdio.h>, it is to inform the compiler to include


the stdio.h header file to the program before executing it.

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

A Header file is a collection of built-in(readymade) functions, which we can directly


use in our program. Header files contain definitions of the functions which can be
incorporated into any C program by using pre-processor #include statement with the
header file. Standard header files are provided with each compiler, and covers a
range of areas like string handling, mathematical functions, data conversion, printing
and reading of variables.

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

main() function is a function that must be there in every C program. Everything


inside this function in a C program will be executed. In the above
example, int written before the main() function is the return type of main() function.
we will discuss about it in detail later. The curly braces { } just after
the main() function encloses the body of 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.

Return statement - return 0;

A return statement is just meant to define the end of any C program.

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.

C Language Basic Syntax Rules

C language syntax specify rules for sequence of characters to be written in C


language. In simple language it states how to form statements in a C language
program - How should the line of code start, how it should end, where to use double
quotes, where to use curly brackets etc.

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.

If we take any one statement:

printf("Hello,World");

Then the tokens in this statement are→ printf, (, "Hello,World", ) and ;.

So C tokens are basically the building blocks of a C program.

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.

There are two ways in which we can write comments.

1. Using // This is used to write a single line comment.


2. Using /* */: The statements enclosed within /* and */ , are used to write multi-
line comments.

Some basic syntax rule for C program

 C is a case sensitive language so all C instructions must be written in lower case


letter.
 All C statement must end with a semicolon.
 Whitespace is used in C to describe blanks and tabs.
 Whitespace is required between keywords and identifiers. We will learn about
keywords and identifiers in the next tutorial.

What are Keywords in C?


Keywords are preserved words that have special meaning in C language. The
meaning of C language keywords has already been described to the C compiler.
These meaning cannot be changed. Thus, keywords cannot be used as variable

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.

auto double int struct

break else long switch

case enum register typedef

const extern return union

char float short unsigned

continue for signed volatile

default goto sizeof void

do if static while

What are Identifiers?


In C language identifiers are the names given to variables, constants, functions and
user-define data. These identifier are defined against a set of rules.

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.

C operators can be classified into following types:

 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

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator - increases integer value by one

-- Decrement operator - decreases integer value by one

9
Relational operators
The following table shows all relation operators supported by C.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators
C language supports following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example

&& Logical AND (a && b) is false

|| 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 AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

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.

Operator Description Example

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

The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3

Explanation:

 The question mark "?" in the syntax represents the if part.


 The first expression (expression 1) generally returns either true or false, based on
which it is decided whether (expression 2) will be executed or (expression 3)
 If (expression 1) returns true then the expression on the left side of " : " i.e
(expression 2) is executed.
 If (expression 1) returns false then the expression on the right side of " : " i.e
(expression 3) is executed.

13
Special operator

Operator Description Example

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

* Pointer to a variable *x ; will be pointer to a variable x

DATA TYPES IN C LANGUAGE


Data types specify how we enter data into our programs and what type of data we
enter. C language has some predefined set of data types to handle various kinds of
data that we can use in our program. These datatypes have different storage
capacities.

C language supports 2 different type of data types:

1. Primary data types:

These are fundamental data types in C namely integer(int), floating point(float),


character(char) and void.

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.

Size and range of Integer type on 16-bit machine:

Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

unsigned short int 1 0 to 255

long int or signed long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

Floating point type


Floating types are used to store real numbers.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

16
double 8 1.7E-308 to 1.7E+308

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

Character type
Character types are used to store characters value.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

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.

The naming of an address is known as variable. Variable is the name of memory


location. Unlike constant, variables are changeable, we can change value of a
variable during execution of a program. A programmer can choose a meaningful
variable name. Example : average, height, age, total etc.

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:

 char: Can hold/store a character in it.


 int: Used to hold an integer.
 float: Used to hold a float value.
 double: Used to hold a double value.
 void

Rules to name a Variable

1. Variable name must not start with a digit.


2. Variable name can consist of alphabets, digits and special symbols like
underscore _.
18
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it
is suggested to keep the variable names in lower case.

Declaring, Defining and Initializing a variable


Declaration of variables must be done before they are used in the program.
Declaration does the following things.

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.
3. Until the variable is defined the compiler doesn't have to worry about allocating
memory space to the variable.
4. Declaration is more like informing the compiler that there exist a variable with
following datatype which is used in the program.
5. A variable is declared using the extern keyword, outside the main() function.

C INPUT AND OUTPUT


Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.

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.

Format String Meaning

%d Scan or print an integer as signed decimal number

%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends at whitespace.

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.

getchar() & putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer.
This function reads only single character at a time. You can use this method in

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.

gets() & puts() functions


The gets() function reads a line from stdin(standard input) into the buffer pointed to
by str pointer, until either a terminating newline or EOF (end of file) occurs.
The puts() function writes the string str and a trailing newline to stdout.

Difference between scanf() and gets()


The main difference between these two functions is that scanf() stops reading
characters when it encounters a space, but gets() reads space as character too.

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

 Decision making statements

 Selection statements

 Iteration or Looping 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

The general form of a simple if statement is,

if(expression)

statement inside;

statement outside;

If the expression returns true, then the statement-inside will be executed,


otherwise statement-inside is skipped and only the statement-outside is executed.

Example:

#include <stdio.h>

void main( )

int x, y;

x = 15;

22
y = 13;

if (x > y )

printf("x is greater than y");

x is greater than y

if...else statement

The general form of a simple if...else statement is,

if(expression)

statement block1;

else

statement block2;

If the expression is true, the statement-block1 is executed, else statement-block1 is


skipped and statement-block2 is executed.

23
Example:

#include <stdio.h>

void main( )

int x, y;

x = 15;

y = 18;

if (x > y )

printf("x is greater than y");

else

printf("y is greater than x");

y is greater than x

24
Nested if....else statement

The general form of a nested if...else statement is,

if( expression )

if( expression1 )

statement block1;

else

statement block2;

else

statement block3;

if expression is false then statement-block3 will be executed, otherwise the


execution continues and enters inside the first if to perform the check for the
next if block, where if expression 1 is true the statement-block1 is executed
otherwise statement-block2 is executed.

25
Example:

#include <stdio.h>

void main( )

int a, b, c;

printf("Enter 3 numbers...");

scanf("%d%d%d",&a, &b, &c);

if(a > b)

if(a > c)

printf("a is the greatest");

else

printf("c is the greatest");

else

26
if(b > c)

printf("b is the greatest");

else

printf("c is the greatest");

else if ladder

The general form of else-if ladder is,

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

if(a%5 == 0 && a%8 == 0)

printf("Divisible by both 5 and 8");

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

1. In if statement, a single statement can be included without enclosing it into curly


braces { ... }

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");

In above example, hello will be printed.

Switch statement in C (Selection statement)


When you want to solve multiple option type problems, for example: Menu like
program, where one value is associated with each option and you need to choose
only one at a time, then, switch statement is used.

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;

Rules for using switch statement

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.

3. default case is executed when none of the mentioned case matches


the switch expression. The default case can be placed anywhere in
the switch case. Even if we don't include the default case, switch statement works.
4. Nesting of switch statements are allowed, which means you can
have switch statements inside another switch block. However,
nested switch statements should be avoided as it makes the program more
complex and less readable.

Example of switch statement

#include<stdio.h>

void main( )

int a, b, c, choice;

while(choice != 3)

/* Printing the available options */

printf("\n 1. Press 1 for addition");

printf("\n 2. Press 2 for subtraction");

33
printf("\n Enter your choice");

/* Taking users input */

scanf("%d", &choice);

switch(choice)

case 1:

printf("Enter 2 numbers");

scanf("%d%d", &a, &b);

c = a + b;

printf("%d", c);

break;

case 2:

printf("Enter 2 numbers");

scanf("%d%d", &a, &b);

c = a - b;

printf("%d", c);

break;

default:

printf("you have passed a wrong key");

printf("\n press any key to continue");

34
}

Difference between switch and if

 if statements can evaluate float conditions. switch statements cannot


evaluate floatconditions.
 if statement can evaluate relational operators. switch statement cannot evaluate
relational operators i.e they are not allowed in switch statement.

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.

 Variable initialization.(e.g int x = 0;)


 condition(e.g while(x <= 10))

35
 Variable increment or decrement ( x++ or x-- or x = x + 2 )

Syntax :

variable initialization;

while(condition)

statements;

variable increment or decrement;

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )

int x;

x = 1;

while(x <= 10)

printf("%d\t", x);

/* below statement means, do x = x+1, increment x by 1*/

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,

for(initialization; condition; increment/decrement)

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.

The for loop is executed as follows:

1. It first evaluates the initialization code.


2. Then it checks the condition expression.
3. If it is true, it executes the for-loop body.

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.

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )

int x;

for(x = 1; x <= 10; 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,

for(initialization; condition; increment/decrement)

for(initialization; condition; increment/decrement)

statement ;

Example: Program to print half Pyramid of numbers

#include<stdio.h>

void main( )

int i, j;

/* first for loop */

for(i = 1; i < 5; i++)

printf("\n");

39
/* second for loop inside the first */

for(j = i; j > 0; j--)

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)

Example: Program to print first 10 multiples of 5.

#include<stdio.h>

void main()

int a, i;

a = 5;

i = 1;

do

printf("%d\t", a*i);

i++;

while(i <= 10);

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

You might also like