0% found this document useful (0 votes)
3 views34 pages

Data Structures in C Programming

The document provides an introduction to programming in C, covering the basic structure of a C program, including its various sections and components. It explains C programming concepts such as tokens, data types, operators, and provides examples of syntax and functions. Additionally, it discusses the differences between assignment and equality operators, as well as shorthand notations and user-defined data types.

Uploaded by

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

Data Structures in C Programming

The document provides an introduction to programming in C, covering the basic structure of a C program, including its various sections and components. It explains C programming concepts such as tokens, data types, operators, and provides examples of syntax and functions. Additionally, it discusses the differences between assignment and equality operators, as well as shorthand notations and user-defined data types.

Uploaded by

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

DATA STRUCTURE USING C

MODULE 1
INTRODUCTION TO
PROGRAMMING

CO - Students will be able to describe the basic


concepts of C program with the help of simple
examples.
Prepared By Dr. EBIN PM , AP (CSE AIML) 1

BASIC STRUCTURE OF C PROGRAM


• The set of instructions that are provided to computer is known as a
program and the development of program is known as
programming.
• Programming is a problem-solving activity.
• C was evolved from ALGOL, BCPL (Basic Combined Programming
Language) and B by Dennis Ritchie.
• C is structured, high level, machine independent language
• C is a very powerful and widely used language. It is used in many
scientific programming situations.
• It forms (or is the basis for) the core of the modern languages Java
and C++. It allows you access to the bare bones of your computer.
Prepared By Dr. EBIN PM , AP (CSE AIML) 2

Prepared By Dr. EBIN PM, AP (CSE AIML) 1


DATA STRUCTURE USING C

STRUCTURE OF A C PROGRAM
DOCUMENTATION SECTION comments
LINKAGE SECTION #include files
DEFINITION SECTION #define
GLOBAL DECLARATION SECTION variable and functions

MAIN FUNCTION SECTION main ( ) function

Local Declaration Part


Executable Code Part

SUB PROGRAM SECTION function definition Section

Function 1 ( )
Function 2 ( )
……………
Function N ( )

Prepared By Dr. EBIN PM , AP (CSE AIML) 3

 Points to remember
• Every statement in C should end with a semicolon.
• In C everything is written in lower case. However upper case letters
used for symbolic names representing constants.
• #include is a pre-processor directive.
• Stdio.h is a header file, for standard input output functions. It
activate keyboard and monitor.
• Single line comment is represented using //
• Multiple line comment is represented using /*……………….*/
• Comment lines are not executable statements and therefore
anything between/*and*/ is ignored by the compiler.
Prepared By Dr. EBIN PM , AP (CSE AIML) 4

Prepared By Dr. EBIN PM, AP (CSE AIML) 2


DATA STRUCTURE USING C

• Execution begins from main ( )


• main has no arguments(or Parameters)
• Every program must have exactly one main function. C permits
different forms of main statements. They are
main ( )
int main ( )
void main ( )
main (void)
void main (void)
int main (void)

Prepared By Dr. EBIN PM , AP (CSE AIML) 5

C PROGRAM TOKENS
The smallest individual unit in a program is known as tokens. C has
the following tokens
1. Keywords: these are the words whose meaning has already been
explained to the C compiler. The keywords cannot be used as
variable names. The keywords are also known as “Reserved
words”. There are only 32 keywords in C. Examples are char,
double, void, if
2. Identifiers: These are fundamental building block of a program.
Identifiers refer to the names of variables; functions and arrays.
These are user-defined names and consist of a sequence of
letters and digits with the letter as a first character.
Prepared By Dr. EBIN PM , AP (CSE AIML) 6

Prepared By Dr. EBIN PM, AP (CSE AIML) 3


DATA STRUCTURE USING C

