191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
1
EASWARI ENGINEERING COLLEGE
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C
UNIT I : C PROGRAMMING BASICS AND ADVANCED FEATURES 9
Conditional statements – Control statements – Arrays - Pointers - Variation in pointer declarations –
Functions - Function Pointers –-Structures - File handling concepts – File read – write – binary and stdio
- File Manipulations
Problem Formulation and Solving
To develop the solution for the given problem, the following programming techniques are used.
Problem solving techniques
i) Algorithm
It is a set of logical procedure steps to solve the problem.
ii) Flow Charts
It is a diagrammatic representation of the sequence of operation for a given problem.
iii) Pseudo codes
These are the instructions written in ordinary English using mathematical and logical
symbols to display the program logic.
iv) Decision Tables
A decision table consists of many independent conditions with several actions, written in
table format to solve the given problem.
Introduction to ‘ C’ programming
C is a programming language developed at AT & T laboratories of USA in 1972 by Dennis Ritchie in
1970. It was initially implemented on the system that used UNIX operating system. C is a midlevel
computer language. C is a nice blend of high level languages and low level assembly language.
Important Features of C Language
i. C is a system programming language which provides flexibility for writing compilers, operating
systems, etc.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
2
ii. It can also be used for writing the application programs for scientific, engineering and business
applications.
iii. C is famous for its portability, meaning that program written in C for one computer can be easily
loaded to another computer with little or no changes.
iv. C supports variety of data types like integers, float point numbers, characters, etc.
v. C is a procedure oriented language which is most suited for structured programming practice.
vi. It provides a rich set of built in functions.
Program Structure in C
To accomplish the given task programs are written and it is executed in Turbo C/C++ compiler. The
structure of the program is given below.
i. The Documentation Section: It consists of a set of comment lines giving the name of the program, the
author and other details which the programmer would like to use later. The comments are enclosed in a
C program using /* and */ .
ii. The Preprocessor directive or Link section: It provides instruction to the compiler to link some
functions or do some processing prior to the execution of the program. It is also used to define symbolic
constants of the program.
o Header file used by the example is a standard input/output file (stdio.h).
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
3
o programs must contain an #include line for each header file
o There are two punctuation forms for head file.
1. #include <stdio.h>
2. #include “stdio.h”
iii. Global Declaration Section : There are some variables that are used in more than one function. Such
variables are called global variables and are declared in this section that is outside of all other functions.
iv. The main() function section : Every C program must have one main() function. This section contains
two parts, declaration part and executable part. The declaration part declares all the variables used in the
executable part. There is at least one statement in the executable part. These two parts must appear
between the opening and closing braces. The program execution begins at the opening brace and ends
at the closing brace. The closing brace of the main function is the logical end of the program. All
statements in the declaration part and executable parts must end with a semicolon.
v. Sub program Section : It contains all the user defined functions that are called in the main() function.
User defined functions are generally placed immediately after the main function, although they may
appear in any order.
vi. All sections except the main() function may be absent when they are not required in any C program.
vii. Note that each of these topics are explained in detail in the following chapters of the book.
Compilation and Linking Process
Executing a C program involves a series of following steps.
i. Creating a program
ii. Compiling the program
iii. Linking the program with functions that are needed from the C library.
iv. Executing the program
It is represented in the below flowchart.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
4
Points about C Program
1. Every C program requires a main() function. Use of more than one main() is illegal. The place of
main() is where the program execution begins.
2. The Execution of the function begins at the opening brace and ends at the closing brace.
3. C programs are written in lowercase letters. However uppercase letters may be used for symbolic
names and constants.
4. All the words in a program line must be separated from each other by at least one space or a tab, or a
punctuation mark.
5. Every statement must end with a semicolon.
6. All variables must be declared for their type before they are used in the program.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
5
7. Compiler directives such as define and include are special instructions to the compiler, so they do not
end with a semicolon.
8. When braces are used in the program make sure that the opening
brace has corresponding ending brace.
9. C is a free form language and therefore proper form of indentation of various sections would improve
the legibility of the program.
C character set
Every language has its own character set. The character set of the C language consists of basic symbols
of the language. A character indicates any English alphabet, digit or special symbol including arithmetic
operators. The C language character set includes
1. Letter, Uppercase A ….. Z, Lower case a….z
2. Digits, Decimal digits 0….9.
3. Special Characters
, such as comma, period.
semicolon;
colon:
question mark?,
apostrophe‘
quotation mark “
Exclamation mark !
vertical bar |
slash /
backslash 
tilde ~
underscore _
dollar $
percent %
hash #
ampersand &
caret ^
asterisk *
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
6
minus –
plus +
<, >, (, ), [,], {, }
4. White spaces such as blank space, horizontal tab, carriage return, new line and form feed.
Identifiers and Keywords
Variables
A variable is an identifier that may be used to store data value. A value or a quantity which may vary
during the program execution can be called as a variable. Each variable has a specific memory location
in memory unit, where numerical values or characters can be stored. A variable is represented by a
symbolic name is also called as identifier.
Ex : sum = a+b. In this equation sum, a and b are the identifiers or variable names representing the
numbers stored in the memory locations.
Rules to be followed for constructing the Variable names(identifiers)
1. They must begin with a letter and underscore is considered as a
letter.
2. It must consist of single letter or sequence of letters, digits or
underscore character.
3. Uppercase and lowercase are significant. For ex: Sum, SUM and
sum are three distinct variables.
4. Keywords are not allowed in variable names.
5. Special characters except the underscore are not allowed.
6. White space is also not allowed.
Variable Declarations
Syntax :
Data type ‘variable’
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
7
For example:
int a;
float c;
char name;
int sam;
double count;
Assigning Values to Variables
Values can be assigned to variables using assignment operator “=”.
Syntax:
Variable name = value;
For Example: :a = 10; int lvalue = 0;
Identifiers are the names given by user to various program elements such as variables, functions and
arrays. The rules for identifiers are given below.
i. Letters, digits and underscore can be used.
ii. Must not start with a digit.
iii. Avoid using underscore at the start of identifier
iv. Identifier cannot be same as reserved word (Key Word) or C library
function names.
v. Identifiers are Case sensitive. For example india is different from
India.
Examples of Valid and Invalid Identifier are given in
Valid Identifiers:
1) X1x
2) Count_2
3) Num1
Invalid Identifiers:
I) 5thstandard : first character must be a letter
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
8
II) “Sam” : illegal character (“ ”)
III) Emp-no : illegal character( - )
IV) Reg no : illegal character (blank space)
C Keywords
Key words or Reserve words of the C language are the words whose meaning is already defined
and explained to the C language compiler. Therefore Reserve words cannot be used as identifiers or
variable names. They should only be used to carry the pre-defined meaning. For example int is a reserve
word. It indicates the data type of the variable as integer. Therefore it is reserved to carry the specific
meaning. Any attempt to use it other than the intended purpose will generate a compile time error. C
language has 32 keywords. Following are some of them
Some compilers may also include some or all of the following keywords.
Constants
There are four basic types of constants in C. They are integer constants, floating-point constants,
character constants and string constants. Integer
and floating point constants represent numbers. They are also called numeric- type constants.
Integer constants
An integer constant is an integer valued number. It consists of sequence of digits.
Integer constants are divided into three different number systems.
�decimal constants (base 10)
�Octal constants (base8)
�hexadecimal constants (base 16).
All the integer constants have to follow the set of rules given below.
(i)Constant must have at least one digit.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
9
(ii) Must not have decimal point.
(iii) Constant can be preceded by minus (-) sign, to indicate negative
constants.
(iv) Positive integer constants can be preceded by either positive sign
or no sign.
(v) Commas and blank spaces can’t be included with in the constant.
(vi) The value of constant must not exceed specified minimum and
maximum bound.
Generally for 16bit computer, the integer constant range is -32768 to 32767. For 32 bit computer the
range is much larger.
Now let us consider each type of integer constants individually.
Decimal Integer Constants
A decimal integer constant consists of any combination of digits taken from the set 0 to 9. The first digit
must be other than 0.
Valid decimal integer constants:
0 1 743 32767 8888
Invalid decimal integer constants
�080 Fi rst digit cannot be zero
�50.3 Illegal character ( . )
�12,542 Illegal character ( , )
�25 35 60 Illegal character ( Blank Space )
Octal Integer Constants
An octal integer constant consists of combination of digits taken from the set 0 through 7. However the
first digit must be 0, in order to identify the constant as an octal number.
Valid octal integer constants
00 06 0753 0663
Invalid octal integer constants
�543 Does not begin with zero
�07865 Illegal character ( 8 )
�06, 593 Illegal character ( , )
�06.512 Illegal character ( . )
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
10
Hexadecimal Integer Constants
A hexadecimal integer is identified by ox or OX. Hexadecimal integer constant consists of digits taken
from the set of 0 to 9 and letters taken from the set from from A to F (either upper or lower case). The
letter a to f or A to F represent the decimal values from 10 to 15 respectively i.e.,
a=10, b=11, c=12, d=13, e=14 and f=15
Valid hexadecimal integer constants:
0x0 0x1a 0x1BEC 0x7FFF
Invalid hexadecimal integer constants
�0x16.8b Illegal character ( . )
�563c Does not begin with 0 or 0x
�0x7bcg Illegal character ( g )
�0x12.53 Illegal character ( . )
Floating Point Constants
These constants are also called as ‘real constants’. The real constant can be written in two forms
namely factorial form and exponential form. If the value of the constant is either too small or too large
the exponential form is used.
Example:
The number 1.5 x 10 -3 can be written as 1.5 E -3 or 1.5 e -3. This is equivalent to 0.15e-2 or 15e-4.
etc.,
In the exponential form the part of the constant before ‘e’ is called exponent.
Example: 3.5 e + 5
3.5 - Mantissa part
+5 - Exponent part
The rules for constructing real constants are as follows.
(i) Must have at least one digit
(ii) Must have decimal point
(iii) Can be either positive or negative
(iv) Default sign is positive
(v) No comma’s or blanks are allowed with in a constant
(vi) The range of real constant expressed in exponential form is
3.4 e+ 38 to 3.4 e -38
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
11
Valid Real Constants
Some examples of valid real constants are given below.
0.01, 1.5, 825.053, 12E8, 12e8, 12e+8,12e-8, 0.65E-3
Invalid real constants
�1,000.0 illegal character ( . ) 53e10.3 exponent must be integer cot can’t contain a
decimal point.
�13 E 15 illegal character (blank space) in exponent part.
Character Constants
A character constant is a single alphabet a single digit or a single special symbol enclosed in apostrophes.
Some character constants and their corresponding ASCII values.
Constant Value
‘A’ 65
‘b’ 98
‘3’ 51
‘ ’ (blank space) 32
String Constants
String constants consist of any number of consecutive characters enclosed in (double) quotation marks.
Some example string constants
“green” “Rs95.50” “Hi n How are n you” “ ”(empty string)
The string “Hi n How are n You” is printed as
Hi
How are
You ?
Basic Data Types
C supports five fundamental data types: Character, Integer, Floating-Point, Double floating-
Point, and valueless. These are denoted as char, int, float, double, void, respectively, ’void’ is typically
used to declare as function as retuning null value. This issue is discussed in subsequent chapters. The
following table given details about fundamental data types.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
12
Classification of Datatypes
Basic Data Types
Modifiers to Basic Data Types
Modifiers are used to alter the meaning of basic data types to fit various needs. Except the type void, all
others data type can have various modifiers preceding them
List of modifiers used in C are:
i) Signed
ii) Unsigned
iii) Long
iv) Short
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
13
Modifiers and their memory requirements
Operators in C
C has a large number of built in operators.
An operator is a symbol which acts on operands to produce certain result as output. The data items on
which operators act upon are called ‘operands’
For example
expression : a+b;
In the above expression + is an operator, a and b are operands.
The operators are fundamental to any mathematical computations.
1. Based on the number of operands the operator acts upon, Operators can be classified as follows:
a. Unary operators: acts on a single operand. For example: unary minus(-5, -20, etc),
address of operator (&a)
b. Binary operators: acts on two operands. Ex: +, -, %, /, *, etc
c. Ternary operator: acts on three operands.
The symbol ?: is called ternary operator in C language.
Usage: big= a>b?a:b; i.e if a>b, then big=a else big=b.
2. Based on the functions, operators can be classified as given below
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
14
Arithmetic Operators
Arithmetic operators are used to perform numerical operators in C.
They are divided into two classes namely, Unary and Binary arithmetic operators.
Unary operators:
Operators Actions
- Unary minus
++ Increment
-- Decrement
Binary operators:
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Modules
Unary Minus ( - )
This symbol is used to indicate the negative sign of the value.
Example
a = -10;
b = -a;
Here the value -10 is assigned to a and the value-a to b.
Increment and decrement operator
The increment operator ( ++ ) adds 1 to its operand and decrement operator ( -- ) subtracts one
from its operand
Example
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
15
Y = y + 1 Is written as Y = y ++
These are two types of increment and decrement operators.
They are
a. Prefix increment (++ i)
In the prefix increment, first increment and then do operation .
b. Postfix increment (i ++)
In postfix increment, first do the operation and then increment.
c. Postfix decrement (--i)
In prefix decrement first decrement and then do operation.
d. Postfix decrement (i --)
In postfix decrement, first do the operation and then decrement.
Let the integer variable ‘ i ’ is variable one.
Ex. int i= 1;
Print f (“ i = %d n”, i);
Print f (“ i = %d n”, ++i); //prefix increment
Print f (“ i = %d /n”, i);
Output
i = 1
i = 2
i = 3
Example Program for Arithmetic operations using switch case.
# include <stdio.h>
# include <conio.h>
void main()
{
int a,b;
char ch;
clrscr();
printf("nEnter two numbers:");
scanf("%d%d",&a,&b);
printf("n1.Addition(+) n
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
16
2.Subtraction(-) n3.Multiplication(*)n4.Division(/)n5.Modulus(%)");
printf("nEnter the operator:");
ch=getche();
switch(ch)
{ case '+':
printf("Addition=%d",a+b);
break;
case '-':
printf("Subtraction=%d",a-b);
break;
case '*':
printf("Multiplication=%d",a*b);
break;
case '/':
printf("Division=%d",a/b);
break;
case '%':
printf("Mod=%d",a%b);
break;
default :
printf("nInvalid choice");
}
getch();
}
Output:
Enter two numbers : 3 4
Enter the operator : +
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
17
Addition=7
Relational Operators
Relational operators logically compare the values, according to condition given in the program. If the
condition is satisfied, this results in ‘true’ state otherwise ‘false’ state. True is represented by integer
value 1 and false is represented by integer value 0.
Operator Meaning of Operator Example
== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)
Relational Operators
The associatively of these operators is from left to right. The following are the two equality
operators associated with the relational operators.
Logical Operators
In logical operation the operands are themselves logical. The individual logical expression is compared,
using logical operators. The result evaluates which is represented by integer values 0 or 1.
C has three types of logical operators.
● Logical AND evaluates to true condition only if both of the operands are true.
● Logical OR evaluates to true condition if any one of the condition is true.
● Logical NOT can change the false to true or from true to false.
Operator
Meaning of
Operator
Example
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
18
&& Logial AND
If c=5 and d=2 then,((c==5) && (d>5))
returns false.
|| Logical OR
If c=5 and d=2 then, ((c==5) || (d>5))
returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
Logical Operators
Assignment Operators
⚫ The operand that appears towards the left side of an assignment operator should have a
modifiable l-value, otherwise there will be a compilation error “L-value required”.
⚫ There should be no white space character between two symbols of short-hand assignment
operators.
⚫ If two operands of an assignment operator are of different types, the type of operand on the right
side of assignment operator is automatically converted to the type of operand present on its left
side.
Operator Example Same as
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Assignment Operators
Bitwise Operators
● Bitwise operators operate on the individual bits of operands and are used for bit manipulation.
● They can only be applied on operands of type char, short, int, long, whether signed or unsigned.
● The bitwise NOT operator results in 1’s complement of its operand.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
19
● Left shift by one bit is equivalent to multiplication by 2. Left shift by n bits is equivalent to
multiplication by 2n
, provided the magnitude does not overflow.
● Right shift by one bit is equivalent to an integer division by 2. Right shift by n bits is equivalent
to integer division by 2n
.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise Operators
Special Operators
There are two special operators available in C language
i) sizeof Operator
ii) Conditional Operator
Sizeof Operator
The general form of sizeof operator is:
a) sizeof expression or sizeof (expression)
(For example: sizeof 2, sizeof(a), sizeof(2+3))
b) sizeof (type-name)
(For example: sizeof(int), sizeof(int*), sizeof(char))
Example Program using sizeof()
#include<stdio.h>
main()
{
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
20
int a=1,b;
b=sizeof(++a);
printf(“Resultant values of a and b are:n”);
printf(“%d %d”,a ,b);
}
Output: Resultant values of a and b are:
1 2
Conditional Operator
C has special operator called ternary or conditional operator. It uses three expressions. The general
format of conditional operator is given below.
Expression 1 ? Expression 2 : Expression 3
Evaluation of expression 1 is done logically.Hence it results either in true (i.e. value = 1) or in false (I.e.
value = 0) condition. If expression 1 results in true condition then expression 2 is evaluated this becomes
the value of expression 1. If expression 1 results in false condition, then expression 3 is evaluated and
this value is assigned to expression 1.
For example: c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Address-of Operator
1. The syntax of using address-of operator is: & operand
2. The operand of the address-of operator must be a variable or a function designator. The
address of operator cannot be applied to constants, expressions, bit-fields and to the variables
declared with register storage class.
Precedence of Operators
The operators have the following precedence.
Precedence Operator category Operators
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
21
1 unary operators - ++ ! sizeof
(type)
2 arithmetic multiply, divide and
remainder
* / %
3 arithmetic add and subtract + -
4 relational operators < <= > >=
5 equality operators !=
6 logical and &&
7 logical or ||
8 conditional operator ? :
9 assignment operators = += -=
%= /= *=
Managing Input and Output operations
In c language input and output functions are accomplished through library function.
The header file for I/O function is <stdio.h>.
In C there are two types of I/O functions.
They are console I/O and file I/O.
Console I/ o function takes I/P from keyboard and produces o/p on the screen.
The console Input / Output functions are also called as Standard input / output functions.
Classification:
The console I / O function are classified as shown below.
Formatted I / O Functions
Formatted I / O means reading and writing data in formats which are desired by the user. The function
used to input action is scanf() and output action is printf().
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
22
Output Function
The printf() Function
printf() is used to print or display data on the console in a formatted form.
The format of printf() is
printf( “control string”, list of arguments);
Control string contains the formatting instructions within quotes. This can contain
(i) characters that are simply printed as they are
(ii) Conversion specifications with begins with format specifier (%) sign.
(iii) Escape sequences.
Format Specifier
Arguments values get substituted in the place of appropriate format specifications. Arguments can be
variables, constants, arrays or complex expressions. The percentage (%) followed by conversion
character is called format specifier. This indicates the type of the corresponding data
item.Format
specifier
Meaning
%d or %i decimal integers
%u unsigned decimal integer
%x unsigned hexadecimal (lower case letter)
%X unsigned hexadecimal (upper case letter)
%o octal
%c character
%f floating point
%s strings
%lf double
%ld long signed integer
%lu long unsigned integer
%p displays pointer
%% prints a % sign
%e scientific notation (e lower case)
%E scientific notation (e upper case)
Application of printf() Function
The printf() function is used to print the different types of output.
Escape Sequence
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
23
In addition to format specification, escape sequence can also be used in printf(). These are specified in
the control string portion of the printf() and are used mainly for screen formatting. All escape sequence
provided with slash ( / ). Since back slash is considered as an “escape” character. These sequences are
called escape sequences. These sequences cause an escape from the normal interpretation of a string. So
that the next character (after blank slash) is recognized as having a special meaning.
● t moves the cursor to next tab problem
● n makes the a cursor to go to new line.
● r moves the cursor to the beginning of the line in which it is
currently placed.
● a alters the user by sounding the inbuilt speaker of system.
● b moves the cursor one position to the left of its current
opposition.
● The character of single quote and back slash can be printed by
using escape sequence ’, ”,  respectively.
Example:
(i) printf(“Teacher asked, ” did you understand ?” ”);
This will print
Teacher asked, “did you understand?”
(ii) printf(“The sequence is a<b, where ’b’ is > 0”);
This will print
The sequence is a<b, where ‘b’ is >0
(iii) printf(“Hi,n How are n You?”);
This will print Hi
How are
You?
Minimum Field Width Specifier (MFWS)
The following example demonstrates the working of minimum field width specifier.
For Example :
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
24
Double count;
Count = 10.51324; // here total digits are 8, includes dot ( . )
printf (“ %f” , count);
printf (“ %10f” , count);
printf (“ %010f” , count);
Output
10.51324
10.51324 // inserts 2 blank spaces. So that total length = 10 digits
0010.51324 // inserts 2 zeros. So that total length = 10 digits
Input Function
The scanf() Function
The scanf() reads the input data from standard input device(i.e.keyboard).
The general format of the scanf() function is
scanf( “format string” list of arguments );
where format string consists of format specifiers and arguments consists of address of variables.
To this corresponding address the data read from keyboard is sent. The address of the variable is denoted
by ampersand symbol ‘&’ (it is called as ‘’address of the operator).
For Example
(i) To read integer data:
int i ;
scanf(“%d”, &i);
(ii) To read floating point data:
floatf;
scanf(“%f”, &f);
(iii) To read character data;
char sam, john;
scanf(“%c”, &sam, &john);
(vii) To read more than one data types at a time
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
25
int i;
float b;
char c;
string s;
scanf(“%d %f %c %s”, &i, &b, &c, &s );
Unformatted I / O Function
A simple reading of data from keyboard and writing to I / O device, without any format is called
unformatted I / O functions. This can be classified as string I / O and character I /O.
Character Input/Output(I/O)
In order to read and output a single character character I / O functions are used.
The functions under character I / O are
● getchar()
● putchar()
● getch()
● getche()
The getchar( ) function
The getchar function is a part of the standard C I/O library. It returns a single character from a standard
input device typically a keyboard.
Drawback with getchar() is that buffers the input until ‘ENTER’ key is pressed. This means that getchar
does not see the characters until the user presses return.This is called line buffered input.
int i, j;
char a, b;
j = getchar(); // I / O int data type into j
a = getchar(); // I / O char data type into a
putchar(i);
putchar(b);
Output
a
d
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
26
Alternatives to getchar()
The two common alternative functions to getchar() are
● getch()
● getche()
The getch() function reads a single character at a time and it waits for key press. It does not echo the
character on the screen. The getche() is same as getch()/ but the key is echoed.
This is illustrated below.
char ch;
ch = getch() // let key press = k
putchar(ch);
String I / O
In order to read and write string of characters the functions gets() and puts() are used gets() function
reads the string and puts() function takes the string as argument and writes on the screen.
This is illustrated below
char name [50];
puts (“Enter your name”);
gets (name);
puts(“ The name entered is “)
Output:
Enter your name: Fredric /* string as entered by user*/
The name entered is: Fredric
Introduction to looping and branching
In most of C programs that are encountered so far, the instructions appeared in serial fashions.
In reality C program requires a logical test to be carried at some point in the program depending upon
the outcome of the logical test, one of several possible actions can be carried out. This is called
branching. The branching structure which controls the program flow is called control structure. The
classification of control structures is given below.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
27
Conditional control Statements
The if – else statement
It contains a condition. It is logically evaluated. If it evaluates to TRUE condition, then statements
under if part is executed. If the condition evaluates to FALSE state then statements under else part is
executed. Else clause is optional. The statement under if or else part can be single or multiple
statements. If multiple statements are used, they must be embraced with the braces. The syntax of if
One way Branching
If statetment
Two Way Branching
If….else statement
Multi way Branching
If..else if ladder
Nested If
Switch Case
Looping or Iterative
Statements
Decision Statements
CONTROL STRUCTURES
for statement
while statement
do ..while statement
Unconditional control Structure
Conditional control structure
Break
Continue
Goto
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
28
– else statement is given here.
Syntax: i) Simple if statement
if(expression) Statement;
else
Statement; /* else part is optional*/
ii) if – else Statement
if (expression)
{
Statement1; Statement2;
. . .
Statement n;
}
else
{
Statement1; Statement2;
. . .
Statement n;
}
Some valid forms of if are given below
(i) if (x > 0)
printf( “%i”, x);
(ii) if (a > b)
printf( “ a is greatest ”);
else
printf( “ b is greatest ”);
(iii) if ( a = = b )
{
printf( “ a & b are equal ” )
printf( “ x/a is equal to x/b ” )
}
Some invalid forms of if are given below
(i) if ( a > b );
printf( “a is greatest” )
The semicolon at the end of condition, makes if (a>b) as invalid.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
29
(ii) if ( a > b )
statement1; statement2;
statement3;
Here multiple statements under if are not enclosed in braces.
(iii) if ( a > b )
{
Statement 1;
statement 2;
. . .
Statement n;
};
Here the ending brace has semicolon ( ; )
Examples for if….else:
Example 1
Write a program to calculate greatest of 3 numbers.
/* Write a program to calculate greatest of 3 numbers */
# include <stdio.h>
main()
{
int a, b, c;
printf(“Enter three numbers”);
scanf (“ %d %d %d “, &a, &b, &c);
if ( ( a > b) && (a > c))
printf (“n a is greatest”);
if ( ( b > a) & & (b > c))
print f (“n b is greatest”);
if ( ( c > a) & & (c > b))
print f (“n c is greatest”);
}
Example 2
Write a program to check a given number is odd or even.
/* program to check given number is either odd or even*/
# include <stdio.h>
main()
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
30
{
int a;
printf(“Enter the number to bechecked”);
scanf (“ %d” , &a);
if ( (a%2) = = 0)
printf(“The given number is even”);
else
printf(“The given number is odd”);
}
The final else is associated with if (a) and not associated with if c, because it is not in the
same block.
Nested if...else statement (if...elseif....else Statement)
The if...else statement can be used in nested form when a serious decision are involved.
Syntax of nested if...else statement.
Nested if Statement
Syntax:
If(condition1) {
If(condition2) {
If(condition3) {
statement 3; }
else
statement 2; }
else
statement 1; }
else
statement 0;
How nested if...else works?
If the test expression is true, it will execute the code before else part but, if it is false, the control of the
program jumps to the else part and check test expression 1 and the process continues. If all the test
expression are false then, the last statement is executed.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
31
Example of nested if else statement:
Write a C program to check the given two integers are =to or > or < .
#include <stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check".n);
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d=%d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d>%d",numb1,numb2);
else
printf("Result: %d>%d",numb2,numb1);
return 0;
}
Output
Enter two integers to check.
5
3
Result: 5>3
if -else - if Ladder
A common programming construction is the if-else-if staircase because of its appearance. The
general form is
if ( expression ) Statement:
else
if ( expression ) Statement:
else
if ( expression ) Statement:
. . . else Statement;
The condition are evaluated from top, towards down. As soon as a true condition is found, the statement
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
32
associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true,
the final else is executed. If final else is not present, no action taken place if all other conditions are false.
This is given in the below example
# include <stdio.h>
main()
{
int i;
i = 0;
clrscr();
printf(“Enter your choice (1-4);”);
scanf (“ %d” , & i);
if ( i == 1)
printf(“n your choice is 1”);
else if ( i = = 2)
printf(“n your choice is 2”);
else if ( i = = 3)
printf(“n your choice is 3”);
else if ( i = = 4)
printf(“n your choice is 4”);
else
printf(“n invalid choice”);
}
Output:
Enter your choice (1-4): 2
Your choice is 2.
Explanation: here the second condition ( i ==2) is true. Hence the following printf() is executed
and control will come out of loop. If none of the conditions is satisfied then final the statement is
executed.
Switch Statement
C has a multiple branch selection statements called switch. It tests the value of an expression against
a list of integer or character constants. When a match is found the statements associated with that
constants are executed. The general format of switch is
switch (expression)
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
33
{
case constant1:
Statement sequence break;
case constant2:
Statement sequence break;
case constant3:
Statement sequence break;
. . .
default:
Statement sequence
}
Switch, case and default are key words and statement sequence can be single statement or a compound
statement. If it is compound statement it must be enclosed in braces.
In case expression such as case constant1, case constant2, case constant3, . etc the word constant
1 is called case labels or case prefixes. The case label can either be integer or character constant. Each
case label must be distinct.
If none of the cases are satisfied, the default statement is executed. The default statement is optional.
If none of the case are satisfied and default case is also not present, then no action takes place. To
understand the functioning of switch-case statement a few programs are given below.
Example 1 write a program to check whether the enter the character is a vowel, a last alphabet or
consonant
# include <stdio.h>
main()
{
char ch()
printf(“n Enter a lower case alphabeet (a-z);”);
scanf (“ %d” , & ch);
if ( ch<’a’ || ch>’z’)
printf(“n Character is not lower case alphabet”);
else
switch (ch)
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
case ‘u’ :
printf(“n Entered Character is vowel”);
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
34
break;
case ‘z’ :
printf(“n Entered Character is last alphabet”);
break;
default;
printf(“n Entered Character is consonant”);
}
}
Output: Enter a lower case alphabet ( a – z ): p
entered character is consonant.
Explanation: each case need not have its own statements. A set of case can have common statements
to be executed. This is as shown in the above program. The default can either end with break or not.
This depends upon program structure.
Difference Between if Statement and Switch Statement
No. If statement Switch statement
1 It checks whether the condition is
true or false
It is multi-way decision
statement
2 It contains the condition which will
evaluates to true or false
It contains the variable whose value
is to be checked
3 It supports all types of
conditions
It supports checking only integer and
character values
4 Syntax:
if(condition)
{
//statements
}
else
{
//statements
}
Syntax:
switch(variable)
{
case value1:
break;
case value2:
break;
default:
break;
LOOPING
Loops
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
35
In the programming often there is a need to perform an action over and over ie repeatedly, often
with variations in the details each time we repeat. This repetitive operation is done through the
control structure called loop or iteration.
There are three types of looping, namely:
1. for loop
2. while loop
3. do-while loop
The for loop
A for loop is a block of code that iterates a list of commands as long as the loop control condition is
true. The syntax of for loop is
for(initialization;Test condition;loop expression)
statement sequence
Syntax explanation:
(1) Initialization:
This is some kind of expression which initializes the control variable or (index varaible) This
statement is carried out only once before the start of the loop. e.g. i = 0;
(2) Condition:
The condition is evaluated at the beginning of every loop and the loop is only carried out while this
expression is true. e.g. i < 20;
(3) Loop expression
This is some kind of expression for altering the value of the control variable. This expression is
evaluated at the end of each iteration. In C it can be absolutely anything. e.g. i++ or i *= 20 or i /=
2.3 ...
(4) Statement sequence
Statement sequence can consist only one statement or a group of statements. If it contains a group
of statements, they must be embraced in braces({}).If it contains only one statement , braces need
not be enclosed.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
36
Simple programs using for loop is given below
1. Write a program to print a word hello five times using for loop.
/* A program to print hello five times */
#include<stdio.h>
int main()
{
int i;
for(i=0; i<5; i++)
printf("Hello n");
}
Output: Hello
Hello Hello Hello
Hello
Example 2: Write a program to convert 0 through 15integers to hex numbers
#include <stdio.h>
main()
{
int i;
printf("Hex(uppercase)t Hex(lowercase)t Decimaln");
for (i=0; i<16; i++)
printf("%Xt %xt %dn", i, i, i);
}
Output:
Hex(uppercas
e)
Hex(lowercase) Decimal
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
A a 10
B b 11
C c 12
D d 13
E e 14
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
37
F f 15
The Comma Operator in The for Loop
The comma (,) operator is basically used in conjunction with for loop statement. This permits two
expressions to be used in initialization and count section of the for loop. Only one test expression is
allowed in the for loop.
The syntax of this is given below
for (expression1a, expression1b; expression2; expression3a, expression3b) Here
expression 1a and expression 1b and expression 3a expression 3b are separated comma operator.
For example consider the below for statement for(i=0,j=2;j<=0;j--
,i++)
Here i and j are the two different variables used and they are separated by comma operator. Operation
of this is given in the below example:
#include <stdio.h>
main()
{
int i, j;
for (i=0, j=1; i<8; i++, j++)
printf("%d - %d = %dn", j, i, j - i);
}
Output:
1 - 0 = 1
2 - 1 = 1
3 - 2 = 1
4 - 3 = 1
5 - 4 = 1
6 - 5 = 1
7 - 6 = 1
8 - 7 = 1
The Nested for Loop
The concept of using a loop within a loop is called nested loop. If a for loop contains another for loop
statement, such loop is called nested for loop..
SYNTAX:-
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
38
for (initializing ; test condition ; increment / decrement)
{
statement;
for (initializing ; test condition ; increment / decrement)
{
body of inner loop;
}
statement;
}
Example : C program to evaluate the following series 1+1/1!+1/2!+1/3!+1/4!.....
#include <stdio.h>
void main()
{
double sum=0,fact=1;
int n, i,j;
clrscr();
printf("Enter the number ‘n’ to calculate s= 1+1/2!+1/3!......1/n ");
scanf("%d", &n);
for (i=1;i<=n;i++)
{
fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
sum=sum+(1/(fact));
}
printf("Sum : %f",sum);
getch();
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
39
While Loop
The simplest of the three loops is the while loop.The while-loop has a condition and the statements .The syntax
is given below.
while (condition)
{ statements; }
The condition expression (something like (a > b) etc...) is evaluated first. If the expression evaluates to True
state i.e returns a nonzero value (normally 1) the looping continues; that is, the statements inside the
statement block are executed. After the execution, the expression is evaluated again. The statements are then
executed one more time if the expression still returns nonzero value. The process is repeated over and over
until the expression returns 0(False state).
The statement block, surround by the braces { and }.If there is only one statement in the statement block, the
braces can be discarded. Consider an example of using the while statement.
1) Write a program to understand the use of while loop.
#include <stdio.h>
main()
{
int a;
printf("Enter a character:n(enter x to exit)n");
while (a != `x')
{
a = getc(stdin);
putchar(a);
printf("n");
}
printf("nOut of the while loop. Bye!n");
}
Output: Enter a character:
(enter x to exit)
i H x
x
Out of the while loop. Bye!
Do-while Loop
The while and for loops test the termination condition at the beginning of the loop. By contrast, the do-while
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
40
loop, tests at the bottom after making each pass through the loop body; the body is always executed at least
once.
The syntax of the do .. while is
do
statement
while (expression);
First the statement is executed under the do clause, then expression in the while is evaluated. If it is true,
statement is executed and again the while is evaluated and this looping process continues. When the
expression becomes false, the loop terminates. The do-while is much less used than while and for. If the
statement contains a set of statements, they must be enclosed in the braces .consider the example to understand
the working of while-do loop.
1) Write a program to illustrate the working of do-while loop
#include<stdio.h>
int main(void)
{
int pass-word= 15;
int code; int i=3;
do
{
printf("Type the password to enter.n");
scanf("%d", &code);
if (code==15)
printf("Right code. You can Entern");
else
printf(“Wrong Entry”);
i=i-1;
}while(i!=0); }
Output:
13
Wrong Entry
15
Right Code. You can Enter.
In Do-while, the loop the is executed as least once before checking the validity condition. In Do-while structure
entry to the loop is automatic (even with invalid input).Choice is given only for the continuation of the loop. Such
problems are deemed to be lack of control
Difference Between while & Do .. while Statement
S.No While loop do-while loop
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
41
1. In while loop a condition is evaluated at the
beginning of the loop.
In do-while loop a condition is evaluated at
the end of the loop.
2. A body of the loop is not be executed when the
value of the condition is false.
The body of the loop will not be executed
when the value of the condition s false. But
the loop is executed at least once even the
condition is false.
Unconditional control Statements
Break Statement
The break statement is used to terminate loops or to exit from a switch. It is used within loop structures namely
for, while, do-while and switch statement.
The syntax of break statement is
break;
Break Statement Within Loops
A break within a loop is generally protected within an if statement. This provides control towards the exit
condition. This depicted in the below example.
Example: Write a program to illustrate the functioning of break statement inside a for loop.
#inlude <stdio.h>
int main()
{
int i;
for (i = 1; i < 10; i++)
{
printf_s("%dn", i);
if (i == 4)
break;
}
}
Output
1
2
3
4
Continue Statement
Instead of breaking a loop, a need to stay in the loop but skip over some statements within the loop may occur.
To do this, the continue statement is used. The continue statement takes the control to the beginning of the
loop bypassing the statements inside the loop which have not yet been executed. The continue statement can
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
42
only be used within the body of a while, do, or for statement. For better control over the program, like a break
statement, continue is generally used in conjunction with if structure within loops. When continue is used
the next iteration of a do, for, or while statement is determined as follows:
Syntax:
while (<expression>)
{
...
if (<condition>)
continue;
...
...
// control jumps here on the continue
}
Example 1 : Write a program to find the sum Using the continue statement in for loop.
#include <stdio.h>
main()
{
int i, sum;
sum = 0;
for (i=1; i<8; i++)
{
if ((i==3) || (i==5))
continue;
sum += i;
}
printf("The sum of 1, 2, 4, 6, and 7 is: %dn", sum); }
Output
The sum of 1, 2, 4, 6, and 7 is: 20
Example 2: Write a program to find the odd numbers using continue statement in while loop.
/* a program to find the odd numbers using continue statement*/
#include <stdio.h>
main ()
{
Int x;
x = 0;
while (x < 10)
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
43
{
++x;
if (x % 2 == 0)
{
continue;
}
printf ("%i is an odd number.n", x);
}
Output
1 is an odd number.
3 is an odd number.
5 is an odd number.
7 is an odd number.
9 is an odd number.
Goto and Labels
A goto statement causes an unconditional branching of the program to the statement associated with the label
specified on the goto statement. A label has the same form as a variable name, and is followed by a colon. The
scope of a label is the entire function. Label name must be unique for that program .Any number of goto
labels can be used inside the program, provided each one of them is distinct. Format of goto statement is given
below.
Syntax:
for ( ... ) statement
for ( ... )
{
...
if (disaster)
goto label name ;
}
Write a program to understand the functioning of the goto statement.
#include <stdio.h>
int main()
{
int i, j;
for ( i = 0; i < 10; i++ )
{
printf( "Outer loop executing. i = %dn", i );
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
44
for ( j = 1; j < 3; j++ )
{
printf( " Inner loop executing. j = %dn", j );
if ( i == 2 )
goto stop;
}
}
printf( "Loop is quit. i = %dn", i );
stop: printf( "Jumped to stop. i = %dn", i );
}
Output:
Outer loop executing. i =0
Inner loop executing. j =1
Outer loop executing. i =1
Inner loop executing. j =2
Outer loop executing. i =2
Inner loop executing. j =1
Jumped to stop. I=2
this example, a goto statement transfers control to the point labeled stop when i equals 2.
2.11. Simple Scientific and Statistical Problems in C
Program: To find Area and Circumference of the Circle
#include<stdio.h>
#include<conio.h>
void main()
{
float r,Area,Circumference;
clrscr();
printf("nnEnter the Radius of Circle : ");
scanf("%f",&r);
Area = 3.14 * r * r;
Circumference = 2 * 3.14 * r;
printf("nnThe Area of the Circle = %.2f",Area);
printf("nnThe Circumference of the Circle = %.2f",Circumference);
getch();
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
45
}
Input / Output:
Enter the radius of the circle : 2.5
Area of Circle is : 19. 62
Circumference of the Circle : 15.70
Program: To Calculate Simple Interest
#include<stdio.h>
#include<conio.h>
int main()
{
float p,rate,years,si;
clrscr();
printf("Enter Principal amount : ");
scanf("%f", &p);
printf("Enter Number of Years : ");
scanf("%f", &Year);
printf("Enter Rate of interest : ");
scanf("%f", &rate);
si=(p*time*rate)/100;
printf("n Simple Interest = %2f",si);
getch();
return 0;
}
Input / Output:
Enter Principal Amount : 1000
Enter Number of Years : 3
Enter Rate of Interest : 2.5
Simple Interest = Rs. 75.00
Program: To find the given year is leap or not
#include<stdio.h>
#include<conio.h>
void main()
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
46
{
int n;
clrscr();
printf("nEnter the year:");
scanf("%d",&n);
if((n%400==0)||((n%4==0)&&(n%100!=0)))
printf("Leap Year");
else
printf("Not a Leap Year");
getch();
}
Input / Output:
Enter the year: 2000
The given year 2000 is a leap year
Enter the year: 1900
The given year 1900 is not a leap year
Program: To find the Quadratic Equation
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
float a,b,c,d;
float root1,root2;
clrscr();
printf("nnEnter the value of a : ");
scanf("%f",&a);
printf("nnEnter the value of b : ");
scanf("%f",&b);
printf("nnEnter the value of c : ");
scanf("%f",&c);
d = b * b - 4 * a * c;
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
47
if( d >= 0 )
{
root1 = (-b + sqrt (d)) / (2 * a);
root2 = (-b - sqrt (d)) / (2 * a);
printf("nThe Root1 is : %.2f",root1);
printf("nThe Root2 is : %.2f",root2);
}
else
{
printf("nnThe Roots are Imaginary");
}
getch();
}
Input / Output:
Enter the value of a: 1
Enter the value of b: 0
Enter the value of c: -9
The roots of the values a=1 b=0 c = -9 are 3.000000 and 3.000000
Program: to calculate the Celsius to Fahrenheit, Newtons Law of Force, Voltage Calculation, Energy
Calculation, Capacitance Calculation
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
float Celsius, Fahrenheit;
float mass_of_the_object, acceleration_of_the_object,Force;
float V,I,R;
float E,L;
float C;
int choice = 1;
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
48
clrscr();
while(choice < 6)
{
printf("nn1. Celsius To Fahrenheit");
printf("n2. Newtons Law of Force");
printf("n3. Voltage Calculation");
printf("n4. Energy Calculation");
printf("n5. Capacitance Calculation");
printf("n6. Exit");
printf("nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{ case 1 :
printf("nEnter the Celsius Value : ");
scanf("%f",&Celsius);
Fahrenheit = (1.8 * Celsius) + 32;
printf("nThe Fahrenheit Value of %.2f Celsius is : %.2f",Celsius,Fahrenheit);
break;
case 2:
printf("nEnter the value of Mass of the Object : ");
scanf("%f",&mass_of_the_object);
printf("nEnter the value of Acceleration of the Object : ");
scanf("%f",&acceleration_of_the_object);
Force = mass_of_the_object * acceleration_of_the_object;
printf("nThe Force value is : %.2f",Force);
break;
case 3:
printf("nEnter the Resistance value (in ohms) : ");
scanf("%f",&R);
printf("nEnter the Current Value (in amps) : ");
scanf("%f",&I);
V = I * R;
printf("nThe Volts value is : %.2f volts",V);
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
49
break;
case 4: printf("nEnter the Inductance Value (in Henry) : ");
scanf("%f",&L);
printf("nEnter the Current Value (in amps) : ");
scanf("%f",&I);
E = L * I * I / 2;
printf("nThe Energy Value is : %.2f Joules",E);
break;
case 5:
printf("nEnter the Energy Value (in joules) : ");
scanf("%f",&E);
printf("nEnter the Voltage Value (in volts) : ");
scanf("%f",&V);
C = 2 * E / ( V * V );
printf("nThe Capacitance Value is : %.2f farad",C);
break;
case 6:
exit(0);
} }
getch();
}
Input / Output:
1. Celsius To Fahrenheit
2. Newtons Law of Force
3. Voltage Calculation
4. Energy Calculation
5. Capacitance Calculation
Enter your choice: 1
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
50
Enter the Celsius Value: 45
The Fahrenheit of the given Celsius 45.00 is 113.00
ARRAY BASICS
Array is a simple data structure which can store collection of elements of same data type. All
elements are stored in the contiguous memory. An array is used to store a collection of data, but
it is often more useful to think of an array as a collection of variables of the same type. Instead of
declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring Arrays
To declare an array, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10-element array called
balance of type double, use this statement:
double balance[10];
Now balance is avariable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize array either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
51
element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th ie. last element because all arrays have 0 as the index of their first element
which is also called base index.
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable.
e.g.
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
52
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %dn", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
MULTIDIMENSIONAL ARRAYS
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
TWO-DIMENSIONAL ARRAYS
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
53
The simplest form of the multidimensional array is the two-dimensional array. A twodimensional array
is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size x,y you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two
dimensional array can be think as a table which will have x number of rows and y number of
columns. A 2-dimentional array a which contains three rows and four columns can be shown as
below:
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements:
An element in 2-dimensional array is accessed by using the subscripts ie. row index and column
index of the array. For example:
int val = a[2][3];
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
54
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above diagram. Let us check below program where we have used nested loop to handle a two
dimensional array:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %dn", i,j, a[i][j] );
}
}
return 0;
}
When the above code is compiled and executed, it produces following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
55
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
Function
A function is a group of statements that together perform a task. Every C program
has at least one function, which is main (), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions.
Functions are of two types:-
● Built in function or Library Functions
● User defined functions
Built in functions:-
library. Many activities in C
are carried out using library functions. These functions perform file access, mathematical
computations, graphics, memory management etc.
optional list of arguments and header file of used function should be included with the
program.
C has many built-in functions that you can use in your programs.
main( ) printf( ) scanf( ) gets( ) puts( ) strcpy( ) strlen( )
strcmp( ) stricmp( ) strcat( ) strstr( ) isalpha( ) isdigit( )
isupper( ) islower( )
User-Defined Functions:-
If you have a special set of instructions that aren’t in a built-in function, you can create a
user-defined function. Here are the steps:
1. Give your function a name that isn’t already used in C (by built-in functions, types of
variables, keywords, etc.)
2. Create a function header, which contains three things:
a. The type of variable (int, char, double, etc.) that the function will produce (return)
b. The name of the function, which can be one or more words (but put underscores _ or
Capital Letters connecting these words, because no spaces are allowed)
c. The parameters of the function, which are the names and types of variables inside
your function.
A function declaration consist of 4 parts.return-type
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
56
● function name
● parameter list
● terminating semicolon
● Function definition Syntax
General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body ; }
The first line return-type function-name(parameter) is known as function header and the
statement within curly braces is called function body.
1. return- return type specifies the type of value(int,float,char,double) that function
is expected to return to the program calling the function.
2. function-name
is any valid C identifier and therefore must follow the same rule of formation as other
variables in C.
3. parameter-list will receive the data sent
by calling program. They often referred to as formal parameters. These parameters are also
used to send values to calling program.
4. function- The function body contains the declarations and the statement
(algorithm) necessary for performing the required task. The body is enclosed within curly
braces { } and consists of three parts.
Local variable declaration.
Function statement that performs the tasks of the function.
A return statement that return the value evaluated by the function.
Function Prototypes
According the arguments and the returning value, functions are divided into
1) A function with no arguments and no return value
2) A function with no arguments and return a value
3) A function with an argument or arguments and returning no value
4) A function with arguments and returning a value.
1. Function with No Arguments and No Returns a Value
● The function will not get of data from the calling function and also data is not sent
back to the called function.
● Here is no data transfer between calling function and called functions.
● The called functions are used to perform any operation.
● They act independently.
● This is used to print some messages.
Program:
#include<stdio.h>
#include<conio.h>
void fun();
void main()
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
57
{
fun();
getch();
}
fun()
{
}
printf("hi, this is display from function
funct()");
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
58
2. Functions with arguments and no return value in C :
● The function where arguments are passed through the calling function.
● The called function operates on the data.
● But the result is not sent.
● The called ones are partly depend on the calling function.
● The result obtained is utilized by the called function only.
Program:
#include<stdio.h>
#include<conio.h>
void add(int a,int b);
void main()
{
int a=5,b=4;
add(a,b);
getch();
}
void add(int a, int b)
{
int c;
c=a+b;
printf("n Result = %d",c);
}
3. Functions with no arguments and return value in C :
● The type function has no arguments.
● The called one function return the value.
● The called function is been independent of calling.
Program:
#include<stdio.h>
#include<conio.h>
int add();
void main()
{
int result; result=add();
printf("n Result = %d",result);
getch();
}
int add()
{
int a=5,b=4,c; c=a+b;
return c;
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
59
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
60
4.Functions with arguments and return value in C :
● This has arguments as well as return value.
● Both the called and calling function is dependent
● Communication is between both the functions.
Program:
#include<stdio.h>
#include<conio.h>
int add(int a,int b);
void main()
{
int a=5,b=4,c;
c=add(a,b);
printf("n Result = %d",c);
getch();
}
int add(int x, int y)
{
int z;
z=x+y;
return z;
}
Call by Value and Call by Reference
● Functions communicate with each other by passing the arguments.
● There are two ways of passing the arguments namely, call by value and call by
reference.
Call by Value
● Whenever a function is called, the values of variables are passed to the called
function from calling function.
●Such function calls are called “calls by value”.
● The value of each of the actual arguments in the calling function(function call) is
copied into corresponding formal arguments of the called function.
● The function which is called by value can not change the values of actual parameters.
Program:
void main ( )
{
i nt a = 10, b=20; void
swap(int a,int b);
swap(a,b);
printf ("a = % d b = % d", a,b);
getch();
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
61
swap (int x, int y)
{
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
62
int t; t
= x; x
= y; y
= t;
}
output :
a =10 b =20
Call by Reference
● Second method, the addresses of actual arguments in the calling function are copied
in to formal arguments of the called function.
● The values are not passed, the address is been pass.
● Passing the address of a variable to a function is called passing by reference.
● The function which is called by reference can change the values of actual parameters.
Example Program:
void main ( )
{
i nt a = 10, b=20;
void swap(int *a,int *b);
swap(&a,&b);
printf ("a = % d b = % d", a,b);
getch();
}
void swap (int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = *t;
}
output :a =20 b =10
Recursion
A function that calls itself is known as recursive function and this technique is known as recursion
in C programming. (OR)
Recursion is the process of repeating items in a self-similar way. In programming languages, if a
program allows you to call a function inside the same function, then it is called a recursive call of
the function. (OR)
The process of calling a function by itself is called recursion and the function which calls itself is
called recursive function.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
63
Syntax of Recursive Function
returntype recursive_func ([argument list])
{
statements;
... ... ...
recursive_func ([actual argument]);
... ... ...
}
Flowchart of Recursion
Example 1:
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
64
How does it Works
Example #1: C Program to show infinite recursive function
#include<stdio.h>
void main()
{
printf("Hello world");
main();
}
In this program, we are calling main() from main() which is recursion. But we haven't defined
any condition for the program to exit. Hence this code will print "Hello world" infinitely in the
output screen.
Example #2: C program to calculate factorial of a number using recursion.
Program
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return (factorial(n-1)*n);
}
int main()
{
int num,f;
printf("Enter a number: ");
scanf("%d",&num);
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
65
f=factorial(num);
printf("Factorial of %d = %d",num,f);
return 0;
}
Here, factorial is calculated using recursion. The formula for calculating factorial of a number n
is,
n! = 1*2*...(n-1)*n
Again, we can see
(n-1)! = 1*2*...(n-1)
Hence we can write,
n! = (n-1)! * n
We have implemented this recursive relation in our program.
Here,
The number whose factorial is to be found is stored in the variable n.
A recursive function factorial(num) calculates the factorial of the number.
As factorial is (n-1)! * n, factorial function calculates the factorial by recursively multiplying n
with factorial of (n-1).
Finally, when n = 0, it returns 1 because 0! = 1.
Output
Enter a number: 7
Factorial of 7 = 5040
Example #3: C program print first n Fibonacci numbers using recursion.
#include<stdio.h>
int fibo(int num)
{
if(num==1||num==2)
return 1;
else
return (fibo(num-1)+fibo(num-2)); // recursive call
}
int main()
{
int i,n;
printf("Enter the required term: ");
scanf("%d",&n);
printf("First %d fibonacci numbers aren",n);
for (i=1; i<=n; i++)
printf("%dn",fibo(i));
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
66
return 0;
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
67
This program uses recursion to generate Fibonacci series. In a Fibonacci series, nth term can be
obtained by adding (n-1)th and (n-2)th term. Mathematically,
tn = tn-1 + tn-2
Here,
The number of fibonacci terms to be generated is taken from the user and stored in variable n.
A for loop is used to loop through the number to be generated which is sent to the function fibo.
This function is used to calculate and return fibonacci series.
Inside fibo, if the term-number is 1 or 2, it returns 1. This is because, the first two terms of
fibonacci series are both 1. The printed values are 1,1.
Then the next term-number 3 is passed onto fibo function, since it's not 1 or 2, the next term in
the series is calculated by taking fibo(n - 1) + fibo(n - 2), where n = 3. This calculates the last
two terms in the fibonacci series. This is equivalent to fibo(2) + fibo(1), which results in 1 + 1 =
2.
This recursive loop goes on finally printing the series as 1, 1, 2, 3, 5...
Output
Enter the required term: 7
First 7 fibonacci numbers are
1 1 2 3 5 8 13
Pointer
As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator, which denotes an address in
memory. Consider the following example, which prints the address of the variables defined
#include <stdio.h>
void main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %xn", &var1 );
printf("Address of var2 variable: %xn", &var2 );
}
When the above code is compiled and executed, it produces the following result
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
68
store any variable address.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
69
A pointer is a variable which contains the address of another
variable. We can have a pointer to any variable type. (or)
Pointers are variables that hold address of another variable of
same data type.
● A normal variable ‘var’ has a memory address of 1001
and holds a value 50.
● A pointer variable has its own address 2047 but stores
1001, which is the address of the variable ‘var’.
How to Declare a Pointer?
A pointer is declared as : pointer type *pointer-name
An example of a pointer declaration can be :
int *ptr
How to initialize a Pointer?
A pointer is initialized in the following way :
For example :
int a=10;
int *ptr;
ptr=&a;
Program:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
ptr = &q;
printf(“%d”, *ptr);
return 0;
}
Output 50
Pointer and Arrays
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
70
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by
the compiler.
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
71
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
element will be stored as follows
Here variable arr will give the base address, which is a constant pointer
pointing to the element, arr[0].
Therefore arr is containing the address of arr[0] i.e 1000.
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
another.
Program:
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p ;
p=a; // same as int *p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);//same as *p = &a[0]
p++;
}
Pointer Arithmetic
Like any other variables pointer can be used in expressions.
Consider below table, We have declared some of the variables and also assumed some address
for declared variables.
Data Type Initial Address Operation Address after Operations Required Bytes
int 4000 ++ 4002 2
arr is equal to &arr[0] // by default
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
72
Data Type Initial Address Operation Address after Operations Required Bytes
int 4000 - - 3998 2
char 4000 ++ 4001 1
char 4000 - - 3999 1
float 4000 ++ 4004 4
float 4000 - - 3996 4
long 4000 ++ 4004 4
long 4000 - - 3996 4
Pointer Addition
In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
Program
include<stdio.h>
void main()
{
double *ptr,*ptr1,a=10;
ptr=&a;
ptr1=ptr+1;
printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr);
}
Output
New Value of ptr and ptr1: 4286714080 4286714082 10
Pointer Subtraction
Program
include<stdio.h>
void main()
{
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
73
double *ptr,*ptr1,a=10;
ptr=&a;
ptr1=ptr-1;
printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr);
}
Output
New Value of ptr and ptr1 : 4286714080 4286714078 10
Pointer Increment
Incrementing a pointer to an integer data will cause its value to be incremented by 2 .
Program
include<stdio.h>
void main()
{
double *ptr,*ptr1,a=10;
ptr=&a;
ptr1=ptr++;
printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr);
}
Output
New Value of ptr and ptr1: 4286714080 4286714082 10
Pointer Decrement
Decrementing a pointer to an integer data will cause its value to be decremented by 2.
Program
include<stdio.h>
void main()
{
double *ptr,*ptr1,a=10;
ptr=&a;
ptr1=ptr-1;
printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr);
}
Output
New Value of ptr and ptr1 : 4286714080 4286714078 10
Comparing two Pointers
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
74
1. Pointer comparison is Valid only if the two pointers are Pointing to same array
2. All Relational Operators can be used for comparing pointers of same type
3. All Equality and Inequality Operators can be used with all Pointer types
4. Pointers cannot be Divided or Multiplied
#include<stdio.h>
Output
Ptr2 is far from ptr
EXAMPLE PROGRAMS
1.C PROGRAM FOR RECURSIVE FUNCTION TO FIND THE POWER OF A
NUMBER.
PROGRAM
#include <stdio.h>
void main()
{
int base, exp, ans;
int power(int base,int exp);
printf("Enter base number: ");
scanf("%d",&base);
printf("Enter power number: ");
scanf("%d",&exp);
ans=power(base, exp);
printf("Result is %d",ans);
getch();
}
int power(int base,int exp)
{
if ( exp==1 )
{
return base;
}
else
{
return (base*power(base,exp-1));
}
}
2. C PROGRAM TO FIND THE SUM OF DIGITS USING RECURSIVE FUNCTION.
int main()
{
int
*ptr1,*ptr2,a,b;
ptr1 = &a;
ptr2 = &b;
if(ptr2 > ptr1)
printf("Ptr2 is far from
ptr1"); return(0);
}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
75
PROGRAM
#include<stdio.h>
void main()
{
int num,s;
printf("Enter a number: ");
scanf("%d",&num);
s=findsum(num);
printf("Sum of the digits is %d",s);
getch();
}
int findsum(int n)
{
int r,s;
if(n>0)
{
r=n%10;
s=s+r;
findsum(n/10);
}
else
return s;
}
3. C PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER USING
FUNCTIONS. (8)
Program
#include<stdio.h>
int fact(int n);
void main()
{
int n;
printf("Enter a number to calculate it's factorialn");
scanf("%d",&n);
printf("factorial = %d", fact(n));
}
int fact(int n)
{
int i,fact=1;
for( i = 1 ; i <= n ; i++ )
fact = fact*i;
return (fact);
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
76
}
4. C PROGRAM TO PRINT THE FIBONACCI SERIES USING FUNCTIONS. (8)
Program
#include<stdio.h>
#include<conio.h
> int fibo(int n);
void main()
{
int n, i;
clrscr();
printf("Enter the limit:n");
scanf("%d",&n);
i=fibo(n);
printf("nThe %dth Fibonacci number is %ld",n,i);
getch();
}
int fibo(int n)
{
int sum, i=1, a=0,b=1;
while(i<=n)
{
sum=a+b;
a=b;
b=sum;
i++;
printf("n%d",sum);
}
return(sum);
}
5. C PROGRAM USING POINTERS TO READ IN AN ARRAY OF INTEGERS AND PRINT
ITS ELEMENTS IN REVERSE ORDER.(8)
Program
#include<stdio.h>
#include<conio.h>
#define MAX 30
void main()
{
int size,i,arr[MAX];
int *ptr;
clrscr();
ptr=&arr[0];
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
77
printf("Enter the size of array : ");
scanf("%d",&size);
printf("Enter %d integers into array:n",size);
for(i=0;i<size;i++)
{
scanf("%d",ptr);
ptr++;
}
ptr=&arr[size-1];
printf("Elements of array in reverse order are:n");
for(i=size-1;i>=0;i--)
{
printf("nElement%d is %d :",i,*ptr);
ptr--;
}
getch();
}
Output:
Enter the size of array : 5
Enter 5 integers into array : 11 22 33 44 55
Elements of array in reverse order are :
Element 4 is : 55
Element 4 is : 44
Element 4 is : 33
Element 4 is : 22
Element 4 is : 11
6. C PROGRAM TO FIND N
CR USING RECURSIVE FUNCTION (8)
Program
#include<stdio.h>
int main()
{
int n,r,ncr;
printf("Enter any two numbers->");
scanf("%d %d",&n,&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("The NCR factor of %d and %d is %d",n,r,ncr);
return 0;
}
int fact(int n)
{
int i=1;
while(n!=0)
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
78
{
i=i*n;
n--;
}
return i;}
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
79
Structure
Definition
element in a C structure is called member.
Need for structured data type
To store heterogenous values (different data types)
Points about structure
1. As we know that Array is collection of the elements of same type , but many time we have
to store the elements of the different data types.
2. Suppose Student record is to be stored , then for storing the record we have to group
together all the information such as Roll,name,Percent which may be of different data
types.
3. Ideally Structure is collection of different variables under single name.
4. Basically Structure is for storing the complicated data.
5. A structure is a convenient way of grouping several pieces of related information
together.
Definition of Structure in C:
Struct keyword is used to define a structure. Struct define a new data type which is a collection of
different type of data.
Syntax :
struct <structure_name>
{
structure_Element1;
structure_Element2;
structure_Element3;
...
...
};
Example:
191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
30
struct stu {
char name[64]; char
course[128]; int age;
int year;
} student;
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
Declaring Structure Variables
It is possible to declare variables of a structure, after the structure is defined.
Structure variable declaration is similar to the declaration of variables of any other
data types. Structure variables can be declared in following two ways.
1) Declaring Structure variables separately
struct student
{
char[20]
name; int
age;
int rollno;
} ;
struct student S1 , S2; //declaring variables of Student
2) Declaring Structure Variables with Structure definition
struct student
{
char[20]
name; int
age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student.
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and
the structure member that we wish to access. You would use the keyword struct to
define variables of structure type.
Example:
This program is used to store and access “id, name and percentage” for one student.
We can also store and access these data for many students using array of structures.
#include
<stdio.h>
#include
<string.h> struct
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
student
{
int id;
char
name[20];
float
percentag
e;
};
void main()
{
struct student record = {0}; //Initializing to null
record.id=1;
strcpy(record.name,
"Raju"); record.percentage
= 86.5; printf(" Id is: %d
n", record.id);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n",
record.percentage); getch();
}
ANOTHER WAY OF DECLARING C STRUCTURE:
In this program, structure variable “record” is declared while declaring structure itself.
In above structure example program, structure variable “struct student record” is
declared inside main function which is after declaring structure.
#include
<stdio.h>
#include
<string.h> struct
student
{
int id;
char
namE[20];
float
percentag
e;
OUTPUT:
Id is: 1
Name is: Raju
Percentage is:
86.500000
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
}
record;
void
main()
{
record.id=1;
strcpy(record.name,
"Raju");
record.percentage =
86.5;
printf(" Id is: %d n", record.id);
printf(" Name is: %s n",
record.name);
printf(" Percentage is: %f n",
record.percentage); getch();
}
}
Structure within Structure: Nested Structure
● Structure written inside another structure is called as nesting of
two structures.
● Nested Structures are allowed in C Programming Language.
● We can write one Structure inside another structure as member of another
structure.Syntax
struct structure1
{
- - - - - - - - - -
- - - - - - - - - -
};
struct structure2
{
- - - - - - - - - -
- - - - - - - - - -
struct structure1 obj;
};
OUTPUT:
Id is: 1
Name is: Raju
Percentage is:
86.500000
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
How to Use nested Structure
Way 1 : Declare two separate structures
struct date
{
int
dat
e;
int
mo
nth
;
int
yea
r;
};
struct Employee
{
char
enamE[20
]; int ssn;
float
salary;
struct
date
doj;
}eMP1;
Explanation
Accessing Month Field :
eMP1.doj.month Accessing day Field :
emP1.Doj.day Accessing year Field :
emP1.Doj.year
Accessing Nested Elements :
1. Structure members are accessed using dot operator.
2. ‘date‘ structure is nested within Employee Structure.
3. Members of the ‘date‘ can be accessed using ’employee’
4. emP1 & doj are two structure names (Variables)
5.
Way 2 : Declare Embedded structures
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
struct Employee
{
char ename[20]; int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Explanation
Accessing Month Field :
eMP1.doj.month Accessing day Field :
emP1.Doj.day Accessing year Field :
emP1.Doj.year
Example #1 : Display an Employee data
#include<st
dio.h>
struct
Address
{
char
HouseNo[25
]; char
City[25];
char PinCodE[25];
};
struct Employee
{
int Id;
char
Name[25];
float
Salary;
struct Address Add;
};
void main()
{
int i;
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
struct Employee E;
printf("ntEnter Employee Id ");
scanf("%d",&E.Id);
printf("ntEnter Employee Name : ");
scanf("%s",&E.Name);
printf("ntEnter Employee Salary : ");
scanf("%f",&E.Salary);
printf("ntEnter Employee House No : ");
scanf("%s",&E.Add.HouseNo);
printf("ntEnter Employee City : ");
scanf("%s",&E.Add.City);
printf("ntEnter Employee House No : ");
scanf("%s",&E.Add.PinCode);
printf("nDetails of Employees");
printf("ntEmployee Id : %d",E.Id);
printf("ntEmployee Name : %s",E.Name);
printf("ntEmployee Salary : %f",E.Salary);
printf("ntEmployee House No : %s",E.Add.HouseNo);
printf("ntEmployee City : %s",E.Add.City);
printf("ntEmployee House No : %s",E.Add.PinCode);
}
Output :
Enter Employee Id : 101
Enter Employee Name : Suresh Enter Employee
Salary : 45000 Enter Employee House No :
4598/D Enter Employee City : Delhi
Enter Employee Pin Code : 110056
Details of Employees
Employee Id : 101
Employee Name :
Suresh Employee
Salary : 45000
Employee House No :
4598/D Employee City :
Delhi Employee Pin Code
: 110056
Example #2 : Display Student Details
#include <stdio.h>
#include <string.h>
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Anna University"};
printf(" Id is: %d n", stu_data.id);
printf(" Name is: %s n", stu_data.name);
printf(" Percentage is: %f nn", stu_data.percentage);
printf(" College Id is: %d n", stu_data.clg_data.college_id);
printf(" College Name is: %s n", stu_data.clg_data.college_name);
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is:
90.500000 College Id
is: 71145
College Name is: Anna University
Array of Structures
C Structure is collection of different datatypes ( variables ) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is
also called as structure array in C.
EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:
This program is used to store and access “id, name and percentage” for 3 students.
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
Structure array is used in this program to store and display records for many students.
You can store “n” number of students record by declaring structure variable as ‘struct
student record[n]“, where n can be 1000 or 5000 etc.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1ST student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2ND student's record record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
// 3rd student's record record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d n", i+1);
printf(" Id is: %d n", record[i].id);
printf(" Name is: %s n", record[i].name);
printf(" Percentage is: %fnn",record[i].percentage);
}
return 0;
}
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
File Handling
File: the file is a permanent storage medium in which we can store the data
permanently.
Types of file can be handled
we can handle three type of file as
(1) sequential file
(2) random access file
(3) binary file
File Operation
opening a file:
Before performing any type of operation, a file must be opened and for this
fopen() function is used.
syntax:
file-pointer=fopen(“FILE NAME ”,”Mode of open”);
example:
FILE *fp=fopen(“ar.c”,”r”);
If fopen() unable to open a file than it will return NULL to the file pointer.
File-pointer: The file pointer is a pointer variable which can be store the address
of a special file that means it is based upon the file pointer a file gets opened.
Declaration of a file pointer:-
FILE* var;
Modes of open
The file can be open in three different ways as
Read mode ’ r’/rt
Write mode ’w’/wt
Appened Mode ’a’/at
Reading a character from a file
getc() is used to read a character into a file
Syntax:
character_variable=getc(file_ptr);
Writing acharacter into a file
putc() is used to write a character into a file
puts(character-var,file-ptr);
ClOSING A FILE
fclose() function close a file.
fclose(file-ptr);
fcloseall () is used to close all the opened file at a time
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
File Operation
The following file operation carried out the file
(1)creation of a new file
(2)writing a file
(3)closing a file
Before performing any type of operation we must have to open the file.c, language
communicate with file using A new type called file pointer.
Operation with fopen()
File pointer=fopen(“FILE NAME”,”mode of open”);
If fopen() unable to open a file then it will return NULL to the file-pointer.
Reading and writing a characters from/to a file
fgetc() is used for reading a character from the file
Syntax:
character variable= fgetc(file pointer);
fputc() is used to writing a character to a file
Syntax:
fputc(character,file_pointer);
/*Program to copy a file to another*/
#include<stdio.h>
void main()
{
FILE *fs,*fd;
char ch;
If(fs=fopen(“scr.txt”,”r”)==0)
{
printf(“sorry….The source file cannot be opened”);
return;
}
If(fd=fopen(“dest.txt”,”w”)==0)
{
printf(“Sorry…..The destination file cannot be opened”);
fclose(fs);
return;
}
while(ch=fgets(fs)!=EOF)
fputc(ch,fd);
fcloseall();
}
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
Reading and writing a string from/to a file
getw() is used for reading a string from the file
Syntax:
gets(file pointer);
putw() is used to writing a character to a file
Syntax:
fputs(integer,file_pointer);
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int word;
/*place the word in a file*/
fp=fopen(“dgt.txt”,”wb”);
If(fp==NULL)
{
printf(“Error opening file”);
exit(1);
}
word=94;
putw(word,fp);
If(ferror(fp))
printf(“Error writing to filen”);
else
printf(“Successful writen”);
fclose(fp);
/*reopen the file*/
fp=fopen(“dgt.txt”,”rb”);
If(fp==NULL)
{
printf(“Error opening file”);
exit(1);
}
/*extract the word*/
word=getw(fp);
If(ferror(fp))
printf(“Error reading filen”);
else
printf(“Successful read:word=%dn”,word);
/*clean up*/
fclose(fp);
}
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
Working With Strings - fputs() and fgets()
In addition to getc() and putc(), C supports the related functions fputs() and fgets(),
which read and write character strings.
They have the following prototypes:
int fputs (const char *str, FILE *fp);
char *fgets (char *str, int length, FILE *fp);
The function fputs() works like puts() but writes the string to the specified stream. The
fgets()
function reads a string until either a newline character is read or length-1 characters
have been read. If a newline is read, it will be part of the string (unlike gets()). The resultant
string will be null-terminated.
rewind ()
rewind() resets the file position indicator to the beginning of the file. The syntax of
rewind() is:
rewind(fptr);
where, fptr is a file pointer.
ferror ()
ferror() determines whether a file operation has produced an error. It returns TRUE if
an error has occurred, otherwise it returns FALSE. ferror() should be called immediately after
each file operation, otherwise an error may be lost.
fread () and fwrite ()
To read and write data types which are longer than one byte, the ANSI standard
provides fread() and fwrite(). These functions allow the reading and writing of blocks of any
type of data. The prototypes are:
size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp);
size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp);
For fread(), buffer is a pointer to a region of memory which will receive the data from
the file.
For fwrite(), buffer is a pointer to the information which will be written. The buffer
may be simply the memory used to hold the variable, for example, &l for a long integer.
The number of bytes to be read/written is specified by num_bytes. count determines
how many items (each num_bytes in length) are read or written.
fread() returns the number of items read. This value may be less than count if the end
of file is reached or an error occurs. fwrite() returns the number of items written.
One of the most useful applications of fread() and fwrite() involves reading and
writing userdefined data types, especially structures. For example, given this structure:
struct struct_type
{
float balance;
char name[80];
} cust;
The following statement writes the contents of cust:
fwrite (&cust, sizeof(struct struct_type), 1, fp);
191GES205T- PROGRAMMING AND DATA STRUCTURES USING C UNIT-1
fseek() and Random Access I/O
 Random read and write operations may be performed with the help of fseek(), which
sets the file position locator. The prototype is:
 int fseek(FILE *fp, long numbytes, int origin);
 in which numbytes is the number of bytes from the origin, which will become the new
current position, and origin is one of the following macros defined in stdio.h:
 Origin Macro Name
 Beginning of file SEEK_SET
 Current position SEEK_CUR
 End-of-file SEEK_END
 fseek() returns 0 when successful and a non-zero value if an error occurs. fseek() may
be used to seek in multiples of any type of data by simply multiplying the size of the
data by the number of the item to be reached, for example:
 fseek (fp, 9*sizeof (struct list), SEEK_SET);
 Which seeks the tenth address.
fprint() and fscanf()
 fprint() and fscanf() behave exactly like print() and scanf() except that they operate
with files.
 The prototypes are:
 int fprintf (FILE *fp, const char *control_string, ...);
 int fscanf (FILE *fp, const char *control_string, ...);
 Although these functions are often the easiest way to read and write assorted data, they
are not always the most efficient. Because formatted ASCII data is being written as it
would appear on the screen (instead of in binary), extra overhead is incurred with each
call. If speed or file size is of concern, use fread() and fwrite().

UNIT 1 NOTES.docx

  • 1.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 1 EASWARI ENGINEERING COLLEGE DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE 191GES205T -PROGRAMMING AND DATA STRUCTURES USING C UNIT I : C PROGRAMMING BASICS AND ADVANCED FEATURES 9 Conditional statements – Control statements – Arrays - Pointers - Variation in pointer declarations – Functions - Function Pointers –-Structures - File handling concepts – File read – write – binary and stdio - File Manipulations Problem Formulation and Solving To develop the solution for the given problem, the following programming techniques are used. Problem solving techniques i) Algorithm It is a set of logical procedure steps to solve the problem. ii) Flow Charts It is a diagrammatic representation of the sequence of operation for a given problem. iii) Pseudo codes These are the instructions written in ordinary English using mathematical and logical symbols to display the program logic. iv) Decision Tables A decision table consists of many independent conditions with several actions, written in table format to solve the given problem. Introduction to ‘ C’ programming C is a programming language developed at AT & T laboratories of USA in 1972 by Dennis Ritchie in 1970. It was initially implemented on the system that used UNIX operating system. C is a midlevel computer language. C is a nice blend of high level languages and low level assembly language. Important Features of C Language i. C is a system programming language which provides flexibility for writing compilers, operating systems, etc.
  • 2.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 2 ii. It can also be used for writing the application programs for scientific, engineering and business applications. iii. C is famous for its portability, meaning that program written in C for one computer can be easily loaded to another computer with little or no changes. iv. C supports variety of data types like integers, float point numbers, characters, etc. v. C is a procedure oriented language which is most suited for structured programming practice. vi. It provides a rich set of built in functions. Program Structure in C To accomplish the given task programs are written and it is executed in Turbo C/C++ compiler. The structure of the program is given below. i. The Documentation Section: It consists of a set of comment lines giving the name of the program, the author and other details which the programmer would like to use later. The comments are enclosed in a C program using /* and */ . ii. The Preprocessor directive or Link section: It provides instruction to the compiler to link some functions or do some processing prior to the execution of the program. It is also used to define symbolic constants of the program. o Header file used by the example is a standard input/output file (stdio.h).
  • 3.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 3 o programs must contain an #include line for each header file o There are two punctuation forms for head file. 1. #include <stdio.h> 2. #include “stdio.h” iii. Global Declaration Section : There are some variables that are used in more than one function. Such variables are called global variables and are declared in this section that is outside of all other functions. iv. The main() function section : Every C program must have one main() function. This section contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration part and executable parts must end with a semicolon. v. Sub program Section : It contains all the user defined functions that are called in the main() function. User defined functions are generally placed immediately after the main function, although they may appear in any order. vi. All sections except the main() function may be absent when they are not required in any C program. vii. Note that each of these topics are explained in detail in the following chapters of the book. Compilation and Linking Process Executing a C program involves a series of following steps. i. Creating a program ii. Compiling the program iii. Linking the program with functions that are needed from the C library. iv. Executing the program It is represented in the below flowchart.
  • 4.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 4 Points about C Program 1. Every C program requires a main() function. Use of more than one main() is illegal. The place of main() is where the program execution begins. 2. The Execution of the function begins at the opening brace and ends at the closing brace. 3. C programs are written in lowercase letters. However uppercase letters may be used for symbolic names and constants. 4. All the words in a program line must be separated from each other by at least one space or a tab, or a punctuation mark. 5. Every statement must end with a semicolon. 6. All variables must be declared for their type before they are used in the program.
  • 5.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 5 7. Compiler directives such as define and include are special instructions to the compiler, so they do not end with a semicolon. 8. When braces are used in the program make sure that the opening brace has corresponding ending brace. 9. C is a free form language and therefore proper form of indentation of various sections would improve the legibility of the program. C character set Every language has its own character set. The character set of the C language consists of basic symbols of the language. A character indicates any English alphabet, digit or special symbol including arithmetic operators. The C language character set includes 1. Letter, Uppercase A ….. Z, Lower case a….z 2. Digits, Decimal digits 0….9. 3. Special Characters , such as comma, period. semicolon; colon: question mark?, apostrophe‘ quotation mark “ Exclamation mark ! vertical bar | slash / backslash tilde ~ underscore _ dollar $ percent % hash # ampersand & caret ^ asterisk *
  • 6.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 6 minus – plus + <, >, (, ), [,], {, } 4. White spaces such as blank space, horizontal tab, carriage return, new line and form feed. Identifiers and Keywords Variables A variable is an identifier that may be used to store data value. A value or a quantity which may vary during the program execution can be called as a variable. Each variable has a specific memory location in memory unit, where numerical values or characters can be stored. A variable is represented by a symbolic name is also called as identifier. Ex : sum = a+b. In this equation sum, a and b are the identifiers or variable names representing the numbers stored in the memory locations. Rules to be followed for constructing the Variable names(identifiers) 1. They must begin with a letter and underscore is considered as a letter. 2. It must consist of single letter or sequence of letters, digits or underscore character. 3. Uppercase and lowercase are significant. For ex: Sum, SUM and sum are three distinct variables. 4. Keywords are not allowed in variable names. 5. Special characters except the underscore are not allowed. 6. White space is also not allowed. Variable Declarations Syntax : Data type ‘variable’
  • 7.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 7 For example: int a; float c; char name; int sam; double count; Assigning Values to Variables Values can be assigned to variables using assignment operator “=”. Syntax: Variable name = value; For Example: :a = 10; int lvalue = 0; Identifiers are the names given by user to various program elements such as variables, functions and arrays. The rules for identifiers are given below. i. Letters, digits and underscore can be used. ii. Must not start with a digit. iii. Avoid using underscore at the start of identifier iv. Identifier cannot be same as reserved word (Key Word) or C library function names. v. Identifiers are Case sensitive. For example india is different from India. Examples of Valid and Invalid Identifier are given in Valid Identifiers: 1) X1x 2) Count_2 3) Num1 Invalid Identifiers: I) 5thstandard : first character must be a letter
  • 8.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 8 II) “Sam” : illegal character (“ ”) III) Emp-no : illegal character( - ) IV) Reg no : illegal character (blank space) C Keywords Key words or Reserve words of the C language are the words whose meaning is already defined and explained to the C language compiler. Therefore Reserve words cannot be used as identifiers or variable names. They should only be used to carry the pre-defined meaning. For example int is a reserve word. It indicates the data type of the variable as integer. Therefore it is reserved to carry the specific meaning. Any attempt to use it other than the intended purpose will generate a compile time error. C language has 32 keywords. Following are some of them Some compilers may also include some or all of the following keywords. Constants There are four basic types of constants in C. They are integer constants, floating-point constants, character constants and string constants. Integer and floating point constants represent numbers. They are also called numeric- type constants. Integer constants An integer constant is an integer valued number. It consists of sequence of digits. Integer constants are divided into three different number systems. �decimal constants (base 10) �Octal constants (base8) �hexadecimal constants (base 16). All the integer constants have to follow the set of rules given below. (i)Constant must have at least one digit.
  • 9.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 9 (ii) Must not have decimal point. (iii) Constant can be preceded by minus (-) sign, to indicate negative constants. (iv) Positive integer constants can be preceded by either positive sign or no sign. (v) Commas and blank spaces can’t be included with in the constant. (vi) The value of constant must not exceed specified minimum and maximum bound. Generally for 16bit computer, the integer constant range is -32768 to 32767. For 32 bit computer the range is much larger. Now let us consider each type of integer constants individually. Decimal Integer Constants A decimal integer constant consists of any combination of digits taken from the set 0 to 9. The first digit must be other than 0. Valid decimal integer constants: 0 1 743 32767 8888 Invalid decimal integer constants �080 Fi rst digit cannot be zero �50.3 Illegal character ( . ) �12,542 Illegal character ( , ) �25 35 60 Illegal character ( Blank Space ) Octal Integer Constants An octal integer constant consists of combination of digits taken from the set 0 through 7. However the first digit must be 0, in order to identify the constant as an octal number. Valid octal integer constants 00 06 0753 0663 Invalid octal integer constants �543 Does not begin with zero �07865 Illegal character ( 8 ) �06, 593 Illegal character ( , ) �06.512 Illegal character ( . )
  • 10.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 10 Hexadecimal Integer Constants A hexadecimal integer is identified by ox or OX. Hexadecimal integer constant consists of digits taken from the set of 0 to 9 and letters taken from the set from from A to F (either upper or lower case). The letter a to f or A to F represent the decimal values from 10 to 15 respectively i.e., a=10, b=11, c=12, d=13, e=14 and f=15 Valid hexadecimal integer constants: 0x0 0x1a 0x1BEC 0x7FFF Invalid hexadecimal integer constants �0x16.8b Illegal character ( . ) �563c Does not begin with 0 or 0x �0x7bcg Illegal character ( g ) �0x12.53 Illegal character ( . ) Floating Point Constants These constants are also called as ‘real constants’. The real constant can be written in two forms namely factorial form and exponential form. If the value of the constant is either too small or too large the exponential form is used. Example: The number 1.5 x 10 -3 can be written as 1.5 E -3 or 1.5 e -3. This is equivalent to 0.15e-2 or 15e-4. etc., In the exponential form the part of the constant before ‘e’ is called exponent. Example: 3.5 e + 5 3.5 - Mantissa part +5 - Exponent part The rules for constructing real constants are as follows. (i) Must have at least one digit (ii) Must have decimal point (iii) Can be either positive or negative (iv) Default sign is positive (v) No comma’s or blanks are allowed with in a constant (vi) The range of real constant expressed in exponential form is 3.4 e+ 38 to 3.4 e -38
  • 11.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 11 Valid Real Constants Some examples of valid real constants are given below. 0.01, 1.5, 825.053, 12E8, 12e8, 12e+8,12e-8, 0.65E-3 Invalid real constants �1,000.0 illegal character ( . ) 53e10.3 exponent must be integer cot can’t contain a decimal point. �13 E 15 illegal character (blank space) in exponent part. Character Constants A character constant is a single alphabet a single digit or a single special symbol enclosed in apostrophes. Some character constants and their corresponding ASCII values. Constant Value ‘A’ 65 ‘b’ 98 ‘3’ 51 ‘ ’ (blank space) 32 String Constants String constants consist of any number of consecutive characters enclosed in (double) quotation marks. Some example string constants “green” “Rs95.50” “Hi n How are n you” “ ”(empty string) The string “Hi n How are n You” is printed as Hi How are You ? Basic Data Types C supports five fundamental data types: Character, Integer, Floating-Point, Double floating- Point, and valueless. These are denoted as char, int, float, double, void, respectively, ’void’ is typically used to declare as function as retuning null value. This issue is discussed in subsequent chapters. The following table given details about fundamental data types.
  • 12.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 12 Classification of Datatypes Basic Data Types Modifiers to Basic Data Types Modifiers are used to alter the meaning of basic data types to fit various needs. Except the type void, all others data type can have various modifiers preceding them List of modifiers used in C are: i) Signed ii) Unsigned iii) Long iv) Short
  • 13.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 13 Modifiers and their memory requirements Operators in C C has a large number of built in operators. An operator is a symbol which acts on operands to produce certain result as output. The data items on which operators act upon are called ‘operands’ For example expression : a+b; In the above expression + is an operator, a and b are operands. The operators are fundamental to any mathematical computations. 1. Based on the number of operands the operator acts upon, Operators can be classified as follows: a. Unary operators: acts on a single operand. For example: unary minus(-5, -20, etc), address of operator (&a) b. Binary operators: acts on two operands. Ex: +, -, %, /, *, etc c. Ternary operator: acts on three operands. The symbol ?: is called ternary operator in C language. Usage: big= a>b?a:b; i.e if a>b, then big=a else big=b. 2. Based on the functions, operators can be classified as given below
  • 14.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 14 Arithmetic Operators Arithmetic operators are used to perform numerical operators in C. They are divided into two classes namely, Unary and Binary arithmetic operators. Unary operators: Operators Actions - Unary minus ++ Increment -- Decrement Binary operators: Operator Action + Addition - Subtraction * Multiplication / Division % Modules Unary Minus ( - ) This symbol is used to indicate the negative sign of the value. Example a = -10; b = -a; Here the value -10 is assigned to a and the value-a to b. Increment and decrement operator The increment operator ( ++ ) adds 1 to its operand and decrement operator ( -- ) subtracts one from its operand Example
  • 15.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 15 Y = y + 1 Is written as Y = y ++ These are two types of increment and decrement operators. They are a. Prefix increment (++ i) In the prefix increment, first increment and then do operation . b. Postfix increment (i ++) In postfix increment, first do the operation and then increment. c. Postfix decrement (--i) In prefix decrement first decrement and then do operation. d. Postfix decrement (i --) In postfix decrement, first do the operation and then decrement. Let the integer variable ‘ i ’ is variable one. Ex. int i= 1; Print f (“ i = %d n”, i); Print f (“ i = %d n”, ++i); //prefix increment Print f (“ i = %d /n”, i); Output i = 1 i = 2 i = 3 Example Program for Arithmetic operations using switch case. # include <stdio.h> # include <conio.h> void main() { int a,b; char ch; clrscr(); printf("nEnter two numbers:"); scanf("%d%d",&a,&b); printf("n1.Addition(+) n
  • 16.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 16 2.Subtraction(-) n3.Multiplication(*)n4.Division(/)n5.Modulus(%)"); printf("nEnter the operator:"); ch=getche(); switch(ch) { case '+': printf("Addition=%d",a+b); break; case '-': printf("Subtraction=%d",a-b); break; case '*': printf("Multiplication=%d",a*b); break; case '/': printf("Division=%d",a/b); break; case '%': printf("Mod=%d",a%b); break; default : printf("nInvalid choice"); } getch(); } Output: Enter two numbers : 3 4 Enter the operator : +
  • 17.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 17 Addition=7 Relational Operators Relational operators logically compare the values, according to condition given in the program. If the condition is satisfied, this results in ‘true’ state otherwise ‘false’ state. True is represented by integer value 1 and false is represented by integer value 0. Operator Meaning of Operator Example == Equal to 5==3 returns false (0) > Greater than 5>3 returns true (1) < Less than 5<3 returns false (0) != Not equal to 5!=3 returns true(1) >= Greater than or equal to 5>=3 returns true (1) <= Less than or equal to 5<=3 return false (0) Relational Operators The associatively of these operators is from left to right. The following are the two equality operators associated with the relational operators. Logical Operators In logical operation the operands are themselves logical. The individual logical expression is compared, using logical operators. The result evaluates which is represented by integer values 0 or 1. C has three types of logical operators. ● Logical AND evaluates to true condition only if both of the operands are true. ● Logical OR evaluates to true condition if any one of the condition is true. ● Logical NOT can change the false to true or from true to false. Operator Meaning of Operator Example
  • 18.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 18 && Logial AND If c=5 and d=2 then,((c==5) && (d>5)) returns false. || Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true. ! Logical NOT If c=5 then, !(c==5) returns false. Logical Operators Assignment Operators ⚫ The operand that appears towards the left side of an assignment operator should have a modifiable l-value, otherwise there will be a compilation error “L-value required”. ⚫ There should be no white space character between two symbols of short-hand assignment operators. ⚫ If two operands of an assignment operator are of different types, the type of operand on the right side of assignment operator is automatically converted to the type of operand present on its left side. Operator Example Same as = a=b a=b += a+=b a=a+b -= a-=b a=a-b *= a*=b a=a*b /= a/=b a=a/b %= a%=b a=a%b Assignment Operators Bitwise Operators ● Bitwise operators operate on the individual bits of operands and are used for bit manipulation. ● They can only be applied on operands of type char, short, int, long, whether signed or unsigned. ● The bitwise NOT operator results in 1’s complement of its operand.
  • 19.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 19 ● Left shift by one bit is equivalent to multiplication by 2. Left shift by n bits is equivalent to multiplication by 2n , provided the magnitude does not overflow. ● Right shift by one bit is equivalent to an integer division by 2. Right shift by n bits is equivalent to integer division by 2n . Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left >> Shift right Bitwise Operators Special Operators There are two special operators available in C language i) sizeof Operator ii) Conditional Operator Sizeof Operator The general form of sizeof operator is: a) sizeof expression or sizeof (expression) (For example: sizeof 2, sizeof(a), sizeof(2+3)) b) sizeof (type-name) (For example: sizeof(int), sizeof(int*), sizeof(char)) Example Program using sizeof() #include<stdio.h> main() {
  • 20.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 20 int a=1,b; b=sizeof(++a); printf(“Resultant values of a and b are:n”); printf(“%d %d”,a ,b); } Output: Resultant values of a and b are: 1 2 Conditional Operator C has special operator called ternary or conditional operator. It uses three expressions. The general format of conditional operator is given below. Expression 1 ? Expression 2 : Expression 3 Evaluation of expression 1 is done logically.Hence it results either in true (i.e. value = 1) or in false (I.e. value = 0) condition. If expression 1 results in true condition then expression 2 is evaluated this becomes the value of expression 1. If expression 1 results in false condition, then expression 3 is evaluated and this value is assigned to expression 1. For example: c=(c>0)?10:-10; If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10. Address-of Operator 1. The syntax of using address-of operator is: & operand 2. The operand of the address-of operator must be a variable or a function designator. The address of operator cannot be applied to constants, expressions, bit-fields and to the variables declared with register storage class. Precedence of Operators The operators have the following precedence. Precedence Operator category Operators
  • 21.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 21 1 unary operators - ++ ! sizeof (type) 2 arithmetic multiply, divide and remainder * / % 3 arithmetic add and subtract + - 4 relational operators < <= > >= 5 equality operators != 6 logical and && 7 logical or || 8 conditional operator ? : 9 assignment operators = += -= %= /= *= Managing Input and Output operations In c language input and output functions are accomplished through library function. The header file for I/O function is <stdio.h>. In C there are two types of I/O functions. They are console I/O and file I/O. Console I/ o function takes I/P from keyboard and produces o/p on the screen. The console Input / Output functions are also called as Standard input / output functions. Classification: The console I / O function are classified as shown below. Formatted I / O Functions Formatted I / O means reading and writing data in formats which are desired by the user. The function used to input action is scanf() and output action is printf().
  • 22.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 22 Output Function The printf() Function printf() is used to print or display data on the console in a formatted form. The format of printf() is printf( “control string”, list of arguments); Control string contains the formatting instructions within quotes. This can contain (i) characters that are simply printed as they are (ii) Conversion specifications with begins with format specifier (%) sign. (iii) Escape sequences. Format Specifier Arguments values get substituted in the place of appropriate format specifications. Arguments can be variables, constants, arrays or complex expressions. The percentage (%) followed by conversion character is called format specifier. This indicates the type of the corresponding data item.Format specifier Meaning %d or %i decimal integers %u unsigned decimal integer %x unsigned hexadecimal (lower case letter) %X unsigned hexadecimal (upper case letter) %o octal %c character %f floating point %s strings %lf double %ld long signed integer %lu long unsigned integer %p displays pointer %% prints a % sign %e scientific notation (e lower case) %E scientific notation (e upper case) Application of printf() Function The printf() function is used to print the different types of output. Escape Sequence
  • 23.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 23 In addition to format specification, escape sequence can also be used in printf(). These are specified in the control string portion of the printf() and are used mainly for screen formatting. All escape sequence provided with slash ( / ). Since back slash is considered as an “escape” character. These sequences are called escape sequences. These sequences cause an escape from the normal interpretation of a string. So that the next character (after blank slash) is recognized as having a special meaning. ● t moves the cursor to next tab problem ● n makes the a cursor to go to new line. ● r moves the cursor to the beginning of the line in which it is currently placed. ● a alters the user by sounding the inbuilt speaker of system. ● b moves the cursor one position to the left of its current opposition. ● The character of single quote and back slash can be printed by using escape sequence ’, ”, respectively. Example: (i) printf(“Teacher asked, ” did you understand ?” ”); This will print Teacher asked, “did you understand?” (ii) printf(“The sequence is a<b, where ’b’ is > 0”); This will print The sequence is a<b, where ‘b’ is >0 (iii) printf(“Hi,n How are n You?”); This will print Hi How are You? Minimum Field Width Specifier (MFWS) The following example demonstrates the working of minimum field width specifier. For Example :
  • 24.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 24 Double count; Count = 10.51324; // here total digits are 8, includes dot ( . ) printf (“ %f” , count); printf (“ %10f” , count); printf (“ %010f” , count); Output 10.51324 10.51324 // inserts 2 blank spaces. So that total length = 10 digits 0010.51324 // inserts 2 zeros. So that total length = 10 digits Input Function The scanf() Function The scanf() reads the input data from standard input device(i.e.keyboard). The general format of the scanf() function is scanf( “format string” list of arguments ); where format string consists of format specifiers and arguments consists of address of variables. To this corresponding address the data read from keyboard is sent. The address of the variable is denoted by ampersand symbol ‘&’ (it is called as ‘’address of the operator). For Example (i) To read integer data: int i ; scanf(“%d”, &i); (ii) To read floating point data: floatf; scanf(“%f”, &f); (iii) To read character data; char sam, john; scanf(“%c”, &sam, &john); (vii) To read more than one data types at a time
  • 25.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 25 int i; float b; char c; string s; scanf(“%d %f %c %s”, &i, &b, &c, &s ); Unformatted I / O Function A simple reading of data from keyboard and writing to I / O device, without any format is called unformatted I / O functions. This can be classified as string I / O and character I /O. Character Input/Output(I/O) In order to read and output a single character character I / O functions are used. The functions under character I / O are ● getchar() ● putchar() ● getch() ● getche() The getchar( ) function The getchar function is a part of the standard C I/O library. It returns a single character from a standard input device typically a keyboard. Drawback with getchar() is that buffers the input until ‘ENTER’ key is pressed. This means that getchar does not see the characters until the user presses return.This is called line buffered input. int i, j; char a, b; j = getchar(); // I / O int data type into j a = getchar(); // I / O char data type into a putchar(i); putchar(b); Output a d
  • 26.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 26 Alternatives to getchar() The two common alternative functions to getchar() are ● getch() ● getche() The getch() function reads a single character at a time and it waits for key press. It does not echo the character on the screen. The getche() is same as getch()/ but the key is echoed. This is illustrated below. char ch; ch = getch() // let key press = k putchar(ch); String I / O In order to read and write string of characters the functions gets() and puts() are used gets() function reads the string and puts() function takes the string as argument and writes on the screen. This is illustrated below char name [50]; puts (“Enter your name”); gets (name); puts(“ The name entered is “) Output: Enter your name: Fredric /* string as entered by user*/ The name entered is: Fredric Introduction to looping and branching In most of C programs that are encountered so far, the instructions appeared in serial fashions. In reality C program requires a logical test to be carried at some point in the program depending upon the outcome of the logical test, one of several possible actions can be carried out. This is called branching. The branching structure which controls the program flow is called control structure. The classification of control structures is given below.
  • 27.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 27 Conditional control Statements The if – else statement It contains a condition. It is logically evaluated. If it evaluates to TRUE condition, then statements under if part is executed. If the condition evaluates to FALSE state then statements under else part is executed. Else clause is optional. The statement under if or else part can be single or multiple statements. If multiple statements are used, they must be embraced with the braces. The syntax of if One way Branching If statetment Two Way Branching If….else statement Multi way Branching If..else if ladder Nested If Switch Case Looping or Iterative Statements Decision Statements CONTROL STRUCTURES for statement while statement do ..while statement Unconditional control Structure Conditional control structure Break Continue Goto
  • 28.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 28 – else statement is given here. Syntax: i) Simple if statement if(expression) Statement; else Statement; /* else part is optional*/ ii) if – else Statement if (expression) { Statement1; Statement2; . . . Statement n; } else { Statement1; Statement2; . . . Statement n; } Some valid forms of if are given below (i) if (x > 0) printf( “%i”, x); (ii) if (a > b) printf( “ a is greatest ”); else printf( “ b is greatest ”); (iii) if ( a = = b ) { printf( “ a & b are equal ” ) printf( “ x/a is equal to x/b ” ) } Some invalid forms of if are given below (i) if ( a > b ); printf( “a is greatest” ) The semicolon at the end of condition, makes if (a>b) as invalid.
  • 29.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 29 (ii) if ( a > b ) statement1; statement2; statement3; Here multiple statements under if are not enclosed in braces. (iii) if ( a > b ) { Statement 1; statement 2; . . . Statement n; }; Here the ending brace has semicolon ( ; ) Examples for if….else: Example 1 Write a program to calculate greatest of 3 numbers. /* Write a program to calculate greatest of 3 numbers */ # include <stdio.h> main() { int a, b, c; printf(“Enter three numbers”); scanf (“ %d %d %d “, &a, &b, &c); if ( ( a > b) && (a > c)) printf (“n a is greatest”); if ( ( b > a) & & (b > c)) print f (“n b is greatest”); if ( ( c > a) & & (c > b)) print f (“n c is greatest”); } Example 2 Write a program to check a given number is odd or even. /* program to check given number is either odd or even*/ # include <stdio.h> main()
  • 30.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 30 { int a; printf(“Enter the number to bechecked”); scanf (“ %d” , &a); if ( (a%2) = = 0) printf(“The given number is even”); else printf(“The given number is odd”); } The final else is associated with if (a) and not associated with if c, because it is not in the same block. Nested if...else statement (if...elseif....else Statement) The if...else statement can be used in nested form when a serious decision are involved. Syntax of nested if...else statement. Nested if Statement Syntax: If(condition1) { If(condition2) { If(condition3) { statement 3; } else statement 2; } else statement 1; } else statement 0; How nested if...else works? If the test expression is true, it will execute the code before else part but, if it is false, the control of the program jumps to the else part and check test expression 1 and the process continues. If all the test expression are false then, the last statement is executed.
  • 31.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 31 Example of nested if else statement: Write a C program to check the given two integers are =to or > or < . #include <stdio.h> int main(){ int numb1, numb2; printf("Enter two integers to check".n); scanf("%d %d",&numb1,&numb2); if(numb1==numb2) //checking whether two integers are equal. printf("Result: %d=%d",numb1,numb2); else if(numb1>numb2) //checking whether numb1 is greater than numb2. printf("Result: %d>%d",numb1,numb2); else printf("Result: %d>%d",numb2,numb1); return 0; } Output Enter two integers to check. 5 3 Result: 5>3 if -else - if Ladder A common programming construction is the if-else-if staircase because of its appearance. The general form is if ( expression ) Statement: else if ( expression ) Statement: else if ( expression ) Statement: . . . else Statement; The condition are evaluated from top, towards down. As soon as a true condition is found, the statement
  • 32.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 32 associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is executed. If final else is not present, no action taken place if all other conditions are false. This is given in the below example # include <stdio.h> main() { int i; i = 0; clrscr(); printf(“Enter your choice (1-4);”); scanf (“ %d” , & i); if ( i == 1) printf(“n your choice is 1”); else if ( i = = 2) printf(“n your choice is 2”); else if ( i = = 3) printf(“n your choice is 3”); else if ( i = = 4) printf(“n your choice is 4”); else printf(“n invalid choice”); } Output: Enter your choice (1-4): 2 Your choice is 2. Explanation: here the second condition ( i ==2) is true. Hence the following printf() is executed and control will come out of loop. If none of the conditions is satisfied then final the statement is executed. Switch Statement C has a multiple branch selection statements called switch. It tests the value of an expression against a list of integer or character constants. When a match is found the statements associated with that constants are executed. The general format of switch is switch (expression)
  • 33.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 33 { case constant1: Statement sequence break; case constant2: Statement sequence break; case constant3: Statement sequence break; . . . default: Statement sequence } Switch, case and default are key words and statement sequence can be single statement or a compound statement. If it is compound statement it must be enclosed in braces. In case expression such as case constant1, case constant2, case constant3, . etc the word constant 1 is called case labels or case prefixes. The case label can either be integer or character constant. Each case label must be distinct. If none of the cases are satisfied, the default statement is executed. The default statement is optional. If none of the case are satisfied and default case is also not present, then no action takes place. To understand the functioning of switch-case statement a few programs are given below. Example 1 write a program to check whether the enter the character is a vowel, a last alphabet or consonant # include <stdio.h> main() { char ch() printf(“n Enter a lower case alphabeet (a-z);”); scanf (“ %d” , & ch); if ( ch<’a’ || ch>’z’) printf(“n Character is not lower case alphabet”); else switch (ch) { case ‘a’ : case ‘e’ : case ‘i’ : case ‘o’ : case ‘u’ : printf(“n Entered Character is vowel”);
  • 34.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 34 break; case ‘z’ : printf(“n Entered Character is last alphabet”); break; default; printf(“n Entered Character is consonant”); } } Output: Enter a lower case alphabet ( a – z ): p entered character is consonant. Explanation: each case need not have its own statements. A set of case can have common statements to be executed. This is as shown in the above program. The default can either end with break or not. This depends upon program structure. Difference Between if Statement and Switch Statement No. If statement Switch statement 1 It checks whether the condition is true or false It is multi-way decision statement 2 It contains the condition which will evaluates to true or false It contains the variable whose value is to be checked 3 It supports all types of conditions It supports checking only integer and character values 4 Syntax: if(condition) { //statements } else { //statements } Syntax: switch(variable) { case value1: break; case value2: break; default: break; LOOPING Loops
  • 35.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 35 In the programming often there is a need to perform an action over and over ie repeatedly, often with variations in the details each time we repeat. This repetitive operation is done through the control structure called loop or iteration. There are three types of looping, namely: 1. for loop 2. while loop 3. do-while loop The for loop A for loop is a block of code that iterates a list of commands as long as the loop control condition is true. The syntax of for loop is for(initialization;Test condition;loop expression) statement sequence Syntax explanation: (1) Initialization: This is some kind of expression which initializes the control variable or (index varaible) This statement is carried out only once before the start of the loop. e.g. i = 0; (2) Condition: The condition is evaluated at the beginning of every loop and the loop is only carried out while this expression is true. e.g. i < 20; (3) Loop expression This is some kind of expression for altering the value of the control variable. This expression is evaluated at the end of each iteration. In C it can be absolutely anything. e.g. i++ or i *= 20 or i /= 2.3 ... (4) Statement sequence Statement sequence can consist only one statement or a group of statements. If it contains a group of statements, they must be embraced in braces({}).If it contains only one statement , braces need not be enclosed.
  • 36.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 36 Simple programs using for loop is given below 1. Write a program to print a word hello five times using for loop. /* A program to print hello five times */ #include<stdio.h> int main() { int i; for(i=0; i<5; i++) printf("Hello n"); } Output: Hello Hello Hello Hello Hello Example 2: Write a program to convert 0 through 15integers to hex numbers #include <stdio.h> main() { int i; printf("Hex(uppercase)t Hex(lowercase)t Decimaln"); for (i=0; i<16; i++) printf("%Xt %xt %dn", i, i, i); } Output: Hex(uppercas e) Hex(lowercase) Decimal 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 A a 10 B b 11 C c 12 D d 13 E e 14
  • 37.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 37 F f 15 The Comma Operator in The for Loop The comma (,) operator is basically used in conjunction with for loop statement. This permits two expressions to be used in initialization and count section of the for loop. Only one test expression is allowed in the for loop. The syntax of this is given below for (expression1a, expression1b; expression2; expression3a, expression3b) Here expression 1a and expression 1b and expression 3a expression 3b are separated comma operator. For example consider the below for statement for(i=0,j=2;j<=0;j-- ,i++) Here i and j are the two different variables used and they are separated by comma operator. Operation of this is given in the below example: #include <stdio.h> main() { int i, j; for (i=0, j=1; i<8; i++, j++) printf("%d - %d = %dn", j, i, j - i); } Output: 1 - 0 = 1 2 - 1 = 1 3 - 2 = 1 4 - 3 = 1 5 - 4 = 1 6 - 5 = 1 7 - 6 = 1 8 - 7 = 1 The Nested for Loop The concept of using a loop within a loop is called nested loop. If a for loop contains another for loop statement, such loop is called nested for loop.. SYNTAX:-
  • 38.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 38 for (initializing ; test condition ; increment / decrement) { statement; for (initializing ; test condition ; increment / decrement) { body of inner loop; } statement; } Example : C program to evaluate the following series 1+1/1!+1/2!+1/3!+1/4!..... #include <stdio.h> void main() { double sum=0,fact=1; int n, i,j; clrscr(); printf("Enter the number ‘n’ to calculate s= 1+1/2!+1/3!......1/n "); scanf("%d", &n); for (i=1;i<=n;i++) { fact=1; for(j=1;j<=i;j++) { fact=fact*j; } sum=sum+(1/(fact)); } printf("Sum : %f",sum); getch(); }
  • 39.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 39 While Loop The simplest of the three loops is the while loop.The while-loop has a condition and the statements .The syntax is given below. while (condition) { statements; } The condition expression (something like (a > b) etc...) is evaluated first. If the expression evaluates to True state i.e returns a nonzero value (normally 1) the looping continues; that is, the statements inside the statement block are executed. After the execution, the expression is evaluated again. The statements are then executed one more time if the expression still returns nonzero value. The process is repeated over and over until the expression returns 0(False state). The statement block, surround by the braces { and }.If there is only one statement in the statement block, the braces can be discarded. Consider an example of using the while statement. 1) Write a program to understand the use of while loop. #include <stdio.h> main() { int a; printf("Enter a character:n(enter x to exit)n"); while (a != `x') { a = getc(stdin); putchar(a); printf("n"); } printf("nOut of the while loop. Bye!n"); } Output: Enter a character: (enter x to exit) i H x x Out of the while loop. Bye! Do-while Loop The while and for loops test the termination condition at the beginning of the loop. By contrast, the do-while
  • 40.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 40 loop, tests at the bottom after making each pass through the loop body; the body is always executed at least once. The syntax of the do .. while is do statement while (expression); First the statement is executed under the do clause, then expression in the while is evaluated. If it is true, statement is executed and again the while is evaluated and this looping process continues. When the expression becomes false, the loop terminates. The do-while is much less used than while and for. If the statement contains a set of statements, they must be enclosed in the braces .consider the example to understand the working of while-do loop. 1) Write a program to illustrate the working of do-while loop #include<stdio.h> int main(void) { int pass-word= 15; int code; int i=3; do { printf("Type the password to enter.n"); scanf("%d", &code); if (code==15) printf("Right code. You can Entern"); else printf(“Wrong Entry”); i=i-1; }while(i!=0); } Output: 13 Wrong Entry 15 Right Code. You can Enter. In Do-while, the loop the is executed as least once before checking the validity condition. In Do-while structure entry to the loop is automatic (even with invalid input).Choice is given only for the continuation of the loop. Such problems are deemed to be lack of control Difference Between while & Do .. while Statement S.No While loop do-while loop
  • 41.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 41 1. In while loop a condition is evaluated at the beginning of the loop. In do-while loop a condition is evaluated at the end of the loop. 2. A body of the loop is not be executed when the value of the condition is false. The body of the loop will not be executed when the value of the condition s false. But the loop is executed at least once even the condition is false. Unconditional control Statements Break Statement The break statement is used to terminate loops or to exit from a switch. It is used within loop structures namely for, while, do-while and switch statement. The syntax of break statement is break; Break Statement Within Loops A break within a loop is generally protected within an if statement. This provides control towards the exit condition. This depicted in the below example. Example: Write a program to illustrate the functioning of break statement inside a for loop. #inlude <stdio.h> int main() { int i; for (i = 1; i < 10; i++) { printf_s("%dn", i); if (i == 4) break; } } Output 1 2 3 4 Continue Statement Instead of breaking a loop, a need to stay in the loop but skip over some statements within the loop may occur. To do this, the continue statement is used. The continue statement takes the control to the beginning of the loop bypassing the statements inside the loop which have not yet been executed. The continue statement can
  • 42.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 42 only be used within the body of a while, do, or for statement. For better control over the program, like a break statement, continue is generally used in conjunction with if structure within loops. When continue is used the next iteration of a do, for, or while statement is determined as follows: Syntax: while (<expression>) { ... if (<condition>) continue; ... ... // control jumps here on the continue } Example 1 : Write a program to find the sum Using the continue statement in for loop. #include <stdio.h> main() { int i, sum; sum = 0; for (i=1; i<8; i++) { if ((i==3) || (i==5)) continue; sum += i; } printf("The sum of 1, 2, 4, 6, and 7 is: %dn", sum); } Output The sum of 1, 2, 4, 6, and 7 is: 20 Example 2: Write a program to find the odd numbers using continue statement in while loop. /* a program to find the odd numbers using continue statement*/ #include <stdio.h> main () { Int x; x = 0; while (x < 10)
  • 43.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 43 { ++x; if (x % 2 == 0) { continue; } printf ("%i is an odd number.n", x); } Output 1 is an odd number. 3 is an odd number. 5 is an odd number. 7 is an odd number. 9 is an odd number. Goto and Labels A goto statement causes an unconditional branching of the program to the statement associated with the label specified on the goto statement. A label has the same form as a variable name, and is followed by a colon. The scope of a label is the entire function. Label name must be unique for that program .Any number of goto labels can be used inside the program, provided each one of them is distinct. Format of goto statement is given below. Syntax: for ( ... ) statement for ( ... ) { ... if (disaster) goto label name ; } Write a program to understand the functioning of the goto statement. #include <stdio.h> int main() { int i, j; for ( i = 0; i < 10; i++ ) { printf( "Outer loop executing. i = %dn", i );
  • 44.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 44 for ( j = 1; j < 3; j++ ) { printf( " Inner loop executing. j = %dn", j ); if ( i == 2 ) goto stop; } } printf( "Loop is quit. i = %dn", i ); stop: printf( "Jumped to stop. i = %dn", i ); } Output: Outer loop executing. i =0 Inner loop executing. j =1 Outer loop executing. i =1 Inner loop executing. j =2 Outer loop executing. i =2 Inner loop executing. j =1 Jumped to stop. I=2 this example, a goto statement transfers control to the point labeled stop when i equals 2. 2.11. Simple Scientific and Statistical Problems in C Program: To find Area and Circumference of the Circle #include<stdio.h> #include<conio.h> void main() { float r,Area,Circumference; clrscr(); printf("nnEnter the Radius of Circle : "); scanf("%f",&r); Area = 3.14 * r * r; Circumference = 2 * 3.14 * r; printf("nnThe Area of the Circle = %.2f",Area); printf("nnThe Circumference of the Circle = %.2f",Circumference); getch();
  • 45.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 45 } Input / Output: Enter the radius of the circle : 2.5 Area of Circle is : 19. 62 Circumference of the Circle : 15.70 Program: To Calculate Simple Interest #include<stdio.h> #include<conio.h> int main() { float p,rate,years,si; clrscr(); printf("Enter Principal amount : "); scanf("%f", &p); printf("Enter Number of Years : "); scanf("%f", &Year); printf("Enter Rate of interest : "); scanf("%f", &rate); si=(p*time*rate)/100; printf("n Simple Interest = %2f",si); getch(); return 0; } Input / Output: Enter Principal Amount : 1000 Enter Number of Years : 3 Enter Rate of Interest : 2.5 Simple Interest = Rs. 75.00 Program: To find the given year is leap or not #include<stdio.h> #include<conio.h> void main()
  • 46.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 46 { int n; clrscr(); printf("nEnter the year:"); scanf("%d",&n); if((n%400==0)||((n%4==0)&&(n%100!=0))) printf("Leap Year"); else printf("Not a Leap Year"); getch(); } Input / Output: Enter the year: 2000 The given year 2000 is a leap year Enter the year: 1900 The given year 1900 is not a leap year Program: To find the Quadratic Equation #include<stdio.h> #include<math.h> #include<conio.h> void main() { float a,b,c,d; float root1,root2; clrscr(); printf("nnEnter the value of a : "); scanf("%f",&a); printf("nnEnter the value of b : "); scanf("%f",&b); printf("nnEnter the value of c : "); scanf("%f",&c); d = b * b - 4 * a * c;
  • 47.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 47 if( d >= 0 ) { root1 = (-b + sqrt (d)) / (2 * a); root2 = (-b - sqrt (d)) / (2 * a); printf("nThe Root1 is : %.2f",root1); printf("nThe Root2 is : %.2f",root2); } else { printf("nnThe Roots are Imaginary"); } getch(); } Input / Output: Enter the value of a: 1 Enter the value of b: 0 Enter the value of c: -9 The roots of the values a=1 b=0 c = -9 are 3.000000 and 3.000000 Program: to calculate the Celsius to Fahrenheit, Newtons Law of Force, Voltage Calculation, Energy Calculation, Capacitance Calculation #include<stdio.h> #include<stdlib.h> #include<conio.h> void main() { float Celsius, Fahrenheit; float mass_of_the_object, acceleration_of_the_object,Force; float V,I,R; float E,L; float C; int choice = 1;
  • 48.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 48 clrscr(); while(choice < 6) { printf("nn1. Celsius To Fahrenheit"); printf("n2. Newtons Law of Force"); printf("n3. Voltage Calculation"); printf("n4. Energy Calculation"); printf("n5. Capacitance Calculation"); printf("n6. Exit"); printf("nEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1 : printf("nEnter the Celsius Value : "); scanf("%f",&Celsius); Fahrenheit = (1.8 * Celsius) + 32; printf("nThe Fahrenheit Value of %.2f Celsius is : %.2f",Celsius,Fahrenheit); break; case 2: printf("nEnter the value of Mass of the Object : "); scanf("%f",&mass_of_the_object); printf("nEnter the value of Acceleration of the Object : "); scanf("%f",&acceleration_of_the_object); Force = mass_of_the_object * acceleration_of_the_object; printf("nThe Force value is : %.2f",Force); break; case 3: printf("nEnter the Resistance value (in ohms) : "); scanf("%f",&R); printf("nEnter the Current Value (in amps) : "); scanf("%f",&I); V = I * R; printf("nThe Volts value is : %.2f volts",V);
  • 49.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 49 break; case 4: printf("nEnter the Inductance Value (in Henry) : "); scanf("%f",&L); printf("nEnter the Current Value (in amps) : "); scanf("%f",&I); E = L * I * I / 2; printf("nThe Energy Value is : %.2f Joules",E); break; case 5: printf("nEnter the Energy Value (in joules) : "); scanf("%f",&E); printf("nEnter the Voltage Value (in volts) : "); scanf("%f",&V); C = 2 * E / ( V * V ); printf("nThe Capacitance Value is : %.2f farad",C); break; case 6: exit(0); } } getch(); } Input / Output: 1. Celsius To Fahrenheit 2. Newtons Law of Force 3. Voltage Calculation 4. Energy Calculation 5. Capacitance Calculation Enter your choice: 1
  • 50.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 50 Enter the Celsius Value: 45 The Fahrenheit of the given Celsius 45.00 is 113.00 ARRAY BASICS Array is a simple data structure which can store collection of elements of same data type. All elements are stored in the contiguous memory. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array, a programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement: double balance[10]; Now balance is avariable array which is sufficient to hold up to 10 double numbers. Initializing Arrays You can initialize array either one by one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single
  • 51.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 51 element of the array: If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th ie. last element because all arrays have 0 as the index of their first element which is also called base index. Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example: double salary = balance[9]; The above statement will take 10th element from the array and assign the value to salary variable. e.g. #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ }
  • 52.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 52 for (j = 0; j < 10; j++ ) { printf("Element[%d] = %dn", j, n[j] ); } return 0; } When the above code is compiled and executed, it produces the following result: Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 MULTIDIMENSIONAL ARRAYS C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration: type name[size1][size2]...[sizeN]; For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array: int threedim[5][10][4]; TWO-DIMENSIONAL ARRAYS
  • 53.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 53 The simplest form of the multidimensional array is the two-dimensional array. A twodimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y you would write something as follows: type arrayName [ x ][ y ]; Where type can be any valid C data type and arrayName will be a valid C identifier. A two dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimentional array a which contains three rows and four columns can be shown as below: Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a. Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; Accessing Two-Dimensional Array Elements: An element in 2-dimensional array is accessed by using the subscripts ie. row index and column index of the array. For example: int val = a[2][3];
  • 54.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 54 The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array: #include <stdio.h> int main () { /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %dn", i,j, a[i][j] ); } } return 0; } When the above code is compiled and executed, it produces following result: a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4
  • 55.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 55 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 Function A function is a group of statements that together perform a task. Every C program has at least one function, which is main (), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. Functions are of two types:- ● Built in function or Library Functions ● User defined functions Built in functions:- library. Many activities in C are carried out using library functions. These functions perform file access, mathematical computations, graphics, memory management etc. optional list of arguments and header file of used function should be included with the program. C has many built-in functions that you can use in your programs. main( ) printf( ) scanf( ) gets( ) puts( ) strcpy( ) strlen( ) strcmp( ) stricmp( ) strcat( ) strstr( ) isalpha( ) isdigit( ) isupper( ) islower( ) User-Defined Functions:- If you have a special set of instructions that aren’t in a built-in function, you can create a user-defined function. Here are the steps: 1. Give your function a name that isn’t already used in C (by built-in functions, types of variables, keywords, etc.) 2. Create a function header, which contains three things: a. The type of variable (int, char, double, etc.) that the function will produce (return) b. The name of the function, which can be one or more words (but put underscores _ or Capital Letters connecting these words, because no spaces are allowed) c. The parameters of the function, which are the names and types of variables inside your function. A function declaration consist of 4 parts.return-type
  • 56.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 56 ● function name ● parameter list ● terminating semicolon ● Function definition Syntax General syntax of function definition is, return-type function-name (parameter-list) { function-body ; } The first line return-type function-name(parameter) is known as function header and the statement within curly braces is called function body. 1. return- return type specifies the type of value(int,float,char,double) that function is expected to return to the program calling the function. 2. function-name is any valid C identifier and therefore must follow the same rule of formation as other variables in C. 3. parameter-list will receive the data sent by calling program. They often referred to as formal parameters. These parameters are also used to send values to calling program. 4. function- The function body contains the declarations and the statement (algorithm) necessary for performing the required task. The body is enclosed within curly braces { } and consists of three parts. Local variable declaration. Function statement that performs the tasks of the function. A return statement that return the value evaluated by the function. Function Prototypes According the arguments and the returning value, functions are divided into 1) A function with no arguments and no return value 2) A function with no arguments and return a value 3) A function with an argument or arguments and returning no value 4) A function with arguments and returning a value. 1. Function with No Arguments and No Returns a Value ● The function will not get of data from the calling function and also data is not sent back to the called function. ● Here is no data transfer between calling function and called functions. ● The called functions are used to perform any operation. ● They act independently. ● This is used to print some messages. Program: #include<stdio.h> #include<conio.h> void fun(); void main()
  • 57.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 57 { fun(); getch(); } fun() { } printf("hi, this is display from function funct()");
  • 58.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 58 2. Functions with arguments and no return value in C : ● The function where arguments are passed through the calling function. ● The called function operates on the data. ● But the result is not sent. ● The called ones are partly depend on the calling function. ● The result obtained is utilized by the called function only. Program: #include<stdio.h> #include<conio.h> void add(int a,int b); void main() { int a=5,b=4; add(a,b); getch(); } void add(int a, int b) { int c; c=a+b; printf("n Result = %d",c); } 3. Functions with no arguments and return value in C : ● The type function has no arguments. ● The called one function return the value. ● The called function is been independent of calling. Program: #include<stdio.h> #include<conio.h> int add(); void main() { int result; result=add(); printf("n Result = %d",result); getch(); } int add() { int a=5,b=4,c; c=a+b; return c;
  • 59.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 59 }
  • 60.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 60 4.Functions with arguments and return value in C : ● This has arguments as well as return value. ● Both the called and calling function is dependent ● Communication is between both the functions. Program: #include<stdio.h> #include<conio.h> int add(int a,int b); void main() { int a=5,b=4,c; c=add(a,b); printf("n Result = %d",c); getch(); } int add(int x, int y) { int z; z=x+y; return z; } Call by Value and Call by Reference ● Functions communicate with each other by passing the arguments. ● There are two ways of passing the arguments namely, call by value and call by reference. Call by Value ● Whenever a function is called, the values of variables are passed to the called function from calling function. ●Such function calls are called “calls by value”. ● The value of each of the actual arguments in the calling function(function call) is copied into corresponding formal arguments of the called function. ● The function which is called by value can not change the values of actual parameters. Program: void main ( ) { i nt a = 10, b=20; void swap(int a,int b); swap(a,b); printf ("a = % d b = % d", a,b); getch(); }
  • 61.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 61 swap (int x, int y) {
  • 62.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 62 int t; t = x; x = y; y = t; } output : a =10 b =20 Call by Reference ● Second method, the addresses of actual arguments in the calling function are copied in to formal arguments of the called function. ● The values are not passed, the address is been pass. ● Passing the address of a variable to a function is called passing by reference. ● The function which is called by reference can change the values of actual parameters. Example Program: void main ( ) { i nt a = 10, b=20; void swap(int *a,int *b); swap(&a,&b); printf ("a = % d b = % d", a,b); getch(); } void swap (int *x, int *y) { int t; t = *x; *x = *y; *y = *t; } output :a =20 b =10 Recursion A function that calls itself is known as recursive function and this technique is known as recursion in C programming. (OR) Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. (OR) The process of calling a function by itself is called recursion and the function which calls itself is called recursive function.
  • 63.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 63 Syntax of Recursive Function returntype recursive_func ([argument list]) { statements; ... ... ... recursive_func ([actual argument]); ... ... ... } Flowchart of Recursion Example 1: void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); }
  • 64.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 64 How does it Works Example #1: C Program to show infinite recursive function #include<stdio.h> void main() { printf("Hello world"); main(); } In this program, we are calling main() from main() which is recursion. But we haven't defined any condition for the program to exit. Hence this code will print "Hello world" infinitely in the output screen. Example #2: C program to calculate factorial of a number using recursion. Program #include<stdio.h> int factorial(int n) { if(n==0) return 1; else return (factorial(n-1)*n); } int main() { int num,f; printf("Enter a number: "); scanf("%d",&num);
  • 65.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 65 f=factorial(num); printf("Factorial of %d = %d",num,f); return 0; } Here, factorial is calculated using recursion. The formula for calculating factorial of a number n is, n! = 1*2*...(n-1)*n Again, we can see (n-1)! = 1*2*...(n-1) Hence we can write, n! = (n-1)! * n We have implemented this recursive relation in our program. Here, The number whose factorial is to be found is stored in the variable n. A recursive function factorial(num) calculates the factorial of the number. As factorial is (n-1)! * n, factorial function calculates the factorial by recursively multiplying n with factorial of (n-1). Finally, when n = 0, it returns 1 because 0! = 1. Output Enter a number: 7 Factorial of 7 = 5040 Example #3: C program print first n Fibonacci numbers using recursion. #include<stdio.h> int fibo(int num) { if(num==1||num==2) return 1; else return (fibo(num-1)+fibo(num-2)); // recursive call } int main() { int i,n; printf("Enter the required term: "); scanf("%d",&n); printf("First %d fibonacci numbers aren",n); for (i=1; i<=n; i++) printf("%dn",fibo(i));
  • 66.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 66 return 0; }
  • 67.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 67 This program uses recursion to generate Fibonacci series. In a Fibonacci series, nth term can be obtained by adding (n-1)th and (n-2)th term. Mathematically, tn = tn-1 + tn-2 Here, The number of fibonacci terms to be generated is taken from the user and stored in variable n. A for loop is used to loop through the number to be generated which is sent to the function fibo. This function is used to calculate and return fibonacci series. Inside fibo, if the term-number is 1 or 2, it returns 1. This is because, the first two terms of fibonacci series are both 1. The printed values are 1,1. Then the next term-number 3 is passed onto fibo function, since it's not 1 or 2, the next term in the series is calculated by taking fibo(n - 1) + fibo(n - 2), where n = 3. This calculates the last two terms in the fibonacci series. This is equivalent to fibo(2) + fibo(1), which results in 1 + 1 = 2. This recursive loop goes on finally printing the series as 1, 1, 2, 3, 5... Output Enter the required term: 7 First 7 fibonacci numbers are 1 1 2 3 5 8 13 Pointer As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined #include <stdio.h> void main () { int var1; char var2[10]; printf("Address of var1 variable: %xn", &var1 ); printf("Address of var2 variable: %xn", &var2 ); } When the above code is compiled and executed, it produces the following result Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6 What are Pointers? A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to
  • 68.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 68 store any variable address.
  • 69.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 69 A pointer is a variable which contains the address of another variable. We can have a pointer to any variable type. (or) Pointers are variables that hold address of another variable of same data type. ● A normal variable ‘var’ has a memory address of 1001 and holds a value 50. ● A pointer variable has its own address 2047 but stores 1001, which is the address of the variable ‘var’. How to Declare a Pointer? A pointer is declared as : pointer type *pointer-name An example of a pointer declaration can be : int *ptr How to initialize a Pointer? A pointer is initialized in the following way : For example : int a=10; int *ptr; ptr=&a; Program: #include <stdio.h> int main() { int *ptr, q; q = 50; ptr = &q; printf(“%d”, *ptr); return 0; } Output 50 Pointer and Arrays
  • 70.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 70 When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address which gives location of the first element is also allocated by the compiler.
  • 71.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 71 Suppose we declare an array arr, int arr[5]={ 1, 2, 3, 4, 5 }; Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will be stored as follows Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000. We can declare a pointer of type int to point to the array arr. int *p; p = arr; or p = &arr[0]; //both the statements are equivalent. another. Program: int i; int a[5] = {1, 2, 3, 4, 5}; int *p ; p=a; // same as int *p = &a[0] for (i=0; i<5; i++) { printf("%d", *p);//same as *p = &a[0] p++; } Pointer Arithmetic Like any other variables pointer can be used in expressions. Consider below table, We have declared some of the variables and also assumed some address for declared variables. Data Type Initial Address Operation Address after Operations Required Bytes int 4000 ++ 4002 2 arr is equal to &arr[0] // by default
  • 72.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 72 Data Type Initial Address Operation Address after Operations Required Bytes int 4000 - - 3998 2 char 4000 ++ 4001 1 char 4000 - - 3999 1 float 4000 ++ 4004 4 float 4000 - - 3996 4 long 4000 ++ 4004 4 long 4000 - - 3996 4 Pointer Addition In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c programming to add integer to pointer variable. Program include<stdio.h> void main() { double *ptr,*ptr1,a=10; ptr=&a; ptr1=ptr+1; printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr); } Output New Value of ptr and ptr1: 4286714080 4286714082 10 Pointer Subtraction Program include<stdio.h> void main() {
  • 73.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 73 double *ptr,*ptr1,a=10; ptr=&a; ptr1=ptr-1; printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr); } Output New Value of ptr and ptr1 : 4286714080 4286714078 10 Pointer Increment Incrementing a pointer to an integer data will cause its value to be incremented by 2 . Program include<stdio.h> void main() { double *ptr,*ptr1,a=10; ptr=&a; ptr1=ptr++; printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr); } Output New Value of ptr and ptr1: 4286714080 4286714082 10 Pointer Decrement Decrementing a pointer to an integer data will cause its value to be decremented by 2. Program include<stdio.h> void main() { double *ptr,*ptr1,a=10; ptr=&a; ptr1=ptr-1; printf("New Value of ptr : %u n %un %f",ptr,ptr1,*ptr); } Output New Value of ptr and ptr1 : 4286714080 4286714078 10 Comparing two Pointers
  • 74.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 74 1. Pointer comparison is Valid only if the two pointers are Pointing to same array 2. All Relational Operators can be used for comparing pointers of same type 3. All Equality and Inequality Operators can be used with all Pointer types 4. Pointers cannot be Divided or Multiplied #include<stdio.h> Output Ptr2 is far from ptr EXAMPLE PROGRAMS 1.C PROGRAM FOR RECURSIVE FUNCTION TO FIND THE POWER OF A NUMBER. PROGRAM #include <stdio.h> void main() { int base, exp, ans; int power(int base,int exp); printf("Enter base number: "); scanf("%d",&base); printf("Enter power number: "); scanf("%d",&exp); ans=power(base, exp); printf("Result is %d",ans); getch(); } int power(int base,int exp) { if ( exp==1 ) { return base; } else { return (base*power(base,exp-1)); } } 2. C PROGRAM TO FIND THE SUM OF DIGITS USING RECURSIVE FUNCTION. int main() { int *ptr1,*ptr2,a,b; ptr1 = &a; ptr2 = &b; if(ptr2 > ptr1) printf("Ptr2 is far from ptr1"); return(0); }
  • 75.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 75 PROGRAM #include<stdio.h> void main() { int num,s; printf("Enter a number: "); scanf("%d",&num); s=findsum(num); printf("Sum of the digits is %d",s); getch(); } int findsum(int n) { int r,s; if(n>0) { r=n%10; s=s+r; findsum(n/10); } else return s; } 3. C PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER USING FUNCTIONS. (8) Program #include<stdio.h> int fact(int n); void main() { int n; printf("Enter a number to calculate it's factorialn"); scanf("%d",&n); printf("factorial = %d", fact(n)); } int fact(int n) { int i,fact=1; for( i = 1 ; i <= n ; i++ ) fact = fact*i; return (fact);
  • 76.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 76 } 4. C PROGRAM TO PRINT THE FIBONACCI SERIES USING FUNCTIONS. (8) Program #include<stdio.h> #include<conio.h > int fibo(int n); void main() { int n, i; clrscr(); printf("Enter the limit:n"); scanf("%d",&n); i=fibo(n); printf("nThe %dth Fibonacci number is %ld",n,i); getch(); } int fibo(int n) { int sum, i=1, a=0,b=1; while(i<=n) { sum=a+b; a=b; b=sum; i++; printf("n%d",sum); } return(sum); } 5. C PROGRAM USING POINTERS TO READ IN AN ARRAY OF INTEGERS AND PRINT ITS ELEMENTS IN REVERSE ORDER.(8) Program #include<stdio.h> #include<conio.h> #define MAX 30 void main() { int size,i,arr[MAX]; int *ptr; clrscr(); ptr=&arr[0];
  • 77.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 77 printf("Enter the size of array : "); scanf("%d",&size); printf("Enter %d integers into array:n",size); for(i=0;i<size;i++) { scanf("%d",ptr); ptr++; } ptr=&arr[size-1]; printf("Elements of array in reverse order are:n"); for(i=size-1;i>=0;i--) { printf("nElement%d is %d :",i,*ptr); ptr--; } getch(); } Output: Enter the size of array : 5 Enter 5 integers into array : 11 22 33 44 55 Elements of array in reverse order are : Element 4 is : 55 Element 4 is : 44 Element 4 is : 33 Element 4 is : 22 Element 4 is : 11 6. C PROGRAM TO FIND N CR USING RECURSIVE FUNCTION (8) Program #include<stdio.h> int main() { int n,r,ncr; printf("Enter any two numbers->"); scanf("%d %d",&n,&r); ncr=fact(n)/(fact(r)*fact(n-r)); printf("The NCR factor of %d and %d is %d",n,r,ncr); return 0; } int fact(int n) { int i=1; while(n!=0)
  • 78.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 78 { i=i*n; n--; } return i;}
  • 79.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 79 Structure Definition element in a C structure is called member. Need for structured data type To store heterogenous values (different data types) Points about structure 1. As we know that Array is collection of the elements of same type , but many time we have to store the elements of the different data types. 2. Suppose Student record is to be stored , then for storing the record we have to group together all the information such as Roll,name,Percent which may be of different data types. 3. Ideally Structure is collection of different variables under single name. 4. Basically Structure is for storing the complicated data. 5. A structure is a convenient way of grouping several pieces of related information together. Definition of Structure in C: Struct keyword is used to define a structure. Struct define a new data type which is a collection of different type of data. Syntax : struct <structure_name> { structure_Element1; structure_Element2; structure_Element3; ... ... }; Example:
  • 80.
    191GES205T -PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 30 struct stu { char name[64]; char course[128]; int age; int year; } student;
  • 81.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 Declaring Structure Variables It is possible to declare variables of a structure, after the structure is defined. Structure variable declaration is similar to the declaration of variables of any other data types. Structure variables can be declared in following two ways. 1) Declaring Structure variables separately struct student { char[20] name; int age; int rollno; } ; struct student S1 , S2; //declaring variables of Student 2) Declaring Structure Variables with Structure definition struct student { char[20] name; int age; int rollno; } S1, S2 ; Here S1 and S2 are variables of structure Student. Accessing Structure Members To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type. Example: This program is used to store and access “id, name and percentage” for one student. We can also store and access these data for many students using array of structures. #include <stdio.h> #include <string.h> struct
  • 82.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 student { int id; char name[20]; float percentag e; }; void main() { struct student record = {0}; //Initializing to null record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d n", record.id); printf(" Name is: %s n", record.name); printf(" Percentage is: %f n", record.percentage); getch(); } ANOTHER WAY OF DECLARING C STRUCTURE: In this program, structure variable “record” is declared while declaring structure itself. In above structure example program, structure variable “struct student record” is declared inside main function which is after declaring structure. #include <stdio.h> #include <string.h> struct student { int id; char namE[20]; float percentag e; OUTPUT: Id is: 1 Name is: Raju Percentage is: 86.500000
  • 83.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 } record; void main() { record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d n", record.id); printf(" Name is: %s n", record.name); printf(" Percentage is: %f n", record.percentage); getch(); } } Structure within Structure: Nested Structure ● Structure written inside another structure is called as nesting of two structures. ● Nested Structures are allowed in C Programming Language. ● We can write one Structure inside another structure as member of another structure.Syntax struct structure1 { - - - - - - - - - - - - - - - - - - - - }; struct structure2 { - - - - - - - - - - - - - - - - - - - - struct structure1 obj; }; OUTPUT: Id is: 1 Name is: Raju Percentage is: 86.500000
  • 84.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 How to Use nested Structure Way 1 : Declare two separate structures struct date { int dat e; int mo nth ; int yea r; }; struct Employee { char enamE[20 ]; int ssn; float salary; struct date doj; }eMP1; Explanation Accessing Month Field : eMP1.doj.month Accessing day Field : emP1.Doj.day Accessing year Field : emP1.Doj.year Accessing Nested Elements : 1. Structure members are accessed using dot operator. 2. ‘date‘ structure is nested within Employee Structure. 3. Members of the ‘date‘ can be accessed using ’employee’ 4. emP1 & doj are two structure names (Variables) 5. Way 2 : Declare Embedded structures
  • 85.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 struct Employee { char ename[20]; int ssn; float salary; struct date { int date; int month; int year; }doj; }emp1; Explanation Accessing Month Field : eMP1.doj.month Accessing day Field : emP1.Doj.day Accessing year Field : emP1.Doj.year Example #1 : Display an Employee data #include<st dio.h> struct Address { char HouseNo[25 ]; char City[25]; char PinCodE[25]; }; struct Employee { int Id; char Name[25]; float Salary; struct Address Add; }; void main() { int i;
  • 86.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 struct Employee E; printf("ntEnter Employee Id "); scanf("%d",&E.Id); printf("ntEnter Employee Name : "); scanf("%s",&E.Name); printf("ntEnter Employee Salary : "); scanf("%f",&E.Salary); printf("ntEnter Employee House No : "); scanf("%s",&E.Add.HouseNo); printf("ntEnter Employee City : "); scanf("%s",&E.Add.City); printf("ntEnter Employee House No : "); scanf("%s",&E.Add.PinCode); printf("nDetails of Employees"); printf("ntEmployee Id : %d",E.Id); printf("ntEmployee Name : %s",E.Name); printf("ntEmployee Salary : %f",E.Salary); printf("ntEmployee House No : %s",E.Add.HouseNo); printf("ntEmployee City : %s",E.Add.City); printf("ntEmployee House No : %s",E.Add.PinCode); } Output : Enter Employee Id : 101 Enter Employee Name : Suresh Enter Employee Salary : 45000 Enter Employee House No : 4598/D Enter Employee City : Delhi Enter Employee Pin Code : 110056 Details of Employees Employee Id : 101 Employee Name : Suresh Employee Salary : 45000 Employee House No : 4598/D Employee City : Delhi Employee Pin Code : 110056 Example #2 : Display Student Details #include <stdio.h> #include <string.h>
  • 87.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 struct student_college_detail { int college_id; char college_name[50]; }; struct student_detail { int id; char name[20]; float percentage; // structure within structure struct student_college_detail clg_data; }stu_data; int main() { struct student_detail stu_data = {1, "Raju", 90.5, 71145,"Anna University"}; printf(" Id is: %d n", stu_data.id); printf(" Name is: %s n", stu_data.name); printf(" Percentage is: %f nn", stu_data.percentage); printf(" College Id is: %d n", stu_data.clg_data.college_id); printf(" College Name is: %s n", stu_data.clg_data.college_name); return 0; } OUTPUT: Id is: 1 Name is: Raju Percentage is: 90.500000 College Id is: 71145 College Name is: Anna University Array of Structures C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas, array of structures is nothing but collection of structures. This is also called as structure array in C. EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C: This program is used to store and access “id, name and percentage” for 3 students.
  • 88.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 Structure array is used in this program to store and display records for many students. You can store “n” number of students record by declaring structure variable as ‘struct student record[n]“, where n can be 1000 or 5000 etc. #include <stdio.h> #include <string.h> struct student { int id; char name[30]; float percentage; }; int main() { int i; struct student record[2]; // 1ST student's record record[0].id=1; strcpy(record[0].name, "Raju"); record[0].percentage = 86.5; // 2ND student's record record[1].id=2; strcpy(record[1].name, "Surendren"); record[1].percentage = 90.5; // 3rd student's record record[2].id=3; strcpy(record[2].name, "Thiyagu"); record[2].percentage = 81.5; for(i=0; i<3; i++) { printf(" Records of STUDENT : %d n", i+1); printf(" Id is: %d n", record[i].id); printf(" Name is: %s n", record[i].name); printf(" Percentage is: %fnn",record[i].percentage); } return 0; }
  • 89.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 File Handling File: the file is a permanent storage medium in which we can store the data permanently. Types of file can be handled we can handle three type of file as (1) sequential file (2) random access file (3) binary file File Operation opening a file: Before performing any type of operation, a file must be opened and for this fopen() function is used. syntax: file-pointer=fopen(“FILE NAME ”,”Mode of open”); example: FILE *fp=fopen(“ar.c”,”r”); If fopen() unable to open a file than it will return NULL to the file pointer. File-pointer: The file pointer is a pointer variable which can be store the address of a special file that means it is based upon the file pointer a file gets opened. Declaration of a file pointer:- FILE* var; Modes of open The file can be open in three different ways as Read mode ’ r’/rt Write mode ’w’/wt Appened Mode ’a’/at Reading a character from a file getc() is used to read a character into a file Syntax: character_variable=getc(file_ptr); Writing acharacter into a file putc() is used to write a character into a file puts(character-var,file-ptr); ClOSING A FILE fclose() function close a file. fclose(file-ptr); fcloseall () is used to close all the opened file at a time
  • 90.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 File Operation The following file operation carried out the file (1)creation of a new file (2)writing a file (3)closing a file Before performing any type of operation we must have to open the file.c, language communicate with file using A new type called file pointer. Operation with fopen() File pointer=fopen(“FILE NAME”,”mode of open”); If fopen() unable to open a file then it will return NULL to the file-pointer. Reading and writing a characters from/to a file fgetc() is used for reading a character from the file Syntax: character variable= fgetc(file pointer); fputc() is used to writing a character to a file Syntax: fputc(character,file_pointer); /*Program to copy a file to another*/ #include<stdio.h> void main() { FILE *fs,*fd; char ch; If(fs=fopen(“scr.txt”,”r”)==0) { printf(“sorry….The source file cannot be opened”); return; } If(fd=fopen(“dest.txt”,”w”)==0) { printf(“Sorry…..The destination file cannot be opened”); fclose(fs); return; } while(ch=fgets(fs)!=EOF) fputc(ch,fd); fcloseall(); }
  • 91.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 Reading and writing a string from/to a file getw() is used for reading a string from the file Syntax: gets(file pointer); putw() is used to writing a character to a file Syntax: fputs(integer,file_pointer); #include<stdio.h> #include<stdlib.h> void main() { FILE *fp; int word; /*place the word in a file*/ fp=fopen(“dgt.txt”,”wb”); If(fp==NULL) { printf(“Error opening file”); exit(1); } word=94; putw(word,fp); If(ferror(fp)) printf(“Error writing to filen”); else printf(“Successful writen”); fclose(fp); /*reopen the file*/ fp=fopen(“dgt.txt”,”rb”); If(fp==NULL) { printf(“Error opening file”); exit(1); } /*extract the word*/ word=getw(fp); If(ferror(fp)) printf(“Error reading filen”); else printf(“Successful read:word=%dn”,word); /*clean up*/ fclose(fp); }
  • 92.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 Working With Strings - fputs() and fgets() In addition to getc() and putc(), C supports the related functions fputs() and fgets(), which read and write character strings. They have the following prototypes: int fputs (const char *str, FILE *fp); char *fgets (char *str, int length, FILE *fp); The function fputs() works like puts() but writes the string to the specified stream. The fgets() function reads a string until either a newline character is read or length-1 characters have been read. If a newline is read, it will be part of the string (unlike gets()). The resultant string will be null-terminated. rewind () rewind() resets the file position indicator to the beginning of the file. The syntax of rewind() is: rewind(fptr); where, fptr is a file pointer. ferror () ferror() determines whether a file operation has produced an error. It returns TRUE if an error has occurred, otherwise it returns FALSE. ferror() should be called immediately after each file operation, otherwise an error may be lost. fread () and fwrite () To read and write data types which are longer than one byte, the ANSI standard provides fread() and fwrite(). These functions allow the reading and writing of blocks of any type of data. The prototypes are: size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp); size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp); For fread(), buffer is a pointer to a region of memory which will receive the data from the file. For fwrite(), buffer is a pointer to the information which will be written. The buffer may be simply the memory used to hold the variable, for example, &l for a long integer. The number of bytes to be read/written is specified by num_bytes. count determines how many items (each num_bytes in length) are read or written. fread() returns the number of items read. This value may be less than count if the end of file is reached or an error occurs. fwrite() returns the number of items written. One of the most useful applications of fread() and fwrite() involves reading and writing userdefined data types, especially structures. For example, given this structure: struct struct_type { float balance; char name[80]; } cust; The following statement writes the contents of cust: fwrite (&cust, sizeof(struct struct_type), 1, fp);
  • 93.
    191GES205T- PROGRAMMING ANDDATA STRUCTURES USING C UNIT-1 fseek() and Random Access I/O  Random read and write operations may be performed with the help of fseek(), which sets the file position locator. The prototype is:  int fseek(FILE *fp, long numbytes, int origin);  in which numbytes is the number of bytes from the origin, which will become the new current position, and origin is one of the following macros defined in stdio.h:  Origin Macro Name  Beginning of file SEEK_SET  Current position SEEK_CUR  End-of-file SEEK_END  fseek() returns 0 when successful and a non-zero value if an error occurs. fseek() may be used to seek in multiples of any type of data by simply multiplying the size of the data by the number of the item to be reached, for example:  fseek (fp, 9*sizeof (struct list), SEEK_SET);  Which seeks the tenth address. fprint() and fscanf()  fprint() and fscanf() behave exactly like print() and scanf() except that they operate with files.  The prototypes are:  int fprintf (FILE *fp, const char *control_string, ...);  int fscanf (FILE *fp, const char *control_string, ...);  Although these functions are often the easiest way to read and write assorted data, they are not always the most efficient. Because formatted ASCII data is being written as it would appear on the screen (instead of in binary), extra overhead is incurred with each call. If speed or file size is of concern, use fread() and fwrite().