3. Constants (literals): These are data items that never change their
value during a program run. These are fixed values. The types of
constants are
a) Integer constant: These are whole numbers without any
fractional part. It must have at least one digit and must not
contain any decimal point. It can be either positive or negative.
Examples are 426,+200,-760
b) Character constant: A character constant is one character
enclosed in single quotes. Examples are ‘A’, ’5’ ,’=’ . A character
constant have corresponding ASCII (American Standard Code for
Information Interchange) values. For example ASCII value of ‘A’ is
65 and ASCII value of ‘a’ is 97.

Prepared By Dr. EBIN PM , AP (CSE AIML) 7

c) String constant: Multiple character constants are treated as


string constant. A string constant is a sequence of characters
surrounded by double quotes. Examples are “abcd”, ”seena”.
Each string constant is by default (automatically) added with a
special character ’\0’ which makes the end of a string. Thus the
size of a string is
Number of characters + null character (‘\0’)
• For example “abc” size is 4. Thus “abc” will be automatically
represented as “abc\0” in the memory.’\0’ is an end-of-string
marker
d) Floating constant: Floating constants are also called real
constants. These numbers have fractional part. These may be
written in one of the two forms called
Prepared By Dr. EBIN PM , AP (CSE AIML) 8

Prepared By Dr. EBIN PM, AP (CSE AIML) 4


DATA STRUCTURE USING C

Fractional form: A floating constant in fractional form must have


at least one digit before a decimal point and at least one digit after
the decimal point.
• It may also have either positive or negative. Examples are 17.8,-
13.867
Exponent form: A real constant in exponent form consist of two
parts. (a) Mantissa (b) Exponent.
• For example, 9.8 can be written as 0.98×101=0.98E01 where
mantissa part is 0.98 and exponent part is 1. E01 represent 101.
The exponent must be an integer. The examples are
152E05,1.52E07

Prepared By Dr. EBIN PM , AP (CSE AIML) 9

4. Punctuators :
[ ] Bracket (Arrays)
( ) Parentheses (Function call & Function parameters)
{ } Braces (Opening and closing of executable statements)
, Comma (Separator)
; Semicolon (Terminator)
: Colon (Labelled statement)
* Asterisk (Pointer declaration & Multiplication operator)
# Pound sign OR called Hash (Preprocessor directive)
= Equal to (Assignment operator)

Prepared By Dr. EBIN PM , AP (CSE AIML) 10

10

Prepared By Dr. EBIN PM, AP (CSE AIML) 5


DATA STRUCTURE USING C

5. Operators: There are two divisions of operators. (a) Unary


operators (b) Binary operators. Unary operators have one
operator to operate up on. They are
& Address operator
+ Unary plus
ˉ Unary minus
~ Bitwise complement
++ Increment
ˉ ˉ decrement
! Logical negation

Prepared By Dr. EBIN PM , AP (CSE AIML) 11

11

 Binary operators require two operands to operate up on. They


are
ARITHMETIC OPERATORS
+ Addition
- Subtraction
* Multiplication
/ Division
% remainder (modulo division)
SHIFT OPERATORS
<< Left shift
>> Right shift
Prepared By Dr. EBIN PM , AP (CSE AIML) 12

12

Prepared By Dr. EBIN PM, AP (CSE AIML) 6


DATA STRUCTURE USING C

BITWISE OPERATORS
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
LOGICAL OPERATORS
&& Logical AND
| | Logical OR
! Logical NOT
ASSIGNMENT OPERATORS
= Assignment
*= Assign product
/= Assign quotient
+= Assign sum
Prepared By Dr. EBIN PM , AP (CSE AIML) 13

13

RELATIONAL OPERATORS
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
COMPONENT SELECTION
. Direct component selector
→ Indirect component selector

Prepared By Dr. EBIN PM , AP (CSE AIML) 14

14

Prepared By Dr. EBIN PM, AP (CSE AIML) 7


DATA STRUCTURE USING C

 CONDITIONAL OPERATOR(TERNARY OPERATOR)


? True form : false form
Consider the example
int a=10;
int b=15;
int x;
x= (a>b)? a: b;
In this example x will be assigned the value of b. This can be achieved
using the if….else statement as follows
if (a>b)
x=a;
else
x=b;
Prepared By Dr. EBIN PM , AP (CSE AIML) 15

15

 INCREMENT AND DECREMENT OPERATORS


Increment ++
Decrement - -
a= a+1 is same as ++a or a++
a= a-1 is same as - - a or a- -
• The operator ++ adds 1 to its operand and - - subtracts one. The
prefix version comes before the operand (as in ++a or - -a) and the
postfix version comes after the operand (as in a++ or a- -).
• The prefix increment or decrement operator follows Change- Then
– Use rule.
• Postfix increment or decrement operator follows Use- Then-
Change rule.

Prepared By Dr. EBIN PM , AP (CSE AIML) 16

16

Prepared By Dr. EBIN PM, AP (CSE AIML) 8


DATA STRUCTURE USING C

/* A program to add two numbers and print the result*/


#include <stdio.h> /*header files*/
int main ( ) /* main function*/
{
int x, y, sum; /* variable declaration*/
printf (“Enter two integer numbers”); /*printing statement*/
scanf (“%d%d”,&x,&y); /* scanning the input*/
sum =x+y; /* calculation*/
printf (“The sum is%d”,sum); /* printing output*/
return 0;
}

Prepared By Dr. EBIN PM , AP (CSE AIML) 17

17

DIFFERENCE BETWEEN = AND = =


• The expression a= = 5 is test or check whether a is equal to 5
• The expression a=5 is assign 5 to the variable a
#include <stdio.h>
int main ( )
{
int p=8; /*variable initialization*/
if (p = = 8) /* check whether p is equal to 8*/
printf (“Both are same”);
return 0;
}
Output
Both are same
Prepared By Dr. EBIN PM , AP (CSE AIML) 18

18

Prepared By Dr. EBIN PM, AP (CSE AIML) 9


DATA STRUCTURE USING C

SHORT HANDS (COMPOUND ASSIGNMENT)


a=a+10; can be written as a+=10;
Syntax
Variable Operator = Expression;

Prepared By Dr. EBIN PM , AP (CSE AIML) 19

19

DATA TYPES
Data type is a classification identifying one of various types of data. There are
three classes of data types.
• Fundamental (primary) Data types
• Derived Data types
• User defined data types
Fundamental (primary) data types
1. int : for integers (4 byte memory space allocates in memory)
2. char : for characters(1 byte memory space allocates in memory)
3. float : for floating point numbers(4 byte memory space allocates in memory)
4. double : for double precision floating point numbers(8 byte memory space
allocates in memory)
5. void: for empty set of values and non-returning functions. The void type has no
value.
Prepared By Dr. EBIN PM , AP (CSE AIML) 20

20

Prepared By Dr. EBIN PM, AP (CSE AIML) 10


DATA STRUCTURE USING C

Derived data types


Derived data types are constructed from fundamental data types. They are
1. Arrays: An array is a collection of variables of the same type that are
referenced by a common name.
2. Functions: A function is a named part of a program that can be invoked
from other part of the program.
3. Pointer: A pointer is a variable that holds the memory address. This
address is usually the location of another variable in memory.
4. Constant: The keyword const can be added to the declaration of an object
to make that object a constant rather than a variable. Thus, the variable of
the named constant cannot be altered during the program run.
Syntax
const type name = value;
Eg: const int a=10;
Prepared By Dr. EBIN PM , AP (CSE AIML) 21

21

User defined data types


1. typedef: It allows users to define an identifier that would
represent an existing data type.
Syntax
typedef type identifier;
Here, type refers to an existing data type and identifier refers to the
new name given to the data type.
Eg: typedef int units;
typedef float marks;
Here, units symbolize int and marks symbolizes float. They can be
later used to declare variables as follows
Prepared By Dr. EBIN PM , AP (CSE AIML) 22

22

Prepared By Dr. EBIN PM, AP (CSE AIML) 11


DATA STRUCTURE USING C

units batch1, batch2;


marks name1,name2;
• batch1 and batch2 are declared as int variables and name1 and
name2 are declared as floating point variables.
• Advantage of typedef is that we can create meaningful data type
names for increasing the readability of the program.
2. Structure: A structure is a collection of variables of different data
types referenced under one name.
3. Enumeration: Enumerated data type (also called enumeration or
enum) provides a way for attaching names to numbers there by
increasing comprehensibility of the code. It has the following
form.
Prepared By Dr. EBIN PM , AP (CSE AIML) 23

23

enum identifier {value1,value2,…….,value n};


• The identifier is a user defined enumerated data type which can be
used to declare variables that can have one of the values enclosed
with in the braces (known as enumeration constant).
Eg: enum week_day {Monday, Tuesday...Sunday}; // an enumerated
data type week_day has been defined
week_day day1, day2; // variables created of type week_day.
day1=Wednesday; //correct,day1 can have any of the above
given 7 values.
day2=7; // incorrect, no other value can be assigned

Prepared By Dr. EBIN PM , AP (CSE AIML) 24

24

Prepared By Dr. EBIN PM, AP (CSE AIML) 12


DATA STRUCTURE USING C

• Enumerated means all the values are listed. The enum specifier
automatically enumerates a list of words by assigning them values
0, 1, 2, 3, and so on.
• The compiler automatically assigns integer digits beginning with 0
to all the enumeration constants. That is the enumeration constant
Monday is assigned 0, Tuesday is assigned 1 and so on.
• We can give values explicitly (changing default original values) by
the following way
enum day {Monday=1, Tuesday, Wednesday=6, Thursday, Friday….};
Now, Monday=1, Tuesday=2, Wednesday=6, Thursday=7, Friday=8
etc.

Prepared By Dr. EBIN PM , AP (CSE AIML) 25

25

4. Union:
• Structure and union are same but different in memory allocation.
• A union can be declared using the keyword is union.
• A union is a memory location that is shared by two or more
different variables, generally of different types at different times.
• Defining a union is similar to defining a structure.

Prepared By Dr. EBIN PM , AP (CSE AIML) 26

26

Prepared By Dr. EBIN PM, AP (CSE AIML) 13


DATA STRUCTURE USING C

VARIABLES
A variable is a data name that may be used to store a data value.
A variable may take different values at different times during
execution.
Each variable has a specific storage location in memory where its
value is stored. The variables are called symbolic variables because
these are named.
There are two values associated with a symbolic variable.
• Data value: stored at some location in memory. This is sometimes
referred to as a variable’s r- value.
• Location value: This is the address in memory at which its data
value is stored. This is sometimes referred to as variable’s l-value.
Prepared By Dr. EBIN PM , AP (CSE AIML) 27

27

• r-value of A=10 and l-value of A=1052


• r-value of c=25 and l-value of c=1055
Whenever we use the assignment operator, the expression to the
left of an assignment operator must be an l-value. That is, it must
provide an accessible memory address where the data can be
written to.
Prepared By Dr. EBIN PM , AP (CSE AIML) 28

28

Prepared By Dr. EBIN PM, AP (CSE AIML) 14


DATA STRUCTURE USING C

Variable Declaration
A declaration associates a group of variables with a specific data
type. Declaration of variables must be done before they are used in
the program.
Syntax
Data_ type variable_ name;
Eg: int a;
float a, b, c;
char name [10]; // Character array declaration

Prepared By Dr. EBIN PM , AP (CSE AIML) 29

29

Variable Initialization
• The process of giving initial values to variables is called
initialization.
Eg: int x=10;
float n=22.889;
char answer=’y’;
Expression
• An expression represents a single data item, such as number or a
character. Expression can also represent logical conditions
Eg: x+y
y=z
x=y+z
Prepared By Dr. EBIN PM , AP (CSE AIML) 30

30

Prepared By Dr. EBIN PM, AP (CSE AIML) 15


DATA STRUCTURE USING C

• An expression statement consists of an expression followed by a


semicolon. For example, following two expression statements
cause the value of the expression on the right of the equal sign to
be assigned to the variable on the left.
x=5;
x=y+z;
• A compound statement consists of several individual statements
enclosed within a pair of braces ({and}).

Prepared By Dr. EBIN PM , AP (CSE AIML) 31

31

ESCAPE SEQUENCES (BACK SLASH) CHARACTERS


In character constants, their exist nongraphic characters. Non
graphics characters cannot be typed directly from keyboard. These
are represented using escape sequences. An escape sequence is
represented by a back slash (\).
Esc. Seq. Purpose Esc. Seq. Purpose

\n New line \t Horizontal Tab


\b Backspace \r Carriage return
\f Form feed \a Alert
\’ Single quote \” Double quote
\\ Backslash \? Question mark

Prepared By Dr. EBIN PM , AP (CSE AIML) 32

32

Prepared By Dr. EBIN PM, AP (CSE AIML) 16


DATA STRUCTURE USING C

Eg: C program to illustrate \n escape sequence


#include <stdio.h>
int main ()
{
//we are using \n, which
// is a new line character.
printf("Hello\n");
printf("C programming");
return 0;
}
Output
Hello
C programming
Prepared By Dr. EBIN PM , AP (CSE AIML) 33

33

TYPE CASTING (TYPE CONVERSION)


The process of converting one predefined type in to another is called
type casting. It has two forms.
1. Implicit Type casting: It performed by the compiler. It is used in mixed
mode operations.
• RULES
• An arithmetic operation between an integer and integer always yields
an integer result.
• An operation between a real (float) and real operation is performed.
Hence the result is real.

Prepared By Dr. EBIN PM , AP (CSE AIML) 34

34

Prepared By Dr. EBIN PM, AP (CSE AIML) 17


DATA STRUCTURE USING C

• An operation between an integer and real always yields a real


result.
• In this operation the integer is first promoted to a real and then the
operation is performed. Hence the result is real.
2. Explicit Type casting: It is user defined
Syntax
(type) expression;
Eg: b= (float) (x+y/2);

Prepared By Dr. EBIN PM , AP (CSE AIML) 35

35

#include <stdio.h>
int main ( )
{
int x, y,
float sum;
printf (“enter two integer numbers”);
scanf (“%d%d”,&x,&y);
sum =(float) x+y;
printf (“The sum is %f”,sum);
return 0;
}

Prepared By Dr. EBIN PM , AP (CSE AIML) 36

36

Prepared By Dr. EBIN PM, AP (CSE AIML) 18


DATA STRUCTURE USING C

• Consider the following assignment statements.


int k =4.8;
float m = 50;
• Here in the first assignment statement though the expression’s
value is a float (4.8) it cannot be stored in k since it is an int. In
such a case the float is demoted to an int and then its value is
stored.
• Hence what gets stored in k is 4. Exactly opposite happens in the
next statement.
• Here, 50 is promoted to 50.000000 and then stored in m, since m
being a float variable cannot hold anything except a float value.

Prepared By Dr. EBIN PM , AP (CSE AIML) 37

37

• Consider the following program fragment.


float x, y, z ;
int p ;
p = x * y * z / 67 + 89 / 8 - 2 * 4.8;
• Here, in the assignment statement some operands are ints
whereas others are floats.
• As we know, during evaluation of the expression the ints would be
promoted to floats and the result of the expression would be a
float.
• But when this float value is assigned to p, it is again demoted to an
int and then stored in p.

Prepared By Dr. EBIN PM , AP (CSE AIML) 38

38

Prepared By Dr. EBIN PM, AP (CSE AIML) 19


DATA STRUCTURE USING C

PREPROCESSOR DIRECTIVES
The pre-processor is a program that processes the source code
before it passes through the compiler. It operates under the control
of directives.
Before the source code passes through the compiler, it is examined
by the pre-processor for any pre-processor directives.
If there are any, appropriate actions are taken and then the source
program is handed over to the compiler. The three categories of
directives are
1. Macro substitution directives (#define)
2. File inclusion directives (#include)
3. Compiler control directives (#if, #else, #endif)
Prepared By Dr. EBIN PM , AP (CSE AIML) 39

39

• #define: defines a macro substitution.


• #undef: undefines a macro
• #include: Specifies the files to be included.
• #if: Test a compile-time condition
Syntax
#include<file name>
Eg: #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<file name> : The file is searched only in the standard directory
#include “file name” : The file searching is made first in the current
directory and then in the standard directories.
Prepared By Dr. EBIN PM , AP (CSE AIML) 40

40

Prepared By Dr. EBIN PM, AP (CSE AIML) 20


DATA STRUCTURE USING C

MACRO SUBSTITUTION
We can define a symbolic constant using #define. It has the
following form
Syntax
#define symbolic_ name value_ of_ constant
Eg: #define NUMVAL 100
 #define statement must not end with semi colon. Symbolic names
are written in CAPITALS.

Prepared By Dr. EBIN PM , AP (CSE AIML) 41

41

Eg: #include<stdio.h>
#define VALUE 25
int main( )
{
int i ;
for ( i = 1 ; i <= VALUE ; i++ )
printf ( "\n%d", i ) ;
}
In this program, instead of writing 25 in the for loop we are writing
it in the form of VALUE, which has already been defined before
main ( ) through the statement, #define VALUE 25
Prepared By Dr. EBIN PM , AP (CSE AIML) 42

42

Prepared By Dr. EBIN PM, AP (CSE AIML) 21


DATA STRUCTURE USING C

A #define directive could be used even to replace a condition, as shown


below.
# include<stdio.h>
#define AND &&
#define NEW ( a > 25 AND a < 50 )
int main( )
{
int a = 30 ;
if ( NEW )
printf ( "Am your friend" ) ;
else
printf ( "Am not your friend" ) ;
}

Prepared By Dr. EBIN PM , AP (CSE AIML) 43

43

VARIOUS INPUT/OUTPUT FUNCTIONS


1. getchar ( )
• getchar () function reads a single character from standard input. It takes
no parameters and its returned value is the input character. It has the
following form
variable name=getchar( );
Eg: char c;
printf(“Enter a character”);
c=getchar ( );
• The second line causes a single character to be entered from the
standard input device and then assigned to c. The variable name has
been declared as ‘char’ type.
Prepared By Dr. EBIN PM , AP (CSE AIML) 44

44

Prepared By Dr. EBIN PM, AP (CSE AIML) 22


DATA STRUCTURE USING C

2. putchar( )
• It displays a single character on the screen. This function takes one
argument, which is the character to be sent. It also returns this
character as its result. The general form is
putchar ( variable-name);
Eg: char ans=’y’
putchar (ans);
3. gets( ) : receives a string from the keyboard.

Prepared By Dr. EBIN PM , AP (CSE AIML) 45

45

5. puts ( ) : Outputs a string to the screen


Eg: char vehicle [40];
Printf(“Enter your vehicle name”);
gets (vehicle);
puts (vehicle);
• These lines use the gets and puts to transfer the line of text into
and out of the computer.
• When this program is executed, it will give the same result as that
with scanf and printf function for input and output of given
variable or array.

Prepared By Dr. EBIN PM , AP (CSE AIML) 46

46

Prepared By Dr. EBIN PM, AP (CSE AIML) 23


DATA STRUCTURE USING C

6. clrscr ( ) : It is a clear screen function.

7. printf ( ) : For outputting the result we use printf( ) function.


Syntax
printf (“formatted string”, variable);
Eg: printf (“%d”, a);
printf (“WELCOME MY FRIEND”);

Prepared By Dr. EBIN PM , AP (CSE AIML) 47

47

Formatted strings are


1. %d integers
2. %f float
3. %c character
4. %o octal number
5. %s string
6. %e exponential notation
7. %u unsigned integer
8. %x hexadecimal integer
9. % i signed decimal integer
10. %p display a pointer
11. %% prints a percent sign (%)
Prepared By Dr. EBIN PM , AP (CSE AIML) 48

48

Prepared By Dr. EBIN PM, AP (CSE AIML) 24


DATA STRUCTURE USING C

8. scanf ( ) : It can read data from keyboard. scanf ( ) means “scan


formatted” .
Syntax
scanf (“formatted string”, addressed variable);
Eg: scanf (“%d”, &a);
scanf (“%d%f”,&num1,&num2);

Prepared By Dr. EBIN PM , AP (CSE AIML) 49

49

CONTROL FLOW STATEMENTS


C program is a set of statements which are normally executed
sequentially in the order.
We can change the order of execution of statements.
For this purpose, we use branching instructions (Decision-making
statements).
Since these statements control the flow of execution, they also
known as Branching instructions.

1. SIMPLE IF STATEMENT

Prepared By Dr. EBIN PM , AP (CSE AIML) 50

50

Prepared By Dr. EBIN PM, AP (CSE AIML) 25


DATA STRUCTURE USING C

Syntax

• If the test expression is true, the statement block will be executed;


otherwise the statement block will be skipped and the execution
will jump to the statement-x.
• If multiple statements are executed, then they must be placed with
in a pair of braces.

Prepared By Dr. EBIN PM , AP (CSE AIML) 51

51

Eg: /* check a citizen is eligible for voting */


#include<stdio.h>
void main() OUTPUT
{
int age; Enter the age:
printf (“Enter the age : ”); 21
scanf (“%d”,&age);
Eligible for voting…
if(age >= 18)
printf(“Eligible for voting…”);
return 0;
}

Prepared By Dr. EBIN PM , AP (CSE AIML) 52

52

Prepared By Dr. EBIN PM, AP (CSE AIML) 26


DATA STRUCTURE USING C

2. IF…..ELSE STATEMENT
• Here, either true block or false block will be executed, not both. In both
cases control is transferred to the statement-x.
Syntax
if (test expression)
{
True statements;
}
else
{
False statements;
}
Statement-x;
Prepared By Dr. EBIN PM , AP (CSE AIML) 53

53

Eg: /* print a number is even or odd */


#include<stdio.h>
int main ( ) OUTPUT
{
int number; Enter a number:
printf (“Enter a number : “); 12
scanf (“%d”, &number); 12 is even number.
if ((number %2) = = 0)
printf (“%d is even number.”, number);
else
printf (“%d is odd number.”,number);
return 0;
}
Prepared By Dr. EBIN PM , AP (CSE AIML) 54

54

Prepared By Dr. EBIN PM, AP (CSE AIML) 27


DATA STRUCTURE USING C

5. SWITCH STATEMENT
• The switch statement provides a way of choosing between a set of
alternatives, based on the value of an expression. It allows us to
make a decision from the number of choices.

Syntax

Prepared By Dr. EBIN PM , AP (CSE AIML) 55

55

working of switch statement


• First, the expression is evaluated.
• It checks for matching one by one case statements.
• When a match is found, program executes the statement.
• If no match is found, default statement is executed.
• break statement causes an exit from the switch statement.
• It is possible to nest the switch statement.
• The case can be arranged in any order.
• We can use char values in case and switch.

Prepared By Dr. EBIN PM , AP (CSE AIML) 56

56

Prepared By Dr. EBIN PM, AP (CSE AIML) 28


DATA STRUCTURE USING C

Example

Prepared By Dr. EBIN PM , AP (CSE AIML) 57

57

You are also allowed to use char values in case and switch as shown in the
following program:

Prepared By Dr. EBIN PM , AP (CSE AIML) 58

58

Prepared By Dr. EBIN PM, AP (CSE AIML) 29


DATA STRUCTURE USING C

DECISION MAKING & LOOPING


This involves repeating some portion of the program either a
specified number of times or until a particular condition is being
satisfied.
The three types of loops available in C are for, while, and do-
while. A looping process, in general, would include the following
four steps.
• Setting and initialization of a condition variable.
• Execution of the statements in the loop.
• Test for a specified value of the condition variable for execution of
the loop.
• Incrementing or updating the condition variable.
Prepared By Dr. EBIN PM , AP (CSE AIML) 59

59

1. WHILE LOOP
• It is an entry control loop. In a while loop, loop control variable
should be initialized before the loop begins. The loop variable
should be updated inside the body of the while
Syntax
initialize loop counter;
while (test loop counter using a condition)
{
do this;
and this;
increment loop counter;
}
Prepared By Dr. EBIN PM , AP (CSE AIML) 60

60

Prepared By Dr. EBIN PM, AP (CSE AIML) 30


DATA STRUCTURE USING C

Eg: #include <stdio.h>


OUTPUT
void main( ) 1
{ 2
int s=1; 3
while (s<=10) 4
{ 5
printf (“\n%d”,s); 6
s++; 7
8
}
9
return 0; 10
}
Prepared By Dr. EBIN PM , AP (CSE AIML) 61

61

• Instead of incrementing we can even decrement a loop counter


void main( )
{ OUTPUT
int k = 4 ; Decrement counter
while ( k >= 1 ) Decrement counter
{ Decrement counter
printf ( "decrement counter”) ; Decrement counter
k = k- 1 ;
}
}

Prepared By Dr. EBIN PM , AP (CSE AIML) 62

62

Prepared By Dr. EBIN PM, AP (CSE AIML) 31


DATA STRUCTURE USING C

2. FOR LOOP
• It is an entry control loop.
Syntax
for (initialization ; test-condition ; increment)
{ body of the loop
}
• Initialization of the control variable is done first. The variable ‘i’ is
known as loop control variable.
• Next check the test condition. If it is true, the body of the loop is
executed. After this, the control variable is incremented

Prepared By Dr. EBIN PM , AP (CSE AIML) 63

63

OUTPUT
0 1 2 3 4 5 6 7

Eg: for (i=0; i< 8; i++)


{
printf (“%d”,i);
}
• Testing and incrementation of loop counter is done in the for
statement itself.
• Instead of i++, the statements i = i + 1 or i += 1 can also be used.

Prepared By Dr. EBIN PM , AP (CSE AIML) 64

64

Prepared By Dr. EBIN PM, AP (CSE AIML) 32


DATA STRUCTURE USING C

3. DO –WHILE LOOP
• It is an exit control loop. That is, it evaluates its test expression at
the bottom of the loop after executing its loop body statement.
• do -while loop execute at least once even when the test expression
evaluates to false initially
Syntax
do
{
this;
and this;
and this;
} while (this condition is true);

Prepared By Dr. EBIN PM , AP (CSE AIML) 65

65

Eg: int main( )


{
int p =3; OUTPUT
do Am in Do-While
{
printf(“Am in Do-While”);
} while ( p < 2 ) ;
}
• In this program the printf ( ) would be executed once, since first
the body of the loop is executed and then the condition is tested.
• There are some occasions when we want to execute a loop at least
once no matter what.
Prepared By Dr. EBIN PM , AP (CSE AIML) 66

66

Prepared By Dr. EBIN PM, AP (CSE AIML) 33


DATA STRUCTURE USING C

NESTING OF LOOPS
• The way if statements can be nested, similarly while and for can
also be nested. To understand how nested loops work; look at the
program given below:
• OUTPUT

Prepared By Dr. EBIN PM , AP (CSE AIML) 67

67

Prepared By Dr. EBIN PM, AP (CSE AIML) 34

You might also like