Definition of Algorithm: Programming in C and Data Strutures 15PCD13 MODULE 1: Introduction To C Language
Definition of Algorithm: Programming in C and Data Strutures 15PCD13 MODULE 1: Introduction To C Language
Definition of Algorithm: Programming in C and Data Strutures 15PCD13 MODULE 1: Introduction To C Language
Q.3 What is flowchart? List and define the purpose of symbols used to
represent flowchart. Give an example for flowchart.
Ans:
Defintion of flowchart
Flowchart is a graphical or pictorial representation of an algorithm. Its a program
design tool in which standard graphical symbols are used to represent the logical flow of data
through a function.
Flowchart is a combination of symbols. They show start and end points, the order and
sequence of actions, and how one part of a flowchart is connected to another.
The symbols and thier purpose in flowchart is given below.
Symbol Name Purpose
Example:
Flowchart 1: Finding the area of traingle
Start
Print Area_of_Traingle
End
Start
Sum = A+B+C
Avg = Sum/3
End
Q.5 What are C-Tokens? List and define different C-Tokens with examples.
Ans:
A C-Token is a smallest element of a C program. One or more characters are grouped
in sequence to form meaningful words. These meaningful words are called C-Tokens.
The tokens are broadly classified as follows
• Keywords: Keywords are tokens which are used for their intended purpose only. Each
keyword has fixed meaning or predefined meaning and that cannot be changed by user.
Hence, they are also called as reserved-words.
ex: if, for, while, int, float, break, char ..etc.
• Identifiers: As the name indicates, identifier is used to identify various elements of
program such as variables, constants, functions, arrays etc.
ex: sum, length, etc.
• Constants: A constant is an identifier whose value remains fixed throughout the execution
of the program. The constants cannot be modified in the program.
ex: 10, 10.5, 'a', "sri", etc.
• Operators: An operator can be any symbol like + - * / that specifies what operation need to
be performed on the data.
For ex: + indicates addition operation
* indicates multiplication operation
/ indicates division operation, etc.
• Special symbols: The symbols that are used to indicate array subscript, function call, block,
etc.
ex: [], (), {}, etc.
extern: The extern keyword declares that a variable or a function has external linkage outside
of the file it is declared.
for: for is used to repeat set of statements
goto: The goto keyword is used for unconditional jump to a labeled statement inside a
function.
int: The int keyword declares integer type variable.
short, long, signed and unsigned: The short, long, signed and unsigned keywodrs are type
modifiers that alters the meaning of a base data type to yield new type.
return: The return keyword terminates the function and returns the value.
sizeof: The sizeof keyword evaluates the size of a data (a variable or a constant).
register: The register keyword creates register variables which are much faster than normal
variables.
static: The static keyword creates static variable. The value of the static variables persists
until the end of the program.
struct: The struct keyword is used for declaring a structure. A structure can hold variables of
different types under a single name.
typedef: The typedef keyword is used to define user defined name for a datatype.
union: A Union is used for grouping different types of variable under a single name for
easier handling.
void: The void keyword indicates that a function doesn't return value.
volatile: The volatile keyword is used for creating volatile objects. A volatile object can be
modified in unspecified way by the hardware.
Q. 7 What are identifiers? What are the rules for naming a identifier? Give
examples.
Ans:
Identifier is used to name various elements of program such as variables, constants,
functions, arrays, functions etc. An identifier is a word consisting of sequence of Letters,
Digits or _(underscore).
Rules to Name identifiers are
1. The variables must always begin with a letter or underscore as the first character.
2. The following letters can be any number of letters, digits or underscore.
3. Maximum length of any identifier is 31 characters for external names or 63 characters
for local names.
4. Identifiers are case sensitive. Ex. Rate and RaTe are two different identifiers.
5. The variable name should not be a keyword.
Q. 8 What are constants? List and explain different types of constants with
examples.
Ans:
A constant is an identifier whose value remains fixed throughout the execution of the
program. The constants cannot be modified in the program.
For example: 1, 3.14512, „z‟, “hello"
Different types of constants are:
1) Integer Constant: An integer is a whole number without any fraction part.
There are 3 types of integer constants:
i) Decimal constants (0 1 2 3 4 5 6 7 8 9) For ex: 0, -9, 22
ii) Octal constants (0 1 2 3 4 5 6 7) For ex: 021, 077, 033
iii) Hexadecimal constants (0 1 2 3 4 5 6 7 8 9 A B C D E F)
For ex: 0x7f, 0x2a, 0x521
2) Floating Point Constant: The floating point constant is a real number.
The floating point constants can be represented using 2 forms:
i) Fractional Form: A floating point number represented using fractional form
has an integer part followed by a dot and a fractional part.
For ex: 0.5, -0.99
ii) Scientific Notation (Exponent Form): The floating point number represented
using scientific notation has three parts namely: mantissa, E and exponent.
For ex: 9.86E3 imply 9.86 x 103
3) Character Constant: A symbol enclosed within a pair of single quotes(„) is called a
character constant.
Each character is associated with a unique value called an ASCII (American
Standard Code for Information Interchange) code.
For ex: '9', 'a', '\n'
ASCII code of A = 65, a= 97, 0=48, etc
4) String Constant: A sequence of characters enclosed within a pair of double quotes(“)
is called a string constant.
The string always ends with NULL (denoted by \0) character.
For ex: "9", "a", "sri", "\n", “”
Q.9 What is datatype? List and explain different datatypes with examples.
Ans:
Datatype is an entity that defines set of values and set of operations that can be
applied on those values.
Datatypes are broadly categorized as TWO types:
1) Primitive Data Types: Fundamental data types or Basic data types are
primitive data types.
Examples: int, char, float, double, void
2) Non-Primitive Data Types: The derived or user-defined data types are called as non-
primitive data types.
Examples: struct, union, pointers, etc.
int type:
The int type stores integers in the form of "whole numbers". An integer is
typically the size of one machine word, which on most modern home PCs is 32 bits.
Examples of whole numbers (integers) such as 1,2,3, 10, 100... When int is 32 bits, it
can store any whole number (integer) between -2147483648 and 2147483647. A 32
bit word (number) has the possibility of representing any one number out of
4294967296 possibilities (2 to the power of 32).
int numberOfStudents, i, j=5;
In this declaration it declares 3 variables, numberOfStudents, i and j, j here is
assigned the literal 5.
char type
The char type is capable of holding any member of the character set. It stores
the same kind of data as an int (i.e. integers), but typically has a size of one byte. The
size of a byte is specified by the macro CHAR_BIT which specifies the number of
bits in a char (byte). In standard C it never can be less than 8 bits. A variable of type
char is most often used to store character data, hence its name.
Examples of character literals are 'a', 'b', '1', etc., as well as some special
characters such as '\0' (the null character) and '\n' (newline, recall "Hello, World").
Note that the char value must be enclosed within single quotations.
char letter1 = 'a'; /* letter1 is being initialized with the letter 'a' */
char letter2 = 97; /* in ASCII, 97 = 'a' */
In the end, letter1 and letter2 both stores the same thing the letter 'a', but the
first method is clearer, easier to debug, and much more straightforward.
float type
float is short for floating point. It stores real numbers also, but is only one
machine word in size. Therefore, it is used when less precision than a double provides is
required. float literals must be suffixed with F or f, otherwise they will be interpreted as
doubles. Examples are: 3.1415926f, 4.0f, 6.022e+23f. float variables can be declared
using the float keyword.
double type
The double and float types are very similar. The float type allows you to store
single-precision floating point numbers, while the double keyword allows you to store
double-precision floating point numbers – real numbers, in other words, both integer and
non-integer values. Its size is typically two machine words, or 8 bytes on most machines.
Examples of double literals are 3.1415926535897932, 4.0, 6.022e+23 (scientific
notation).
void type
It is an empty data type. It has no size and no value. It is used with functions
which doesnot return any value, pointers,etc.
Range of values for char, int data type can be calculated with following formula
Type Modifiers: Except for type void the meaning of the above basic types may be altered
when combined with the following keywords.
signed
unsigned
long
short
Table: Use of modifiers to create modified data type
Primitive Data Type Type Modifier Modified Data Type
Char Unsigned unsigned char
signed signed char
Int Unsigned unsigned int
signed signed int
short short int
long short
unsigned short int
unsigned short
The signed and unsigned modifiers may be applied to types char and int and will simply
change the range of possible values.
For example an unsigned char has a range of 0 to 255, all positive, as opposed to a
signed char which has a range of -128 to 127.
An unsigned integer on a 16-bit system has a range of 0 to 65535 as opposed to a
signed int which has a range of -32768 to 32767.
Note however that the default for type int or char is signed so that the type signed char
is always equivalent to type char and the type signed int is always equivalent to int.
The long modifier may be applied to type int and double only. A long int will require 4 bytes
of storage no matter what operating system is in use and has a range of -2,147,483,648 to
2,147,483,647.
A long double will require 10 bytes of storage and will be able to maintain up to 19 digits of
precision.
The short modifier may be applied only to type int and will give a 2 byte integer
independent of the operating system in use.
Examples:
short int, long int, long double, unsigned char, signed char, unsigned int, etc
}
[User-defined Functions]
Example Program:
Consider first a simple C program which simply prints a line of text to the computer screen.
This is traditionally the first C program you will see and is commonly called the “Hello
World” program for obvious reasons.
#include <stdio.h>
int main()
{
/* This is how comments are implemented in C to comment out a block of text */
// or like this for a single line comment
printf( "Hello World\n" ) ;
return 0;
}
All C compiler include a library of standard C functions such as printf which allow the
programmer to carry out routine tasks such as I/O operations, mathemetical operations, string
operations etc. but which are not part of the C language, the compiled C code merely being
provided with the compiler in a standard form.
Header files must be included which contain prototypes for the standard library functions and
declarations for the various variables or constants needed. These are normally denoted by a .h
extension and are processed automatically by a program called the Preprocessor prior to the
actual compilation of the C program.
Therefore, The line #include <stdio.h>
Instructs the pre-processor to include the file stdio.h into the program before compilation so
that the definitions for the standard input/output functions including printf will be present for
the compiler.
As you can see this program consists of just one function the mandatory main function. The
parentheses, ( ), after the word main indicate a function while the curly braces, { }, are used
to denote a block of code -- in this case the sequence of instructions that make up the
function.
Comments are contained within a /* ... */ pair in the case of a block(mutli-line) comment or
a double forward slash, //, may be used to comment out single line.
The line printf("Hello World\n " ) ;
is the only C statement in the program and must be terminated by a semi-colon. The
statement calls a function called printf which causes its argument, the string of text within the
quotation marks, to be printed to the screen. The characters \n are not printed as these
characters are interpreted as special characters by the printf function in this case printing out
a newline on the screen. These characters are called escape sequences in C and cause special
actions to occur and are preceded always by the backslash character, \ .
Global and Local Declaration statements are used to declare global and local variables,
arrays, functions, pointers, etc.
Q. 11 What is Variable? What is the need for variables? What are the rules
for naming variables. Give examples.
Ans:
Definition of Variable
Variable is an identifier used to name the memory location which holds the value.
Variable is an entity whose value can be changed (Not Fixed) during the program execution.
Need for variables
It may help to think of variables as a placeholder for a value or data. You can think of
a variable as being equivalent to its assigned value or data. In a C program, if a user wants to
store and use any data then the user must create variables in a program to store the required
data.
Rules for naming a Variable
1. The variables must always begin with a letter or underscore as the first character.
2. The following letters can be any number of letters, digits or underscore.
3. Maximum length of any identifier is 31 characters for external names or 63 characters
for local names.
4. Identifiers are case sensitive. Ex. Rate and RaTe are two different identifiers.
5. The variable name should not be a keyword.
6. No special symbols are allowed except underscore.
Examples:
Valid identifiers:
Sum roll_no _name sum_of_digits
avg_of_3_nums
Invalid Identifiers and reason for invalid:
$roll_no - Name doesn‟t begin with either letter or underscore
for - keyword is used as name
sum,1 - special symbol comma is not allowed
3_factorial - name begins with digit as first letter
Declaring variables is the way in which a C program shows the number of variables it needs,
name of the variables, range of values it can represent and how much memory they need.
Within the C programming language, when managing and working with variables, it is
important to know the type of variables and the size of these types. Size of the datatypes
can be hardware specific – that is, how the language is made to work on one type of machine
can be different from how it is made to work on another.
All variables in C are typed. That is, every variable declared must be assigned with certain
datatype.
General Syntax for declaring variables:
DataType Variable-list;
Where,
DataType can be => int, float, char, double, short, unsigned int, long double, etc
Variable-list can be => list of variables seperated by comma.
DataType var1,var2,var3,...,varN;
Example:
int count; /* It declares a variable count as integer type */
float average; /* It declares a variable average as floating point type */
int number_students, i, j; /* In this declaration it declares 3 variables,
number_students, i and j. */
char code; /* It declares a variable code as character type */
Q.13 What are input and output functions? Explain printf() and scanf()
functions with examples.
Ans:
Input Functions: The functions which helps user to feed some data into program are
called as input functions. When we are saying Input that means to feed some data into
program. This can be given in the form of file or from command line or from keyboard. C
programming language provides a set of built-in functions to read given input and feed it to
the program as per requirement.
Examples: scanf(), gets(), getchar(), fscanf(), etc
Output Functions: The functions which helps user to display or print output on
screen or on paper using printer or in file are called as output functions. When we are saying
Output that means to display some data on screen, printer or in any file. C programming
language provides a set of built-in functions to output the data on the computer screen as well
as you can save that data in text or binary files.
Examples: printf(), puts(), putchar(), fprintf(), etc.
int N;
N = printf(“Hello\n”);
In this example, the printf() prints the text string “Hello” on screen and returns the
integer value 5 which will be stored in N.
Some more examples :-
int i = 10, j = 20 ;
char ch = 'a' ;
double f = 23421.2345 ;
printf( "%d + %d", i, j ) ; /* values of i and j are substituted from the variable list in
order as required */
printf( "%c", ch ) ;
printf( "%s", "Hello World\n" ) ;
printf( "The value of f is : %lf", f ) ; /*Output as : The value of f is : 23421.2345 */
printf( "f in exponential form : %e", f ) ; /* Output as : f in exponential form :
2.34212345e+4
The & character is the address of operator in C, it returns the address of the memory
location of the variable.
Note that while the space and newline characters are normally used as delimiters
between input fields the actual delimiters specified in the format string of the scanf statement
must be reproduced at the keyboard faithfully as in the case of the last example. If this is not
done the program can produce somewhat erratic results!
The scanf function has a return value which represents the number of fields it
was able to convert or read successfully. It can be ignored.
For Example :- num = scanf( “%c %d”, &ch, &i );
This scanf function requires two fields, a character and an integer, so the value placed
in num after the scanf() call will be 2 if successful.
int a = 5, b = 2, x ;
float c = 5.0, d = 2.0, f ;
x = a / b ; // integer division(5/2), therefore, x = 2.
f = c / d ; // floating point division(5.0/2.0), f = 2.5.
x = 5 % 2 ; // remainder operator, x = 1.
x = 7 + 3 * 6 / 2 - 1 ; // x=15,* and / evaluated ahead of + and -.
x = 7 + ( 3 * 6 / 2 ) - 1 ; // x = 15
x = ( 7 + 3 ) * 6 / ( 2 - 1 ) ; // changes order of evaluation, x = 60 now.
4) Relational Operators: The operators which are to compare or to check the relation
between two or more quantities.
Relational Expressions are expressions that contains only relational operators.
The full set of relational operators are provided in shorthand notation
> is greater than >= is greater than or equal to
< is less than <= is less than or equal to
5) Logical Operators: The operators which acts on only two logical values i.e. true and
false.
Logical expressions are expressions that contains only logical operators. Usually to combine
one or more relations these logical operators are used. Hence such expressions are called as
relational logical expressions.
&& Logical AND | | Logical OR
! Logical NOT
NOTE: Since C has no boolean datatype so to use these operators one must need to remember
that
ZERO(0) is always treated as FALSE and vice versa
NON-ZERO (>0 or <0) value is always treated as TRUE. TRUE is always
represented as 1.
For Example :-
if ( x >= 0 && x < 10 )
printf( “ x is greater than or equal to zero and less than ten.\n” ) ;
For Example :- 2 > 1 -- TRUE so expression has value 1
2 > 3 -- FALSE so expression has value 0
i = 2 > 1 ; -- relation is TRUE -- has value 1, i is assigned value 1
NOTE: Every C expression has a value. Typically we regard expressions like 2 + 3 as the
only expressions with actual numeric values. However the relation 2 > 1 is an expression
which evaluates to TRUE so it has a value 1 in C. Likewise if we have an expression x = 10
this has a value which in this case is 10 the value actually assigned.
6) Conditional Operators: the operators ?: is called as conditional operator and it is
also called as ternary operator since it operates on three operands.
Syntax: expression1?expression2:expression3;
In the above conditional expression, if expression1 is TRUE then returns the value of
expression2 otherwise returns the value of expression3.
For example:-
5>12 ? 11: 12; // returns 12, since 5 not greater than 12.
Prepared By: Mr. M.V.Jerabandi, CSE, REC, HKT Page 20
Programming in C and Data Strutures 15PCD13 MODULE 1: Introduction to C Language
one or zero. The programmer will need to be able to manipulate individual bits directly in
these situations. A mask variable which allows us to ignore certain bit positions and
concentrate the operation only on those of specific interest to us is almost always used in
these situations. The value given to the mask variable depends on the operator being used and
the result required.
For Example :- To clear bit 7 of a char variable.
char ch = 89 ; // any value
char mask = 127 ; // 0111 1111
ch = ch & mask ; // clears bit7 of a variable ch ;
For Example :- To set bit 1 of an integer variable.
int i = 234 ; // any value
int mask = 2 ; // a 1 in bit position 2
i = i | mask ; // sets the bit 1 of variable i
This expression is actually two binary expressions, with one multiplication and one division
operator. But both multiplication and division has a precedence of 13(same precedence).
Hence, apply the associativity rule as given in table above i.e left to right. This results in the
multiplication being done first, followed by the division. The result of the complete
expression is 1.
Q.17 WACP to which takes p,t,r as input and compute the simple interest
and display the result.
Ans:
/* Program to find the simple interest */
#include<stdio.h>
int main()
{
float p,t,r,si;
printf(“Enter p, t and r\n”);
scanf(“%f%f%f”,&p,&t,&r);
si = (p*t*r)/100;
printf(“Simple interest = %f\n”,si);
return 0;
}
Q.18 What is the value of X in the following code segments? Justify your
answers.
i) int a,b; ii) int a,b;
float x; float x;
a=4; a=4;
b=5; b=5;
x=b/a; x = (float) b/a;
Ans:
i) x = b/a;
x = 5/4; // x = int/int
x= 1.0 // since 5/4(int/int) results as 1 but x is of type float so 1 is
converted to float i.e. 1.0
ii) x = (float) b/a;
x = (float) 5/4;
x = 5.0/4; // 5 is converted to 5.0(float type) because of cast operator
x = 5.0/4.0; // 4 is also converted to 4.0 because of implicit type conversion
x = 1.25 // hence, the result is 1.25
Q.24 Write a C program that computes the size of int, float, double and
char variables.
Ans:
/* program to compute size of int, float, double and char variables */
#include<stdio.h>
int main()
{
int i;
float f;
double d;
char c;
printf(“ Size of integer variable = %d\n” , sizeof(i));
printf(“ Size of float variable = %d\n” , sizeof(f));
printf(“ Size of double variable = %d\n” , sizeof(d));
printf(“ Size of character variable = %d\n” , sizeof(c));
return 0;
}
√ √
iii) D = iv) B = √
√
√
v) E = vi) X =
Ans:
i) Given A =
ii) Given C =
Corresponding C expression is C = exp( fabs(x+y-10) );
√ √
iii) Given D =
√
Corresponding C expression is
D = ( exp(sqrt(x)) + exp(sqrt(y)) ) / (x*sin(sqrt(y));
iv) Given B = √
Corresponding C expression is
B = sqrt(s*(s-a)*(s-b)*(s-c));
v) Gievn E =
Corresponding C expression is
E = pow(x,25) + pow(y,25);
√
vi) Given X =
Corresponding C expression is
X = ( -b + sqrt(b*b-4*a*c) ) / (2*a);
// use associativity rule of || operator i.e. left to right and evaluate 1||0 is 1 */
1||0
1 // result of complete expression
Every pointer variable before it is used, it must be declared. Declaration tells the
compiler the name of pointer, to which type of variable it points.
General Syntax of Pointer Declaration:
Datatype *pointer_name;
Where, pointer_name should be framed with the help of rule of identifier.
Datatype can be any valid C data type to which the pointer will point.
Ex:
int *ptr; // ptr is a pointer to integer
char *c ; // c is pointer to character
float *fp; // fp is a pointer to floating point variable
Initialization of Pointer variable:
The process of assigning address of a variable to the pointer variable is called as
initialization.
General Syntax of Initialization:
pointer_name = &variable;
Here, the address of variable is assigned to pointer.
Example:
int var;
After declaration of variable var, it is allocated in some memory location (address) say
1000.
int *p;
here, it declares pointer p which can contain the address of any integer variable.
p = &var;
here, the address of variable var i.e 1000 is stored into pointer variable p. Therefore p
contains 1000. Now onwards p acts as a pointer to var.
}
In this example, the function accepts address of actual parameters and returns address of
result obtained.
Example Program: To swap two numbers using pointers and functions
// Pointer is a variable which contains address of another variable
#include<stdio.h>
void swap(int *x, int *y);
int main()
{
int p, q;
printf(“Enter the value for p and q\n”);
scanf(„%d%d”, &p, &q);
printf(“In Main: Before Function Call\n”);
printf(“p=%d, q=%d\n”, p, q);
swap(1000,2500)
swap(&p,&q); Copies address of p (&p) assumed
that it is at address 1000 to
printf(“In Main: After Function Call\n”); formal parameter *x and address
printf(“p=%d, q=%d\n”, p, q); of q (&q) assumed that it is at
return 0; address 2500 to formal
} parameter *y and transfers
void swap(int *x, int *y) control to function definition
{
int temp;
printf(“In Swap: Before Exchange\n”);
printf(“x=%d, y=%d\n”, *x, *y);
temp=*x;
*x=*y;
*y=temp;
printf(“In Swap: After Exchange\n”);
printf(“x=%d, y=%d\n”, *x, *y);
}
Output of the above program is
Enter the value for p and q
10 20
In Main: Before Function Call
p=10, q=20
In Swap: Before Exchange
x=10, y=20
In Swap: After Exchange
x=20, y=10
In Main: After Function Call
p=20, q=10
From the above output and flow shown with arrow and text description, we can understand
that the address of actual parameters p and q are copied to formal parameters *x and *y
respectively. From the bold text of output we can understand that the modification that we
have done for formal parameters in function definition have affected(modified) actual
parameters in calling function hence, the p and q value before function call and after function
are different.
a. malloc()
b. calloc()
c. realloc()
d. free()
a. malloc() function: It is used to allocate a single block of memory of specified size
dynamically and returns a pointer to the allocated block. The initial values in all the
memory locations will be garbage values.
The general form for memory allocation using malloc is:
datatype *ptr =(data type *)malloc (requiredAmountofmemory);
Example 1 :
int *ptr;
ptr = (int *) malloc(10*sizeof(int));
In this example, it allocates 10 * sizeof(int) = 10 * 4 bytes = 40 bytes of memory
and starting address of block is assigned to pointer ptr.
Example 2 :
char *ptr ;
ptr = (char *) malloc(5*sizeof(char));
In this example, it allocates 5 * sizeof(char) = 5 * 1 bytes = 5 bytes of memory
and starting address of block is assigned to pointer ptr.
b. calloc() function: It is used to allocate multiple blocks of memory of specified size
dynamically and returns a pointer to the allocated block. The initial values in all the
memory locations will be ZERO.
The general form for memory allocation using calloc is:
datatype *ptr =(data type *)calloc (NoOfBlocks , requiredAmountofmemory);
Example 1 :
int *ptr;
ptr = (int *) calloc(10, sizeof(int));
In this example, it allocates 10blocks of memory. Each block will be of size
4bytes since size of int is 4bytes in 32bit machine. Therefore, total of 40 bytes of
memory is allocated and starting address of first block is assigned to pointer ptr.
Example 2 :
char *ptr ;
ptr = (char *) calloc(5, sizeof(char));
In this example, it allocates 5blocks of memory. Each block will be size 1byte
since size of char is 1byte. Therefore, total of 5bytes of memory is allocated and
starting address of first block is assigned to pointer ptr.
c. realloc() function: It is used to increase or decrease the size of already allocated
memory using malloc or calloc function and returns a pointer to the newly
allocated block.
The general form for memory allocation using realloc is:
datatype *ptr =(data type *)realloc (ptrname, NewAmountofmemory);
Example 1 :
int *ptr;
ptr = (int *) malloc(10*sizeof(int));
Non Primitive Data Types: are those that are not defined by the programming language
but are instead created by the programmer. These are also known as derived data types
which are derived from the existing fundamental data types.
Non Primitive Data Types are classified into two types
a. Linear Data Types
b. Non Linear Data types
a. Linear Data Types: Here the data elements are arranged in linear fashion.
Examples:
stack – it is a linear data structure, where insertion and deletion are done from
only one end i.e top end. It is also known as Last-In-First-Out(LIFO) data
structure.
Queue – it is a linear data structure, where insertion is done from rear end and
deletion is done from front end. It is also known as First-In-First-Out(FIFO)
data structure.
Linked list – it is a linear data structure where insertion and deletion are done
linearly.
b. Non Linear Data Types: Here the data elements are arranged in nonlinear
fashion.
Examples:
Trees – it is a non-linear data structure, where data are arranged in non-linear
fashion.
Graphs – where set of vertices and edges are arranged non-linearly.
Maps - where different states, districts, cities, etc are represented in non-linear
fashion.
In the above example, we can observe that data items and various operations are listed but not
detailed any information about how the data items are stored in memory, manipulated and
operated. Similarly, how the operations are implemented is also not described. Hence, it hides
the implementation details from the user.
a. Stack: It is a linear data structure, where insertion and deletion are done from only
one end i.e., top end. It is also known as Last-In-First-Out (LIFO) data structure.
Pictorial View of Stack:
b. Queue: it is a linear data structure, where insertion is done from rear end and deletion
is done from front end. It is also known as First-In-First-Out(FIFO) data structure.
Pictorial view of Queue
Types of Queue: There are three different types of queue based on how way they insert and
delete from the queue.
1. Linear Queue: where insertion and deletion is done linearly i.e. insertion is done
from one end and deletion is done from other end.
Example:
2. Circular Queue: where insertion and deletion of data items is done in circular
fashion.
Rear
Front
3. Double Ended Queue: Where insertion and deletion is done from both the ends i.e.,
insertion can be done from both rear end and front end, similarly deletion can also be
done from both ends.
Delete from
Insert from
Front End
Rear End
Insert from Delete from
Front End Rear End
Applications of Queue:
i. It is used in implementing job scheduling
ii. It is used in implementing CPU scheduling
iii. It is used in implementing Disk scheduling
iv. It is used in implementing Input and Output buffe
v. It is used in servicing printing requests of printer
2. Circular Linked list: It is a linear data structure, where each node contains a pointer
to the next node and last node contains a pointer to the first node.
Example:
3. Doubly linked list: It is a linear data structure, each node contains a pointer to the
next node as well as to the previous node.
Example
d. Tree: Tree is a non-linear data structure, where the data are arranged in hierarchical
fashion.
Types of Tree:
1. Binary Tree
2. Binary Search Tree
3. RED-BLACK Tree
4. AVL Tree
5. B Tree
6. B+ Tree
Total memory allocated for one variable of defined structure is sum of size of each
member of the structure.
The syntax of declaring structure variables is shown below:
struct struct_tag v1,v2,v3,…,vn;
Example: struct student s1, s2, s3;
In the above statement, three variables s1, s2 and s3 are created of type struct student.
Hence, separate memory allocation is done for each variable.
Therefore, total memory allocated for s1 = 20bytes (size of member name) + 4bytes
(size of member roll_number) + 8bytes(size of average_marks) => 32bytes.
Similarly, for s2 another 32bytes of memory is allocated and for s3 also another
32bytes of memory is allocated.
.
structure_variablename membername;
Example: E1.name, here E1 is structure variable of structure employee and name is
one of the member of structure employee.
Structure assignment (using assignment operator): the variable of one structure
can be assigned to another variable of same structure. Every member value of one
variable is copied to corresponding member of another variable.
Example:
struct student cse = { “Raju”,18, 87.5}; // creates a variable cse
and initialized with values as specified in curly braces.
struct student ise; //creates another variable ise of structure student
type.
ise = cse;
in this statement, the value of name, roll_number and average_marks of cse are
copied to name, roll_number and average_marks of ise respectively.
Syntax for Declaring and Defining Structure: the declaration of structure defines a
template for structure and its members. No memory allocation is done for the declared
structure.
struct struct_tag
{
type var_1;
type var_2;
.
.
.
type var_n;
};
Here,
The word struct is a keyword in C
The item identified as struct_tag is called a tag and identifies the structure later
in the program
Each type1, type2, …, typen can be any valid C data type including structure
type
The item var_1,var_2,…,var_n are the members or fields of the structure
Example:
struct student
{
char name[20];
int roll_number;
float average_marks;
};
Declaring Structure Variables: declaring structure variables is nothing but creating
instances of structures. Hence, actual memory allocation is done after declaring
variables of structure type. Until and unless we create structure variables, it is not
possible to store, process and access the members of the structure.
Total memory allocated for one variable of defined structure is sum of size of each
member of the structure.
The syntax of declaring structure variables is shown below:
struct struct_tag v1,v2,v3,…,vn;
Example: struct student s1, s2, s3;
In the above statement, three variables s1, s2 and s3 are created of type struct student.
Hence, separate memory allocation is done for each variable.
Therefore, total memory allocated for s1 = 20bytes (size of member name) + 4bytes
(size of member roll_number) + 8bytes(size of average_marks) => 32bytes.
Similarly, for s2 another 32bytes of memory is allocated and for s3 also another
32bytes of memory is allocated.
Structure Initialization: Assigning the values to the structure member fields is
known as structure initialization. The syntax of initializing structure variables is
similar to that of arrays i.e all the elements are enclosed within braces i.e { and } and
are separated by commas. The appropriate values for each member of the structure
must be provided in sequence. Partial initialization is also allowed but programmer
must not omit initializers for middle members of the structure.
The syntax is as shown below:
struct struct_tag variable = { v1,v2,v3,…,vn};
Example : struct student cse = { “Raju”,18, 87.5};
4. What are typedefinitions? What are the advantages of typedef? Explain with
an example, how to create a structure using „typedef‟.
Type definition: The typedef is a keyword using which the programmer can
create a new data type name for an already existing data type name. So the
purpose of typedef is to redefine or rename the name of an existing data type.
Syntax:
typedef data_type newname1, newname2,…, newnamen;
Example1: typedef int NUMBER;
Example2: typedef float SALARY;
The new names that are given by the user for the already existing data types are
called user defined data types. In the above example NUMBER and SALARY
are user defined data types.
The user defined data types can be used to declare variables as illustrated below:
Example1: typedef int NUMBER;
NUMBER N1,N2,N3;
Example2: typedef float SALARY;
SALARY s1,s2,s3,s4,s5;
Advantages of typedef
a. User-defined names can be defined for existing data types
Example:
typedef int integer;
typedef char character;
integer n1, n2;
character c1;
From the above example, we can understand that, beginners of users of C can
understand the statement integer n1, n2 as n1 and n2 are variables of integer
type and similarly, c1 is of character type.
b. Based on context or application, new names can be defined for data types.
Example1: if we are developing program to represent various whole
numbers then int can be renamed as below
typedef int WHOLE_NUMBER;
WHOLE_NUMBER w1, w2;
From the above two lines, we can understand that w1 and w2 will be used to
represent whole numbers as the name of the data type indicates its purpose.
Example2: if we are developing program to represent percentage of three
semesters of student then float can be renamed as below
Example:
typedef struct student Optional
{
char name[20];
char usn[11];
float marks;
}STUDENT;
NOTE: as shown with diagram and arrow mark, the tag name i.e. student which
is used to name the structure is optional.
In this example, the new data type struct student has been declared as well it is
been renamed as STUDENT.
int mm;
int yyyy;
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct dob DOB;
}stu_data;
In this example, “dob‟ structure is declared inside “student_detail” structure. Both
structure variables are normal structure variables.
To access members of the main structure and nested structure we have to use the
following syntax.
To access dd of nested structure: stu_data.DOB.dd
To access mm of nested structure: stu_data.DOB.mm
To access yyyy of nested structure: stu_data.DOB.yyyy
This program explains how to use structure within structure in C.
“student_college_detail‟ structure is declared inside “student_detail” structure in this
program. Both structure variables are normal structure variables.
Please note that members of “student_college_detail” structure are accessed by 2
dot(.) operator and members of “student_detail” structure are accessed by single dot(.)
operator.
#include <stdio.h>
#include <string.h>
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;
};
int main()
{
struct student_detail stu_data = {1, "xyz", 90.5, 32, "REC Hulkoti"};
printf(" Id is: %d \n", stu_data.id);
};
}
Some Observations and Important Points :
Tip #1 : All Structure Members need not be initialized
#include<stdio.h>
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = {{"Book1",700,"YPK"}, {"Book2",500,"AAK",350.00},
{"Book3",120,"HST",450.00}};
int main()
{
printf("\nBook Name : %s",b1[0].bname);
printf("\nBook Pages: %d",b1[0].pages);
printf("\nBook Author: %s",b1[0].author);
printf("\nBook Price : %f",b1[0].price);
}
Output :
Book Name : Book1
Book Pages : 700
Book Author : YPK
Book Price : 0.000000
Explanation: In this example, While initializing first element of the array we have
not specified the price of book 1. It is not mandatory to provide initialization for
all the values. Suppose we have 5 structure elements and we provide initial values
for first two element then we cannot provide initial values to remaining elements.
{"Book1", 700, ,90.00}
above initialization is illegal and can cause compile time error.
Tip #2 : Default Initial Value
struct Book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[3] = { {},{"Book2",500,"AAK",350.00}, {"Book3",120,"HST",450.00} };
Output :
Book Name : Book
Pages : 0
Book Author :
Book Price : 0.000000
It is clear from above output. Default values for different data types.
C program: to illustrate array of structures.
#include<stdio.h>
typedef struct
{
char name[20]; // Name
char usn[11]; //usn
char subname[30]; //subject name
int m1, m2, m3; //marks
}student;
int main()
{
student s[100];
int i, N;
printf(“Enter N value\n”);
scanf(“%d”, &N);
//Reading student details
printf(“Enter %d student details\n”, N);
for(i=0;i<N;i++)
{
printf(“Enter details of %d student\n” , i+1);
printf(“\nEnter name of a student :”);
scanf(“%s” , s[i].name);
printf(“\n Enter USN:”);
scanf(“%s” , s[i].usn);
printf(“\n Enter subject name:”);
scanf(“%s” , s[i].subname);
printf(“\n Enter first, second and third IA marks :”);
scanf(“ %d %d %d” , &s[i].m1, &s[i].m2, &s[i].m3);
}
// Printing student details
printf(“\n Name \t USN \t Subject Name \t Marks1 \t Marks2 \tMarks3\n”);
for(i=0;i<N;i++)
printf(“%s \t %s \t %s \t %d \t %d \t %d \n” , s[i].name, s[i].usn,
s[i].subname, s[i].m1, s[i].m2, s[i].m3);
return 0;
}
Explanation: in this program a structure which include name, usn, subject name
and IA marks of student is declared then an array of students is declared by using
student s[100] statement which defines array s with capable of storing 100
students information. Each student information is accessed by subscripting name
of the array s with an index i as s[i]. In this example, N student details are inputted
from the keyboard and same details are displayed on screen.
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18 - 2.3
Explaination: In this program, structure variables dist1 and dist2 are passed by
value (because value of dist1 and dist2 does not need to be displayed in main
function) and dist3 is passed by reference, i.e, address of dist3 (&dist3) is passed
as an argument. Thus, the structure pointer variable d3 points to the address of
dist3. If any change is made in d3 variable, effect of it is seen in dist3 variable in
main function.
10. Write a C program to input the following details of „N‟ students using
structure:
Roll No: integer, Name: string, Marks: float, Grade: char
Print the names of the students with marks>=70.0%.
Program:
#include<stdio.h>
struct student
{
int rno; // Roll No
char name[20]; // Name
float marks; //Marks
char grade; //Grade
};
int main()
{
int i, n, found=0;
struct student s[20];
printf(“\nHow many student details ?);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Type in %d student detail \n”,i+1);
printf(“\n Roll no :”);
scanf(“%d” , &s[i].rno);
printf(“\n Name:”);
scanf(“%s” , s[i].name);
printf(“\n Marks:”);
scanf(“%f” , &s[i].marks);
printf(“\n Grade :”);
scanf(“ %c” , &s[i].grade);
}
printf(“\n The Names of the students with marks >=70.0%\n”);
for(i=0;i<n;i++)
{
if(s[i].marks>=70.0))
{
printf(“\n %s\n” , s[i].name);
found =1;
}
}
if(found ==0)
printf(“\n There is no student with marks >=70.0%\n”);
return 0;
}
11. Write a C program to maintain a record of “n” student details using an array
of structures with four fields (Roll number, Name, Marks, and Grade). Each
field is of an appropriate data type. Print the marks of the student given
student name as input.
Program:
#include<stdio.h>
#include<string.h>
struct student
{
int rno; // Roll No
char name[20]; // Name
float marks; //Marks
char grade; //Grade
};
int main()
{
int i, N;
struct student s[20];
char key[20];
printf(“\nHow many student details ?);
scanf(“%d”,&N);
for(i=0;i<N;i++)
{
printf(“\n Type in %d student detail \n”,i+1);
printf(“\n Roll no :”);
scanf(“%d” , &s[i].rno);
printf(“\n Name:”);
scanf(“%s” , s[i].name);
printf(“\n Marks:”);
scanf(“%f” , &s[i].marks);
printf(“\n Grade :”);
scanf(“%c” , &s[i].grade);
}
printf(“Enter the name to be searched\n”);
scanf(“%s”, key);
for(i=0; i<N; i++)
{
if(strcmp(key, s[i].name))
{
printf(“\n Marks obtained by %s = %d\n” , key, s[i].marks);
return 0;
}
}
printf(“\n No student found with name = %s \n”, key);
return 0;
}
File Handling
12. What is a file? What are the different modes of opening a file? Explain.
Solution: Abstractly, a file is a collection of data stored on a secondary storage
device, which is generally a disk. The collection of data may be interpreted, for
example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical
image.
Files can be classified as input files and output files. Input files are file which
contains various data that will be provided as input to the program. Output files
are files which contains the output produced from the program.
Working with file: While working with file, you need to declare a pointer of type
FILE. This declaration is needed for communication between file and program.
FILE *ptr;
Here, ptr is pointer to file called as file pointer which will be used to address or
reference the file.
Different Modes of file opening in Standard I/O
In C, the files are opened using fopen function. Which accepts two parameters;
first parameter is name of the file to be opened and second parameter is mode of
file open.
General Syntax of fopen call:
FILE *fopen(char filename[], char mode[]);
On successful opening of specified file, fopen function returns a file pointer. On
failure, fopen function returns NULL.
File Access Mode Meaning of Mode If file doesn‟t exist
“r” Open for reading If the file does not exist,
fopen() returns NULL.
“w” Open for writing If the file exists, its
contents are overwritten.
If the file does not exist, it
will be created.
“a” Open for appending i.e If the file doesn‟t exist it
data is added from end of will be created
file
“r+” Open for both reading If the file does not exist,
and writing fopen() returns NULL.
“w+” Open for both reading If the file exists, its
and writing contents are overwritten.
If the file does not exist, it
will be created.
“a+” Open for both reading If the file does not exists,
and appending it will be created.
13. Explain how the input is accepted from a file and displayed.
Solution:
Accepting input from a file and displaying can be done in different ways.
a. Using fscanf() and fprint()
fscanf function is used to accept input from a file. Which accepts three
parameters; first parameter is source of input which can be either file or standard
input device, second parameter defines the type of data to read and third parameter
defines address of variable where the data is to be stored. Once the data is stored
in variables then it can be displayed on standard output device i.e., monitor or can
be stored in a file using fprintf().
This program reads a string of text from a file using fscanf() and fprintf().
/* Source Code to read a text of string and display the same from a file. */
#include <stdio.h>
#include<stdlib.h> // for exit function
int main()
{
char data[1000];
FILE *fptr;
if ((fptr=fopen("program.txt","r"))==NULL)
{
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%[^\n]",data); //read every character that is not „\n‟
fprintf(stdout,"Data from file:\n%s",data);
fclose(fptr);
return 0;
}
This program reads the content of “program.txt” file and stores it in a string data.
Then content of this data is displayed on screen using fprintf(). If there is no file
named program.txt then, this program displays Error! opening file and program
will be terminated.
b. Using fgetc and fputc function
fgetc() function is used to read one character at a time from a specified file. This
procedure can be repeated until end of file.
fputc() function is used to write one character at a time into a specified file. This
procedure can be repeated until all the characters are written to a file.
/* program to read text from file and store it in another file using fgetc and
fputc */
#include <stdio.h>
#include<stdlib.h> // for exit function
int main()
{
char ch;
FILE *fptr1,*fptr2;
if ((fptr1=fopen("read.txt","r"))==NULL)
{
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
if ((fptr2=fopen("write.txt","w"))==NULL)
{
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
while((ch = fgetc(fptr1)) != EOF) // Read a Character until end of file
fputc(ch,fptr2);
fclose(fptr1);
fclose(fptr2);
return 0;
}
c. Using fgets and fputs functions
These are useful for reading and writing entire lines of data to/from a file.
If buffer is a pointer to a character array and n is the maximum number of
characters to be stored, then
fgets (buffer, n, input_file);
will read an entire line of text (max chars = n) into buffer until the newline
character or n=max, whichever occurs first. The function places a NULL
character after the last character in the buffer. The fgets function returns
NULL when no more data to read.
fputs (buffer, output_file);
writes the characters in buffer until a NULL is found. The NULL character is
not written to the output_file.
NOTE: fgets does not store the newline into the buffer, fputs will append a
newline to the line written to the output file.
/* program to read text from file and store it in another file using fgets and
fputs */
#include <stdio.h>
#include<stdlib.h> // for exit function
int main()
{
char data[101];
FILE *fptr1,*fptr2;
if ((fptr1=fopen("read.txt","r"))==NULL)
{
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
if ((fptr2=fopen("write.txt","w"))==NULL)
{
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
/* Read 100 Characters or until end of file whichever occurs first from read.txt
file and write it to write.txt file. */
while((fgets(data,100,fptr1)) != NULL)
fputs(data,fptr2);
fclose(fptr1);
fclose(fptr2);
return 0;
}
14. Explain the following file operations along with syntax and examples:
a) fopen() b) fclose() c) fscanf() d) fprintf() e) feof()
Solution:
a) fopen() : Opening a file is done by a call to the function fopen( ) which tells
the operating system the name of the file and whether the file is to be opened
for reading or for writing or for appending.
General form of call to fopen:
FILE *fopen(char filename[], const char mode[]);
OR
filepointer = fopen (“Filename” , “mode”);
The function fopen takes two parameters both of which are strings.
The parameter filename is a C string which must contain the name of the disk file
to be opened. If the file is not in the default directory a full path name must be
provided.
Parameter mode is a C string which defines the way the file is to be opened. The
mode is a string not characters and must be enclosed in double quotation marks.
The various modes are shown below.
Access Description
Mode
“r” Open a file for reading. Specified file must exist.
“w” Creates an empty file for writing. If the specified file doesn‟t exist
then, it creates a new file by specified name and opens for writing. If
the file already exist then, its content is erased and opens as new empty
file for writing.
“a” Open a file for appending. If the file doesn‟t exist then, it creates new
file by specified name and opens it for appending.
“r+” Open a file for both reading and writing. Specified file must exist.
“w+” Creates an empty file for both reading and writing.
“a+” Opens a file for both reading and appending.
ii) fclose() : After file has been used it must be closed. This is done by a call to
the function fclose(). The fclose() function breaks the connection between the
stream and the file.
General form of a call to the fclose() is
fclose(file_pointer);
The function fclose takes one parameter which is pointer to a file of opened file. If
there is an error, such as trying to close a file that is not opened, the function
returns EOF; otherwise it returns 0. The return value is usually not checked.
Example :
File *fp1,*fp2 ;
fclose(fp1) ; // closes a file referenced by fp1
fclose(fp2); // closes a file referenced by fp2
Opening and closing the File : Example program
int main()
{
FILE *fp;
char ch;
fp = fopen("INPUT.txt","r"); // Open file in Read mode
while(1)
{
ch = fgetc(fp); // Read a Character
if(ch == EOF ) // Check for End of File
break ;
printf("%c",ch);
}
fclose(fp); // Close File after Reading
}
iii) fscanf()
The C library function fscanf() reads formatted input from a file or from the
standard input device i.e. keyboard.
General syntax of fscanf() is
fscanf(filepointer, “format string”, list of address of variables);
iv) fprintf()
The C library function fprintf() prints formatted output to a file, printer or to the
standard output device i.e. screen.
General syntax of fprintf() is
fprintf(filepointer, “format string”, list of variables);
fprintf() returns number of data items successfully written.
Here,
filepointer − This is the pointer to a FILE object that identifies the opened
file or it can be stdout if we want to write data to screen.
format string − This is the C string that contains one or more format
specifiers which defines type of data to be written to the file or standard
output device.
List of variables – this contains one or more variables of which the data
will be written.
/* example program to write data to a file */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp;
fp = fopen ("file.txt", "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012); // writes three
strings followed by an integer separated by whitespace to the file file.txt
fclose(fp);
return(0);
}
v) feof()
The C library function int feof(FILE *filepointer) tests the end-of-file indicator
for the given file. Where, filepointer is the pointer to file object which identifies
the file to be tested.
This function returns a non-zero value when End-of-File is encountered, else zero
is returned.
// use of feof() in program
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
if((fp = fopen("file.txt","r"))==NULL)
{
printf("Error in opening file");
return (-1);
}
while(!feof(fp)) //feof() tests the End-of-File, if EOF then jumps out of loop.
{
c = fgetc(fp);
printf("%c", c);
}
fclose(fp);
return(0);
}
15. Explain the following file operations along with syntax and examples:
a) fputc( ) b) fputs( ) c) fgetc( ) d) fgets()
a) fputc()
The C library function int fputc(int character, FILE *filepointer) writes a character
(an unsigned char) specified by the argument char to the specified file and advances
the position indicator for the file.
Here,
character - This is the character to be written. This is passed as its int
promotion.
filepointer -- This is the pointer to a FILE object that identifies the file where
the character is to be written.
If there are no errors, the same character that has been written is returned. If an error
occurs, EOF is returned and the error indicator is set.
// example program to illustrate use of fputc()
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;
fp = fopen("file.txt", "w+");
for( ch = „A‟ ; ch <= „Z‟; ch++ )
fputc(ch, fp); // writes a character stored in ch to file pointed by fp
fclose(fp);
return(0);
}
b) fputs()
The C library function int fputs(const char *str, FILE *filepointer) writes a string
to the specified file up to but not including the null character.
Here,
str - This is an array containing the null-terminated sequence of characters to
be written.
filepointer - This is the pointer to a FILE object that identifies the file where
the string is to be written.
This function returns a non-negative value on success or EOF on error.
// program to illustrate use of fputs()
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt", "w+");
//writes this is c programming to file pointed by fp
fputs("This is c programming.", fp);
//writes This is a system programming language. to the file pointed by fp.
fputs("This is a system programming language.", fp);
fclose(fp);
return 0;
}
c) fgetc()
The C library function int fgetc(FILE *filepointer) gets the next character (an
unsigned char) from the specified file and advances the position indicator for the
file.
Where,
filepointer - This is the pointer to a FILE object that identifies the file
on which the operation is to be performed.
This function returns the character read as an unsigned char cast to an int or EOF on
end of file or error.
// program to illustrate use of fputc()
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
int n = 0;
fp = fopen("file.txt","r");
if(fp == NULL)
{
printf("Error in opening file");
return (-1);
}
while(!feof(fp)) //read until end of file
{
c = fgetc(fp); // reads an unsigned character and converts to integer.
printf("%c", c);
}
fclose(fp);
return(0);
}
d) fgets()
The C library function char *fgets(char *str, int n, FILE *filepointer) reads a line
from the specified stream and stores it into the string pointed to by str.
It stops when either n-1 characters are read, the newline character is read, or the end-
of-file is reached, whichever comes first.
Where,
str -- This is the pointer to an array of characters where the string read
is stored.
16. Write a C program to read and display a text from the file.
/* Source Code to read a text of string and display the same from a file. */
#include <stdio.h>
#include<stdlib.h> // for exit function
int main()
{
char ch;
FILE *fptr;
if ((fptr=fopen("program.txt","r"))==NULL)
{
printf("Error! opening file");
Prepared By: Mr. M.V.Jerabandi, CSE, REC, HKT Page 28
Programming in C and Data Structures 15PCD13 MODULE 4: Structures and File Handling
16. Write a C program to read the contents from the file called „abc.txt‟, count
the number of characters, number of lines and number of whitespaces and
output the same.
Program:
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
int cc =0; /* number of characters */
int bc=0; /* number of blanks */
int tc =0; /* number of tabs*/
int lc=0; /* number of lines */
int wc=0; /* number of words */
fp = fopen(“abc.txt” , “r”);
if(fp==NULL)
{
printf(“Error in opening the file \n”);
return -1;
}
while((ch=fgetc(fp))!=EOF)
{
cc++;
if (ch == “”)
bc++;
if(ch == “\n”)
lc++;
if(ch == “\t”)
tc++;
}
fclose(fp);
wc = bc + lc;
printf(“\n Number of characters = %d\n” , cc);
printf(“\n Number of tabs = %d\n” , tc);
printf(“\n Number of lines = %d\n”, lc);
printf(“\n Number of blanks = %d\n” , bc);
printf(“\n Number of words count = %d\n” , wc);
return 0;
}
fclose(fd1);
fclose(fd2);
fclose(fd3);
printf(“Content of Karnataka.in file is:\n”);
fd1=fopen("Karnataka.in","r");
while((buff=fgetc(fd1))!=EOF)
{
if(buff=='\n')
line++;
if(isspace(buff)||buff=='\t'||buff=='\n')
word++;
putchar(buff);
}
fclose(fd1);
printf("\n no of lines=%d\n",line);
printf("no of words=%d\n",word);
return 0;
}
18. Given two university information files “studentname.txt” and “usn.txt” that
contains students Name and USN respectively. Write a C program to create a
new file called “output.txt” and copy the content of files “studentname.txt”
and “usn.txt” into output file in the sequence shown below. Display the
contents of output file “output.txt” on to the screen.
Student Name USN
Name1 USN1
Name2 USN2
… …
… …
#include<stdio.h>
#include<stdlib.h>
int main()
{
char buff;
FILE *fd1,*fd2,*fd3;
fd1=fopen("USN.txt","r");
if(fd1==NULL)
{
printf("Error: opening USN.txt file");
exit(1);
}
fd2=fopen("OUTPUT.txt","w");
if(fd2==NULL)
{
printf("Error: Opening OUTPUT.txt file");
exit(1);
}
fd3=fopen("studentname.txt","r");
if(fd3==NULL)
{
printf("Error: opening studentname.txt file");
exit(1);
}
fprintf(fd2,"%s\t%s\n","Student Name","USN");
do
{
buff=fgetc(fd3); //read content from file studentname.txt
if((buff!=EOF) && (buff!='\n'))
fputc(buff,fd2); //write into the file output.txt
if(buff=='\n')
{
fputc('\t',fd2);
do
{
buff=fgetc(fd1); //read content from USN.txt file
if(buff!=EOF)
fputc(buff,fd2); //write into the file output.txt
if(buff=='\n')
break;
}while(1); //until end-of-file for USN.txt
}
}while(buff!=EOF); //until end-of-file for NAME.txt
fclose(fd1);
fclose(fd2);
fclose(fd3);
printf(“Content of output.txt file is:\n”);
fd1=fopen("output.txt","r");
while((buff=fgetc(fd1))!=EOF)
putchar(buff);
fclose(fd1);
return 0;
}
Imagine we have a problem that requires us to read, process and print 10 integers. To
begin, we can declare and define 10 variables, each with a different name as shown below;
int r1, r2, r3, r4, r5, r6, r7, r8, r9, r10;
This creates 10 variables and allocates 10 different blocks of memory one for each variable as
shown below.
Having 10 different names, how can we read 10 integers from the keyboard and store them?
To read 10 integers from the keyboard, we need 10 read statements, each to a different
variable. Furthermore, once we have them in memory, how can we print them? To print them
we need 10 print statements.
r1 r6
r2 r7
r3 r8
r4 r9
r5 r10
For example, the following program illustrates how to read and print 10 integer numbers into
10 different names.
#include<stdio.h>
int main()
{
int r1, r2, r3, r4, r5, r6, r7, r8, r9, r10;
// read 10 integers into 10 different names
scanf(“%d”, &r1);
scanf(“%d”, &r2);
scanf(“%d”, &r3);
scanf(“%d”, &r4);
scanf(“%d”, &r5);
scanf(“%d”, &r6);
scanf(“%d”, &r7);
scanf(“%d”, &r8);
scanf(“%d”, &r9);
scanf(“%d”, &r10);
printf(“%d”, r8);
printf(“%d”, r9);
printf(“%d”, r10);
return 0;
}
Although this approach may be acceptable for 10 variables but how about 100 variables,
1000 variables or 10000 variables? It is definitely not acceptable.
Hence, we need more powerful data structure to process large amounts of data. Hence the
array is used for processing large amounts of data of same type.
By using arrays the above program can be rewritten as follows
#include<stdio.h>
int main()
{
int r[10];
int i;
// read 10 integer numbers
for(i=0;i<10;i++)
scanf(“%d” , &a[i]);
//print 10 integer numbers
for(i=0;i<10;i++)
printf(“%d” , a[i]);
return 0;
}
This example program is much easier to read, understand and alter the number of elements to
be read and print as per the requirement. Hence, the arrays are much better than variables for
storing large amounts of same type of data. Hence the various applications and advantages
are listed below.
Applications of Arrays
Various applications and advantages of arrays are
Can store large elements of same type
Can replace multiple different variable names of same type by single name
Can be used for sorting and searching applications
Can be used for representing matrix
Can be used in recursion
Can be used for implementing various data structures like stack, queue, etc.
Different Types of Arrays
In C, the arrays can be classified as two types based on the arrangement of data.
a. One-Dimensional Array
b. Multi-Dimensional Array
One-Dimensional Array:
An array is one in which elements are arranged linearly. If an array contains only one
subscript then it is called as one-dimensional array.
Similarly, second element of the array can be accessed by marks[1], third element by
marks[2], etc.
Storing Values in Arrays
Declaration and definition only reserve space for the elements in the array. No values
are stored.
If we want to store values in the array, we can use the following methods of initialization
initialize the elements (Initialization)
read values from the keyboard (Inputting)
assign values to each individual element (Assignment)
Initialization of an array
Providing a value for each element of the array is called as initialization. The list of
values must be enclosed in curly braces.
NOTE: It is a compile time error if we provide more values than the size of the array.
Examples:
a) basic initialization
int numbers[5] = { 3, 23, 17, 8, 19};
In this example, first element numbers[0] is initialized to 3
second element numbers[1] is initialized to 23
third element numbers[2] is initialized to 17
fourth element numbers[3] is initialized to 8
fifth element numbers[4] is initialized to 19
b) initialization without size of the array
int numbers[ ] = { 3, 7, 12, 29, 30 };
In this example, since the size of the array is not specified in brackets, size of
array is decided based on number of elements in the curly braces. Hence the
size of array is 5.
c) Partial initialization
int numbers[5] = {4, 9};
In this example, the array is partially initialized, since the number of values
provided in curly braces are fewer than the size of the array. Therefore, it
initializes first element with 4, second element with 9 and unassigned or
uninitialized elements are filled with ZEROs automatically.
d) Initialization of all elements to ZEROs
int numbers[100] = {0};
In this example, all the elements are filled with ZEROs.
Inputting Values
Another way to fill the array is to read the values from the keyboard or file by using
scanf statement or fscanf statement.
For Example,
int numbers[5];
int i;
for(i=0;i<5;i++)
scanf(“%d” , &numbers[i]);
In this example, scanf function is repetitively called for 5 times and reads the values
for all elements of the array. Since the starting index of array is ZERO, so index i is
initialized to 0 in for loop and the condition i<5 iterates loop for 5 times i.e., the number of
elements in the array.
Assigning values
We can assign values to individual elements using the assignment operator. Any value
that reduces to the proper type of array can be assigned to an individual array element.
For Example,
int numbers[5];
numbers[0] = 10; //assigns first element to 10
numbers[1] = 4; //assigns second element to 4
II. Functions in C
Function is an independent module which contains set of instructions to perform a particular
task.
Why Functions? Or What is the need for functions in C?
Since C is modular programming language, the larger problem or complex problem can sub
divided into smaller problems, each of these smaller problems can be developed
independently by using functions. Hence, by using functions in C, we can have so many
advantages listed below. The process of subdividing larger problem into smaller problem is
called modular approach.
Advantages of Functions
It is easy to read, understand, test, manage, and debug the programs.
Reduces the development time
Reusability of code can be done
We can protect data, since one function cannot access local data of another function.
Complexity of the program can be reduced.
Users can create their own libraries i.e user-defined libraries.
Types of Functions in C
There are two types of functions in C.
a. Standard functions or library functions:
The functions which have pre-defined purpose and readily available for use in header
files are called as standard functions or library functions.
Examples:
sqrt() - used to find square root of a given number. Available in
math.h header file.
sin() - used to find sin(x). Available in math.h header file.
printf() - used to display data in required form. Available in stdio.h
header file.
scanf() - used to read data in required form. Available in stdio.h header
file.
b. User-defined functions:
The functions which are defined by user to perform a specific task are called as user-defined
functions.
Using User-defined functions in C
To understand how to use user-defined functions in C and how program is executed
when functions are used in C, we will start with a simple program and its flow of execution.
One must understand different elements of functions and various statements to be used while
designing functions in C program.
Explanation:
The below shown program illustrates finding a square of a given number using a user-defined
function square(). It also illustrates flow of program execution and the three elements of
function.
Understanding flow of program execution
a. Firstly Operating System will call main function.
b. When control comes inside main function, execution of main starts (i.e execution of C
program starts) and executes Line 5 first
c. Consider Line 6 i.e., result = square(5),
In this statement, a function call is made to the user-defined function square()
which accepts one parameter i.e., 5 to find a square of 5. Hence, it halts or stops the
execution of main function at line 6 and the control is transferred to the function
definition i.e., line 10 as shown with arrow. The value of function parameter is copied
to variable x.
d. Then function definition is executed line by line i.e., from line 10 to line 14.
e. Consider line 14 i.e. return y,
In this statement the value of y i.e. 25 is returned to the calling function i.e.
main function. Hence, the called function i.e., square() completes its execution and
returns the control back to calling function i.e. main function to the line 6 as shown
with arrow. The return value i.e. 25 is copied to variable result.
f. Then main function will resume its execution and executes its statements.
g. Lastly the main function terminates with return value 0 to the operating system.
From the example, we can also define the following basic definitions related to functions of
C.
Calling Function: The function which invokes another function to do something is known as
calling function.
Called Function: The function which is invoked by another function is known as called
function.
Actual Parameters: the parameters in a function call which are used to send one or more
values to the called function are known as actual parameters.
For example:
If a function call is
addition(p,q);
Then in this function call the parameters listed in parenthesis namely variables p and q are
actual parameters whose value is passed to the formal parameters.
Formal Parameters: the parameters in function declaration or definition which are used to
receive one or more values from the calling function are known as formal parameters.
For example:
If a function definition is
void addition(int x, int y)
{
printf(“sum = %d\n”, x+y);
}
In this function definition, the parameters listed in function header namely x and y are formal
parameters which will receive the copy of actual parameters.
Return statement: the statement which is used to return a value to the calling function from
called function is known as return statement.
Function Name: the name given to the function which must be framed with the help of rules
of identifier.
Line 1: #include<stdio.h>
Function Name
Formal Parameters List
Return-Type
r = x+y; Statement
Elements of Function
From the above example, one can observe that to define user-defined functions in C
program, the three elements of functions are very important and need to understand how to
use and purpose of these elements.
Three elements of function are
1. Function Declaration or Function Prototype
2. Function call
3. Function Definition
1. Function Declaration or Function Prototype or Function Header
As we declare variables, arrays, etc, the function must be declared before we use it. The
function declaration tells the compiler that we are going to define this function somewhere in
the program. It gives prior information about the function to the compiler. It contains only a
function header.
The declaration tells the compiler about
Name of the function
Return type of the function
List of formal parameters and their types
Hence, the general format or syntax for declaring function is as given below. The declaration
must end with semicolon.
return-type Function_Name (List of formal parameters) ;
Where,
return-type can be
void type when function doesn‟t return any value
any of the standard data type or user-defined data type when function
returns a value
for example: int, float, double, char, short int, long int, etc
Function_Name can be any name framed by using the rules of identifier
List of formal parameters: refers to zero or more parameters to receive either value
or address of actual parameters.
Format for writing list of formal parameters
Type1 param1, Type2 param2, Type3 param3, …, TypeN paramN
Where,
Type1,Type2, …, TypeN can be any valid data types of C
Param1, param2, …, paramN are names of formal parameters. All names must be
unique. The names must be framed by using rules of identifier.
For example:
a. int addition(int x, int y); // here the function name is addition
which accepts two parameters of type integer and returns an integer value.
b. void square(float a); // here function name is square which
accepts one parameter of floating point type and doesn‟t return any value.
c. char str(char c, int a); // here function name is str which accepts
two parameters one of type character and another of integer type and returns a character.
2. Function Call
Function call is an operator which is used to invoke a function with or without parameters or
arguments known as actual parameters. The actual parameters identify the values or
addresses that are to be sent to the called function. They can contain zero or more parameters.
They must match the functions formal parameters type and order in the parameter list.
Function call statement must end with semicolon.
General Syntax or format of function call is
variable = Fucntion_Name (list of actual parameters) ;
Where,
Variable is one which receives the return value of function if the function return type
is Non-Void. If the function return type is void then variable must be ignored.
Function_Name must match to name of the function which is declared before.
List of actual parameters can be zero or more names of variables to send either value
or address.
For example,
a. sum = addition(p, q); // it invokes function addition with two actual
parameters p and q and return value of function is stored into variable sum.
b. square(x); // invokes a function square with only one actual parameter x
c. ch = str(ch1, x); // invokes a function str with two parameters ch1 and x
and stores the return value in variable ch.
3. Function Definition
The function definition contains the code for a function. It is made up of two parts: the
function header and the function body, which is a block of statements enclosed in pair of
curly braces.
Syntax of function definition is
{
//local declarations
//executable statements
Function Body
// optional return statement
}
A function header consists of three parts: return-type, the function name and list of formal
parameters. A semicolon is not used at the end of the function header.
Function body contains local declarations and the set of executable statements to perform a
particular task.
If the function return-type is void then function definition must not contain return statement
or it can have empty return statement. If the function return-type is non-void then function
definition must return with appropriate type of value using return statement.
For example,
a. int addition(int x, int y)
{
int sum;
sum = x+y;
return sum;
}
In this function definition, x and y are formal parameters, sum is a local variable. The
function returns value of sum using return statement.
b. void square(float x)
{
printf(“square of %f = %f\n” , x, x*x);
}
In this function definition, x is a formal parameter of type float. This function prints
square of x. Function doesn‟t return any value since return type is void hence, it has
no return statement.
int main()
{
int p, q;
printf(“Enter the value for p and q\n”);
scanf(„%d%d”, &p, &q);
printf(“In Main: Before Function Call\n”);
printf(“p=%d, q=%d\n”, p, q);
swap(10,20)
swap(p,q);
Copies value of p=10 to
formal parameter x and
printf(“In Main: After Function Call\n”);
value of q=20 to formal
printf(“p=%d, q=%d\n”, p, q);
parameter y and transfers
return 0;
control to function
}
definition
void swap(int x, int y)
{
int temp;
printf(“In Swap: Before Exchange\n”);
printf(“x=%d, y=%d\n”, x, y);
temp=x;
x=y;
y=temp;
printf(“In Swap: After Exchange\n”);
printf(“x=%d, y=%d\n”, x, y);
}
Output of the above program is
Enter the value for p and q
10 20
In Main: Before Function Call
p=10, q=20
In Swap: Before Exchange
x=10, y=20
In Swap: After Exchange
x=20, y=10
In Main: After Function Call
p=10, q=20
From the above output and flow shown with arrow and text description, we can understand
that the values of actual parameters p and q are copied to formal parameters x and y
respectively. From the bold text of output we can understand that the modification that we
have done for formal parameters in function definition have not affected actual parameters in
calling function hence, the p and q value before function call and after function is same.
int main()
{
Local Declarations
Executable Statements
Functions call
}
Example for Top-Down Approach
//program to print a greeting message using top-down approach
#include<stdio.>
void greeting(void);
int main()
{
greeting();
return 0;
}
void greeting(void)
{
printf(“Good Morning!!!Have a Good Day\n”);
}
Here, in this program main function is designed first which invokes sub function greeting() to
display a greeting message. So sub function is designed later. The program starts its
execution from main function and flows through sub function greeting hence, it is top-down
approach.
Example for Bottom-Up Approach
//program to print a greeting message using bottom-up approach
#include<stdio.>
void greeting(void)
{
printf(“Good Morning!!!Have a Good Day\n”);
}
int main()
{
greeting();
return 0;
}
Here, in this program sub function greeting is designed and developed first then main
function is designed which invokes sub function greeting() to display a greeting message. The
program starts its execution from main function (bottom) then flows through sub function
greeting() (which is above main()) hence, it is bottom-up approach.
V. Function Design
The functions can be designed in four different forms to establish the communications such
as one-way communication or two-way communication. These function designs are
categorized based on return value of the function and parameters accepted by the function. So
they are also called as categories of function designs.
The four different forms or categories of function design are:
1. Void function without parameters
2. Void function with parameters
3. Non-Void function without parameters
4. Non-Void function with parameters
1. Void function without parameters
In this design, the function doesn‟t return any value and doesn‟t accept any parameters so it is
also called as function with no return value and no parameters.
When function doesn‟t return value then return type must be void.
Consider the following example program which performs addition of two integer numbers
with the help of function.
#include<stdio.h>
void addition(void);
int main()
{
addition();
return 0;
}
void addition(void)
{
int p, q,sum;
printf(“Enter p and q\n”);
scanf(“%d%d”, &p, &q);
sum = p + q;
printf(“sum = %d\n”, sum);
}
In this program, the sub function addition() is not returning any value and not even taking any
parameters. The full control is given to sub function which reads two integer numbers,
performs addition and then prints the sum.
2. Void function with parameters
In this design, the function doesn‟t return any value but accepts one or more parameters so it
is also called as function with no return value but with parameters.
When function doesn‟t return value then return type must be void.
Consider the following example program which performs addition of two integer numbers
with the help of function.
#include<stdio.h>
void addition(int x, int y);
int main()
{
int a, b;
printf(“Enter a and b\n”);
scanf(“%d%d”, &a, &b);
addition(a,b);
return 0;
}
void addition(int x, int y)
{
int sum;
sum = x + y;
printf(“sum = %d\n”, sum);
}
In this program, the sub function addition() is not returning any value but taking two
parameters x and y which receives copy of a and b respectively. It is a type of down-ward
one-way communication since, main function i.e calling function is sending data to sub
function addition i.e. called function.
3. Non-Void function without parameters
In this design, the function returns a value but doesn‟t accept any parameters so it is also
called as function with return value and no parameters.
When function returns a value then return type must be non-void.
Consider the following example program which performs addition of two integer numbers
with the help of function.
#include<stdio.h>
int addition(void);
int main()
{
int sum;
sum = addition();
printf(“sum = %d\n”, sum);
return 0;
}
int addition(void)
{
int sum, a, b;
printf(“Enter a and b\n”);
scanf(“%d%d”, &a, &b);
sum = x + y;
return sum;
}
In this program, the sub function addition() is returning an integer value i.e. sum but not
taking any parameters. It is a type of up-ward one-way communication since sub function i.e
called function is sending data to main function i.e. calling function.
4. Non-Void function with parameters
In this design, the function returns a value and also accepts one or more parameters so it is
also called as function with return value and with parameters.
When function returns a value then return type must be non-void.
Consider the following example program which performs addition of two integer numbers
with the help of function.
#include<stdio.h>
int addition(int x, int y);
int main()
{
int a, b, sum;
printf(“Enter a and b\n”);
scanf(“%d%d”, &a, &b);
sum = addition(a,b);
printf(“sum = %d\n”, sum);
return 0;
}
int addition(int x, int y)
{
int sum;
sum = x + y;
return sum;
}
In this program, the sub function addition() is returning an integer value i.e. sum and also
taking two parameters x and y which receives copy of a and b respectively. It is a type of
two-way communication since, main function i.e calling function is sending data to sub
function addition i.e. called function as well as called function is also returning a value to
calling function.
VI. Recursion
Recursion is a process in which a function calls itself. This enables the function to call
several times or repeatedly to solve the given problem. The function which is called
recursively by itself is known as recursive function. Since recursion initiates repetition of
same function there must exist a stopping condition.
The various types of recursion are
a. Direct recursion
b. Indirect recursion
a. Direct recursion
A function that invokes itself is said to be direct recursion.
The following picture depicts the direct recursion
Addition()
Invokes
b. Indirect recursion
A function is recursively invoked by another function then it is known as indirect recursion.
Function1()
Invokes
Function2()
Invokes
In this picture, it illustrates that Function1 is invoking Function2 in turn Function2 is
invoking Function1 hence it forms recursion. Here, Function1 is called recursively by
Function2 and even Function2 is called recursively by Function1 hence, both Function1 and
Function2 are indirect recursive functions.
Example: Program to find the factorial of a given number using recursion.
#include<stdio.h>
int fact (int n)
{
if( n ==0)
return 1;
return n * fact(n-1) ;
}
int main()
{
int N, result;
printf(“Enter the value of N\n”);
scanf(“%d”, &N);
result = fact(N);
printf(“Factorial of %d = %d\n” , N, result);
return 0;
}
To access first element of first row of the array matrix, we can use matrix[0][0], since the
index of first row is ZERO (0) and first column is ZERO (0).
Similarly, second element of first row of the array can be accessed by matrix[0][1], third
element of second row can be accessed by matrix[1][2], etc.
Storing Values in two-dimensional Arrays
Declaration and definition only reserve space for the elements in the array. No values
are stored.
If we want to store values in the array, we can use the following different methods of
initialization
initialize the elements (Initialization)
read values from the keyboard (Inputting)
assign values to each individual element (Assignment)
Initialization of two-dimensional array
Providing a value for each element of the array is called as initialization. The list of
values must be enclosed in curly braces.
NOTE: It is a compile time error if we provide more values than the size of the array.
Example 1: Initializing all elements. All elements are initialized sequentially.
int numbers[3][2] = { 3, 23, 17, 8, 19,7};
In this example, two-dimensional arrays numbers is initialized as given below
Column Index 0 1
Row Index
0 3 23
1 17 8
2 19 7
Inputting Values
Another way to fill the array is to read the values from the keyboard or file by using
scanf statement or fscanf statement.
For Example,
int numbers[3][2];
int i, j ;
for(i=0;i<3;i++)
for(j=0;j<2;j++)
scanf(“%d” , &numbers[i][j]);
In this example, scanf function is repetitively called for 3*2 = 6 times and reads the
values for all elements of the array. Since the starting index of row and column is ZERO, so
index i and j are initialized to 0 in for loop and the condition i<3 iterates 3 times i.e., the
number of rows and the condition j<2 iterates for 2 times i.e., the number of columns.
Assigning values
We can assign values to individual elements using the assignment operator. Any value
that reduces to the proper type of array can be assigned to an individual array element.
For Example,
int numbers[3][3];
numbers[0][0] = 10; //assigns first element of first row to 10
numbers[1][2] = 4; //assigns third element of second row to 4
Process x;
}
Passing Addresses
We pass addresses of the individual elements of the array. The actual parameters in function
call are individual elements of the array whose addresses are copied to the formal parameters.
For example:
Process x;
}
b. Passing the entire array
Passing individual elements of the array is not a feasible method since it requires a lot of
memory and time to process large array. For example, if an array consists of 20000 elements
then if we pass individual elements to the function then another 20000 memory blocks are to
be allocated in function to store the values of each element of the array. So instead of passing
individual elements, starting address of whole array can be passed. Hence, for passing the
entire array, the default method of parameter passing mechanism is pass-by-address or
reference.
NOTE: In C, the name of the array is a primary expression whose
value is the address of the first element in the array.
A pictorial representation of above NOTE is shown below.
int numbers[5];
1000
From the picture, we can understand that the name of array numbers is having the starting
address i.e., 1000 in it. With the help of this address we can go through each and every
element of the array. Hence, to pass the entire array to the function, we can pass only
name of the array which contains starting address.
To pass the whole array, we simply use the array name as actual parameter in a function call.
In function declaration or definition, we can declare a formal parameter in two different
ways.
First, it can use an array declaration with an empty set of brackets in the parameter list.
Secondly, it can specify that the array parameter is a pointer.
Any modification in the function definition by using formal parameter will modify
actual parameter since formal parameter is a reference to the actual parameter.
For example:
void fun (int num[ ],…);
void fun (int *ptr, …);
H e l l o \0
What is important here is that the string “Hello” is stored in an array of characters that ends
with null (\0) character.
NOTE 1: Empty string is represented by “” which requires one byte of memory.
The file pointers are the means to access the file for reading and writing purpose. This
section explains how to read values from the keyboard and how to print the result on the
screen.
C provides two basic ways to read and write strings.
1. Formatted Input and Output Functions: the functions which helps to read and
write the data in the required format are known as formatted input and output
functions
a. Formatted Input Functions: scanf() and fscanf()
b. Formatted Output Functions: printf() and fprintf()
Formatted Input Functions: scanf()
We read strings from the keyboard using the read-formatted function i.e. scanf().
The conversion code for a string is „s‟. Therefore, format string or control string to read a
string is “%s”.
Scanf() do the following work when we enter string from the keyboard
A. First, it removes the whitespaces which appear before the string
B. Once it finds a character, then its starts reading characters until it finds a whitespace
and stores in array in order.
C. Then it ends the string with a null character.
For example:
char str[20];
scanf(“%s”, str); // & operator must not be used since str contains starting
// address of string
If we enter the following string as input from keyboard, then it reads HELLO as string,
terminates it with null character and stores in str. Therefore, str[20] will be “HELLO\0”.
Press
Space Space Space H E L L O Space W O R L D
Enter
In this example, the scanf() has skipped 3 leading white spaces and started reading from the
character „H‟ until a white space. Remaining characters will not be read and left in buffer.
NOTE: The string conversion code skips whitespace.
Drawback of scanf():
The main drawback of this scanf() to read a string is that as soon as it encounters a
white space it stops reading the string. Hence, it is not possible to read a string with multiple
words separated by white space(sentence for example).
2. Unformatted Input and Output Functions: the functions which reads and writes the
data without any format are known as unformatted input and output functions
a. Unformatted Input Functions: gets(), getchar(), getc(), and fgetc()
b. Unformatted Output Functions: puts(), putchar(), putc(), and fputc()
Unformatted Input and output Functions: getchar() and putchar()
The int getchar(void) function reads the next available character from the keyboard and
returns it as an integer. This function reads only single character at a time. You can use this
method in the loop in case you want to read more than one character from the screen.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. You can use this method in the
loop in case you want to display more than one character on the screen.
#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then the program proceeds and reads only a single character
and displays it as follows
./a.out
Enter a value : I am reading a character using getchar
You entered : I
From the output, we can understand that the getchar function reads only single character at a
time i.e I and stores it in variable c. So only, putchar function prints value of variable c i.e. I
on the screen.
putc()
The C library function int putc(int ch, FILE *stream) writes a character (an unsigned char)
specified by the argument ch to the specified stream and advances the position indicator for
the stream.
Declaration
Following is the declaration for putc() function.
int putc(int ch, FILE *stream)
Parameters
char -- This is the character to be written. The character is passed as its int
promotion.
stream -- This is the pointer to a FILE object that identifies the stream where the
character is to be written. It should be stdout to write on screen.
Return Value
This function returns the character written as an unsigned char cast to an int or EOF on
error.
Example
The following example shows the usage of getc() and putc() function.
#include<stdio.h>
int main()
{
char c;
printf("Enter character: ");
c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);
return(0);
}
Let us compile and run the above program that will produce the following result:
Enter character: A
Character entered: A
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then the program proceeds and reads the complete line till
end, and displays it as follows
./a.out
Enter a value : I am reading a line
You entered : I am reading a line
From the output, we can understand that the gets function reads a line at a time i.e I am
reading a line and stores it in variable str. So only, puts function prints value of variable str
i.e. I am reading a line on the screen.
Program: C program to read a sentence and count the frequency of
VOWELs and total count of consonants.
#include<stdio.h>
int main()
{
char sentence[100];
int vowelA=0, vowelE=0, vowelI=0, vowelO=0, vowelU=0, cons=0;
printf(“Enter a sentence\n”);
gets(sentence);
i=0;
while((ch=sentence[i++])! = „\0‟)
{
switch(ch)
{
case „a‟:
case „A‟: vowelA++;
break;
case „e‟:
case „E‟: vowelE++;
break;
case „i‟:
case „I‟: vowelI++;
break;
case „o‟:
case „O‟: vowelO++;
break;
case „u‟:
case „U‟: vowelU++;
break;
default: cons++;
}
}
int length;
length = strlen(str);
Output:
length=5 since, strlen() returns length of string i.e. 5 since the string constant
“Hello” is having 5 characters.
Example 2: int len;
len = strlen(“Hello World”);
Output:
len=11, since there are 11 characters in string constant “Hello World”
Example 2:
char str[20];
strcpy(str, “Hello World”); // copies string literal to str
printf(“str = %s\n” , str);
Output:
str = Hello World since strcpy copies string constant i.e “Hello World” to
str. Therefore, str will be “Hello World”.
Example 2:
char str[20];
strcpy(str, “Hello World”, 7); // copies first 7 characters of string literal to str
printf(“str = %s\n” , str);
Output:
str = Hello W since strcpy copies first 7 characters of string constant
to str. Therefore, str will be “Hello W”.
Example 3:
char src[20] = “Hello”;
char dest[20];
strcpy(dest, src, 20); // copies first 20 characters of src to dest
printf(“dest = %s\n” , dest);
Output:
dest = Hello since the length of string src is 5 which is less than 20 so it copies entire string
in src to dest. Therefore, dest will be “Hello”.
Example 2:
char string1[20] = “Hello”;
char string2[20] = “World”;
strcat(string1, string2, 20);
printf(“String 1 =%s\n”, string1);
Output:
String 1 = HelloWorld since length of string2 is less than 20 so entire source string is
concatenated with string1. Therefore, string1 = “HelloWorld”.
Example 1:
char string1[20] = “Hello”;
char string2[20] = “Hello”;
n = strcmp(string1, string2);
Output:
n = 0 since string1 and string2 are equal
Example 2:
char string1[20] = “Hello”;
char string2[20] = “World”;
n = strcmp(string1, string2);
Output:
n = less than 0 since string1 is less than string2
Example 3:
char string1[20] = “Welcome”;
char string2[20] = “Hi”;
n = strcmp(string1, string2);
Output:
n = greater than 0 since string1 is greater than string2
Example 1:
char string1[20] = “Hello”;
char string2[20] = “Hello”;
X = strncmp(string1, string2, 3);
Output:
X = 0 since first 3 characters of string1 and string2 are equal
Example 2:
Example 3:
char string1[20] = “Welcome”;
char string2[20] = “Hi”;
X = strncmp(string1, string2,1);
Output:
n = greater than 0 since first 1 character of string1 is greater than string2
char *s;
char buf [] = "This is testing";
s = strchr (buf, 't');
if (s != NULL)
printf ("found a 't' at %s\n", s);
Output:
It will produce following result
found a „t‟ at ting
k. strtok() - parse or split the string into tokens using specified delimiters
Definition:
The strtok function is used to locate substrings known as tokens in a string. Its most
common use is to split or parse the given string into tokens using one or more delimiters.
Syntax:
strtok(string, delimiters)
where,
string - can be either C string or string literal which is to be parsed
delimiters - one or more characters to be used to split or parse the given string
Example:
char| string[ ] = “ONE,TWO-THREE”;
strtok(string, “,-”);
In this example, the two delimiters specified are comma(,) and hypen(-) hence the given
string “ONE,TWO-THREE” is parsed or split into three substrings namely “ONE” , “TWO”
and “THREE”.
Output:
“ONE”
“TWO”
“THREE”‟
XII. Array of Strings
As we know the definition of string is that it is an array of characters, then array of strings
can be defined as array of array of characters. Hence, array of strings is basically an
application of two-dimensional arrays. Each string is independent and at the same time they
are grouped together through the array.
For example, if we need to store seven days of the week in the array then we have to arrange
these as array of strings since we have to store seven days of the week and each day of the
week is again an array of characters so it is two-dimensional array.
Declaration of array of strings
#define days 7
#define size 15
char week[days][size];
In this example, two-dimensional array called week is been created with seven days and each
day can have maximum of 15 characters.
Initialization of array of strings
a. Initialization with SIZE
#define days 7
#define size 15
char week[days][size] = {“Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”, “Sunday” };
Pictorial representation of array of string is shown below
M O N D A Y \0
T U E S D A Y \0
W E D N E S D A Y \0
T H U R S D A Y \0
F R I D A Y \0
S A T U R D A Y \0
S U N D A Y \0
}
dest[len]='\0';
}
int main(void)
{
char dest[20]="ABCD",src[20]="EFG";
strconcat(dest,src);
printf("After concatinating the strings, destination string is %s\n",dest);
return 0;
}
3. Write a C Program to find length of a string without using built in function strlen().
#include<stdio.h>
#include <string.h>
int strlength(char src[])
{
int i=0;
// start finding the length from first char to last char
while (src[i]!= „\0‟)
i++;
return i;
}
int main(void)
{
char src[20];
printf(“Enter a string\n”);
scanf(“%s”, src);
printf("Length of %s string=%d\n", strlength(src));
return 0;
}
5. Write a C program using recursion to print prime numbers between 1 and 100.
#include<stdio.h>
int isprime(int n, int p)
{
if (p==1)
return 1;
else if (n%p==0)
return 0;
else
return isprime(n,p-1);
}
int main(void)
{
int i;
printf("The prime numbers are :");
for (i=2;i<100;i++)
if (isprime(i, i/2)==1)
printf("%d ",i);
return 0;
}
6. Write a C Program to find the greatest number from a given one dimensional array.
#include<stdio.h>
int main()
{
int arr[20], i, large, n;
printf(“Enter number of elements\n”);
scanf(“%d”, &n);
printf(“Enter %d elements\n”, n);
for(i=0; i<n; i++)
scanf(“%d”,&arr[i]);
printf(“The largest element is: “);
large = a[0];
for(i=1; i<n; i++)
{
if(a[i] > large)
large = a[i];
}
printf(“%d”, large);
return 0;
}
9. Write a C program to read a matrix of size MxN and find the following
I. The sum of elements of each row
II. The sum of elements of each column
III. Total sum of all elements of matrix
#include<stdio.h>
int main( )
{
int a[10][10], i, j , rsum, csum, tsum=0, m, n;
printf(“\n Enter the order of matrix:”);
scanf(%d%d”,&m, &n);
printf(“\n Enter elements of matrix \n”);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
scanf(“%d”, &a[i][j]);
for(i=0; i<m; i++)
{
rsum=0;
csum=0;
for(j=0; j<n; j++)
{
rsum = rsum +a[i][j];
csum = csum + a[j][i];
}
tsum = tsum + rsum
printf(“Sum of %d row = %d\n”, i+1, rsum);
printf(“Sum of %d columns = %d\n”, i+1, csum);
}
printf(“Total sum of all elements = %d\n”, tsum);
return 0;
}
10. Write a C program to find the largest element in a two dimensional array.
#include<stdio.h>
int main( )
{
int i, j, a[10][10], large, m, n;
printf(“\n Enter the order of matrix:”);
scanf(%d%d”,&m, &n);
printf(“\n Enter elements of matrix \n”);
11. Write a C program to find the addition of two matrices a and b. Print the
resultant matrix.
#include<stdio.h>
int main( )
{
int i, j, a[10][10], b[10][10], c[10][10], m, n;
printf(“\n Enter the order of matrix a:”);
scanf(%d%d”,&m, &n);
printf(“\n Enter elements of matrix A\n”);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
scanf(“%d”, &a[i][j]);
printf(“\n Enter elements of matrix B\n”);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
scanf(“%d”, &b[i][j]);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
c[i][j] = a[i][j] + b[i][j];
printf(“Resultant matrix C is:”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
printf(“%5d”, c[i][j]);
printf(“\n”);
}
return 0;
}
12. Write a C program that reads N integer numbers and arrange them in ascending
order using Bubble Sort technique.
#include<stdio.h>
int main()
{
int n, i, j, a[10], temp;
printf("Enter the no of elements:\n");
scanf("%d", &n);
printf("\n Enter %d elements\n", n);
for(i=0; i<n; i++)
scanf("%d",&a[i]);
printf("The original elements are:\n");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
for(i=0; i<n-1; i++)
{
for(j=0; j<n-1-i; j++)
{
if(a[i] >a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\n The Sorted array is :\n");
for(i=0;i<n;i++)
printf("%d\n", a[i]);
return 0;
}
13. Write a C program to search a Name in a list of names using Binary searching
Technique.
#include<stdio.h>
int main()
{
char arr[25][20], key[25];
int i, n, low, high, mid, cond;
printf("Enter the number of strings you want to enter\n");
scanf("%d", &n);
printf("Enter %d strings in alphabetical order\n", n);
for (i=0; i<n; i++)
scanf("%s", arr[i]);
printf("Enter string to be searched\n");
scanf("%s", key);
low = 0;
high = n-1;
while(low <= high)
{
mid = (low + high) / 2;
if((cond = strcmp(key, arr[mid])) == 0)
{
printf("Key found at %d position\n", mid+1);
return 0;
}
else if(cond< 0)
high = mid - 1;
else
low = mid + 1;
}
printf("String %s is not found\n", key);
return 0;
}
14. Write a C program to search a number in a list of numbers using Binary searching
Technique.
#include<stdio.h>
int main()
{
int arr[25], key;
int i, n, low, high, mid, cond;
printf("Enter the number of elements you want to enter\n");
scanf("%d", &n);
printf("Enter %d numbers\n", n);
for (i=0; i<n; i++)
scanf("%d", &arr[i]);
printf("Enter the number to be searched\n");
scanf("%d", &key);
//first sort all the elements in ascending order using bubble sort
for(i=0; i<n-1; i++)
{
for(j=0; j<n-i-1; j++)
{
if(a[j]>a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
// search for a number using binary search
low = 0;
high = n-1;
while(low <= high)
{
mid = (low + high) / 2;
if(key == arr[mid])
{
printf("Key found at %d position\n", mid+1);
return 0;
}
else if(key < arr[mid])
high = mid - 1;
else
low = mid + 1;
}
printf("key %d is not found\n", key);
return 0;
}
Output:
Enter any non-zero integer:
7
Number is positive number
In the above example, the program reads a integer number from user and
checks is it greater than zero if true the it displays a message “Number is positive
number” otherwise it does nothing. Hence, it considers only one alternative.
Flowchart of if statement
if False
expression
True
Statement 1
Next-Statement
True if False
expression
Statement 1 Statement 2
Next-Statement
prints “Number is negative number”. Hence, it selects only one from two alternatives,
so only it is called as two-way selection.
The one of the drawback of this nested if statement is as the number of levels of
nesting increases, the complexity increases and it makes difficult to understand and
trace the flow of execution.
if
TRUE FALSE
expr1?
if if
TRUE FALSE TRUE FALSE
expr2? expr3?
Next-Statement
Example: Program to select and print the largest of the 3 numbers using nested
“if-else” statements.
#include<stdio.h>
int main()
{
int a,b,c;
printf(“Enter Three Values: \n”);
scanf(“%d %d %d ”, &a, &b, &c);
printf(“Largest Value is: ”) ;
if(a>b)
{
if(a>c)
printf(“ %d ”, a);
else
printf(“ %d ”, c);
}
else
{
if(b>c)
printf(“ %d”, b);
else
printf(“ %d”, c);
}
return 0;
}
Output:
Enter Three Values:
17 18 6
Largest Value is: 18
if
FALSE
expression1?
TRUE
if
FALSE
expression2?
Statement1
TRUE
if
expression3?
Statement2
Statement3
Next-Statement
Example: Program to select and print the largest of the 3 numbers using
“else…if ladder” statements.
#include<stdio.h>
int main()
{
int a,b,c;
e. switch Statement:
This is a multi-branch statement similar to the else…if ladder (with limitations) but
clearer and easier to code. This is used when we must choose among many
alternatives. This statement is to be used only when we have to make decision using
integral values (i.e., either integer values or characters).
Why we should use Switch statement?
1. One of the classic problems encountered in nested if-else / else-if ladder is
called problem of Confusion.
2. It occurs when no matching else is available for if.
3. As the number of alternatives increases the Complexity of program increases
drastically.
To overcome these, C Provides a multi-way decision statement called „Switch
Statement‟
Syntax:
switch ( expression )
{
case label1 :
statement1 ;
break ;
case label2 :
statement2 ;
break ;
...
default : statement ;
}
Where,
if
expression
Next-Statement
break ;
case '-' : result = num1 - num2 ;
break ;
case „*‟: result = num1 * num2 ;
break ;
case „%‟: result=num1%num2;
break;
case „/‟ : if ( num2 != 0.0 )
{
result = num1 / num2 ;
break ;
}
// else we allow to fall through for error message
default : printf ("ERROR -- Invalid operation or division by 0.0" ) ;
}
printf( "%f %c %f = %f\n", num1, op, num2, result) ;
return 0;
}
Note : The break statement need not be included at the end of the case statement body
if it is logically correct for execution to fall through to the next case statement (as in
the case of division by 0.0) or to the end of the switch statement (as in the case of
default : ).
Output:
Enter number operator number
2+4
2+4=6
small=A;
else
small=B;
printf(“Smallest of %d and %d = %d\n” , A, B, small);
return 0;
}
8. WACP to find a given year is leap year or not using ternary operator.
Program:
#include<stdio.h>
int main()
{
int year;
printf(“Enter a year\n”);
scanf(“%d” , &year);
(year%4 = = 0 && year%100 != 0 || year%400 = = 0) ? printf(“%d is a Leap
Year\n” , year) : printf(“%d is Not a Leap Year\n” , year);
return 0;
}
else
{
if(B<C)
small=B;
else
small=C;
}
printf(“Smallest of %d, %d and %d is = %d\n” , A, B, C, small);
return 0;
}
else
small = C;
printf(“Smallest of %d, %d and %d is = %d\n” , A, B, C, small);
return 0;
}
return 0;
}
if ( A > B )
printf(“%d is Larger than %d\n”, A, B);
else
printf(“%d is Equal to %d\n”, A, B);
}
else
printf(“%d is Smaller than %d\n”, A, B);
return 0;
}
22. WACP to find the roots of a quadratic equation using else…if ladder
or cascaded if statement.
PROGRAM:
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c;
float r1, r2, d;
printf("Enter the coefficients a,b, and c:\n");
scanf("%f%f%f", &a, &b, &c);
if (a!=0 && b!=0 && c!=0)
{
d=(b*b)-(4*a*c);
if (d>0)
{
printf("roots are real and distinct :\n");
r1 = (-b+sqrt(d))/(2*a);
r2 = (-b-sqrt(d))/(2*a);
printf("root1=%f \n root2=%f\n", r1, r2);
}
else if (d<0)
{
printf ("roots are imaginary : \n");
r1 = -b/(2*a);
r2 = sqrt(fabs(d))/(2*a);
printf("root1=%f + i %f \n root2=%f – i %f\n", r1, r2, r1, r2);
}
else
{
printf ("roots are real and equal: \n");
r1 = -b/(2*a);
r2 = r1;
printf("root1=%f \n root2= %f \n", r1, r2);
}
}
else
printf("All coefficients must be non zero \n");
return 0;
}
char grade;
printf(“Enter the marks obtained by a student\n”);
scanf(“%d”, &marks);
if ( marks >= 90 )
grade=‟S‟ ;
else if ( marks >= 80 )
grade=‟A‟ ;
else if ( marks >= 70 )
grade=‟B‟ ;
else if ( marks >= 60 )
grade=‟C‟ ;
else if ( marks >= 50 )
grade=‟D‟ ;
else if ( marks >= 40 )
grade=‟E‟ ;
else
grade=‟F‟ ;
printf(“Grade of a Student = %c \n”, grade);
return 0;
}
break;
case 4: grade = „E‟;
break;
default: grade = „F‟;
}
printf(“Grade of a Student = %c \n”, grade);
return 0;
}
return 0;
}
char ch;
printf(“Enter a character \n”);
scanf(“%c”, &ch);
if ( ch = = „a‟ || ch = = „A‟ )
printf(“%c is Vowel \n”, ch);
else if if ( ch = = „e‟ || ch = = „E‟ )
printf(“%c is Vowel \n”, ch);
else if if ( ch = = „i‟ || ch = = „I‟ )
printf(“%c is Vowel \n”, ch);
else if if ( ch = = „o‟ || ch = = „O‟ )
printf(“%c is Vowel \n”, ch);
else if if ( ch = = „u‟ || ch = = „U‟ )
printf(“%c is Vowel \n”, ch);
else
printf(“%c is not a Vowel \n”, ch);
return 0;
}
In example 1, since the first statement is goto label1 it jumps to label1 and starts
executing the statement4 as shown with arrows. Hence the jump is made in
forwarding direction.
In example 2, it first executes statements 1, 2 and 3 in sequence then because of the
statement goto label2, it jumps to label2 and starts executing the statements 1, 2, and
3 and repeats the same process as shown with arrows. Hence the jump is made in
backward direction and forms a loop.
From the example 2, we can understand one of the main drawback of using goto
statement is that it forms infinite loop (i.e., loop that never ends) since it is
unconditional jump statement.
Another drawback of using goto statement is that it is used to transfer the control only
within the function but cannot be used to jump between functions.
NOTE: Try to avoid using goto statement. It‟s a bad practice of using goto in a
program.
Example: Program to detect the entered number is even or odd using goto statement.
#include<stdio.h>
int main()
{
int x;
printf(“Enter a Number: \n”);
scanf(“%d”, &x);
if(x % 2 = = 0)
goto even;
else
goto odd;
even : printf(“%d is Even Number” , x);
return 0;
odd : printf(“ %d is Odd Number” , x);
return 0;
}
Output 1:
Enter a Number: 5
5 is Odd Number.
Output 2:
Enter a Number: 8
8 is Even Number.
b. break statement
The break statement can be used in any looping statements and switch
statement.
When a break statement is encountered inside a while, for, do…while statement, then
break statement immediately terminates the entire loop and jumps out of the loop and
resumes execution at the next statement following the loop (if any).
When a break statement is encountered inside a switch statement case, then break
statement will terminate the corresponding switch case and transfers the control out of
switch statement and resumes the execution at the next statement following the switch
statement (if any).
Example 1:-
...
for ( x = 1 ; x <= 10 ; x++ )
{
if ( x > 4 )
break ;
printf( “%d “ , x ) ;
}
printf( "Next Statement\n" );
true then it executes the break statement that terminates the remaining iterations of for
loop and transfers control out of loop and continues with the next statement after for
loop i.e. it executes printf statement. Therefore it prints 1 2 3 4 Next Statement as
output.
Example 2:-
switch (ch)
{
case 1: s1;
break;
…………
…………
}
Next-Statement;
In the above example, if value of ch matches with case 1 then it executes statement s1
followed by break statement. After executing break statement the control is
transferred to out of switch statement i.e. Next-Statement.
c. continue statement
The continue statement can be used only in looping statements.
The continue statement terminates the current iteration of a while, for or
do…while statement and resumes execution of next iteration of the loop.
For Example :-
...
for ( x = 1; x <= 5; x++ )
{
if ( x = = 3 )
continue ;
printf( “%d “, x ) ;
}
Looping statements:
The statements that help us to execute set of statements repeatedly are called as
looping statements.
The concept of loop is shown in the following flowchart.
In this flowchart, the action is repeated over and over again. It never stops.
Since the loop never stops, the action or actions will be repeated forever. We don‟t
want this to happen; we want our loop to end when the work is done. To make sure that it
ends, we must have a condition that controls the loop. The condition which is used to control
the loop is called as loop control expression.
Based on the placement of loop control expression, the loops are classified as TWO types
i. Entry controlled loop or Pre-Test Loop:
In the entry controlled loop or Pre-Test loop, the loop control expression is
checked before we start and at the beginning of each iteration of the loop. If the
control expression is true, we execute action or actions; if the control expression is
false, we terminate the loop.
Examples:
while statement and for statement
ii. Exit controlled loop or Post-Test Loop
In the exit controlled loop or Post-Test loop, the loop control expression is
checked after or at the end of each iteration of the loop. If the control expression is
true, we repeat action or actions; if the control expression is false, we terminate the
loop.
Examples:
do…while statement
The flowchart of entry controlled and exit controlled loops and other differences between
the two are given below.
Entry Controlled or Pre-Test Loop Exit Controlled or Post-Test Loop
The loop control expression is checked The loop control expression is checked after
before we start and at the beginning of each or at the end of each iteration of the loop
iteration of the loop
Flowchart: Flowchart:
Control Expression
TRUE FALSE
An Action or Series of
An Action or Series of Actions
Actions
TRUE
Control Expression
False
Minimum Iterations: Atleast ZERO Times Minimum Iterations: Atleast ONE Times
If the control expression is TRUE for N If the control expression is TRUE for N
times, then action or actions are executed for times, then action or actions are executed for
N times N+1 times
Examples: for loop and while loop Example: do…while loop
Prints numbers from 1 to 10 Prints numbers from 1 to 10
i=1; i=1;
while( i<=10) do
{ {
printf(“%d\n”, i); printf(“%d\n”, i);
i++; i++;
} }while(i<10);
Initialization: Before a loop can start, some preparation is usually required. We call this
preparation as initialization. Initialization must be done before the execution of the loop
body. Initialization sets the variable which will be used in control expression to control the
loop.
Updating: how can the control expression that controls the loop be true for a while and then
change to false? The answer is that something must happen inside the body of the loop to
change the control expression. Otherwise, the loop leads to infinite loop. Hence, the actions
that cause these changes are known as update.
a. while statement
The while statement is typically used in situations where it is not known in advance
how many iterations are required.
Syntax:
while ( control expression )
{
An action or Series of Actions ; //body of loop
}
Initialization
Control Expression
TRUE FALSE
An Action or Series of
Actions
Updating
b. for statement
The for statement is most often used in situations where the programmer knows in
advance how many times a particular set of statements are to be repeated. The for
statement is sometimes termed as counter controlled loop.
Syntax :
for ( expression1 ; expression2 ; expression3 )
{
An action or series of actions ; // body of loop
}
Where,
expression1:- This is usually an assignment/initialization statement to set a loop
control variable(s) for example. But it is not restricted to only initialization, it can be
any valid C statement.
expression2:- This is usually a control expression which determines when loop will
terminate. But, this can be any statement of C that evaluates to TRUE or FALSE.
expression3:- This usually defines how the loop control variable(s) will change each
time the loop is executed i.e. updating.
Body of loop:- Can be a single statement, no statement or a block of statements.
NOTE: All three expressions are optional. But semicolons must be present as in
syntax in the loop.
Curly braces are used in C to denote block whether in a function as in main() or as the
body of a loop. It is optional if body of loop is a single statement or no statement.
The for statement executes as follows:
Example 1: Program to sum all numbers from 1 to 100.
#include <stdio.h>
int main()
{
int x, sum=0 ;
for ( x = 1; x <= 100; x++ )
sum = sum + x;
printf(“Sum = %d\n”, sum);
return 0;
}
Expression1
Expression2
TRUE FALSE
An Action or Series of
Actions
Expression3
printf( "%d\n", x ) ;
For Example 3:- An infinite loop may be created as follows
for ( ; ; )
body of loop;
For Example 4:- Sometimes a for statement may not even have a body to execute as in
the following example where we just want to create a time delay.
for ( t = 0; t < big_num ; t++ )
;
For Example 5:- expression 3 is a printf statement. This example prints from 1 to 100.
for ( x = 1; x <= 100; printf( "%d\n", x++ ) ) ;
For Example 6:- The expression1, expression2 and expression3 sections of the for
statement can contain any valid C expressions.
for ( x = 12 * 4 ; x < 34 / 2 * 47 ; x += 10 )
printf( “%d “, x ) ;
Nested for loops:- It is possible to build a nested structure of for loops, for example
the following creates a large time delay using just integer variables.
unsigned int x, y ;
for ( x = 0; x < m; x++ )
for ( y = 0; y < n; y++ )
;
In this example, the outer for loop will iterate for „m‟ times and inner loop will
iterate for „n‟ times, hence the total iterations from nested loop is m*n times.
For Example: Program to produce the following table of values
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
#include <stdio.h>
int main()
{
int j, k ;
for ( j = 1; j <= 5; j++ )
{
for ( k = j ; k < j + 5; k++ )
{
printf( "%d ", k ) ;
}
printf( “\n” ) ;
}
return 0;
}
c. do…while statement
The terminating condition in the for and while loops is always tested before
the body of the loop is executed -- so of course the body of the loop may not be
executed at all.
In the do…while statement on the other hand the body of the loop is always
executed at least once as the condition is tested at the end of the body of the loop.
Syntax :
Initialization
do
{
An action or Series of Actions ; // body of loop
Updating
} while ( control expression ) ;
The flow of do…while loop is shown below
Initialization
An Action or Series of
Actions
Updating
TRUE
Control Expression
FALSE
10. WACP to print alternate uppercase letters starting with letter „A‟.
Program:
#include<stdio.h>
int main()
{
char ch;
printf(“Alternate Uppercase letters starting with letter A are:\n”);
for(ch=‟A‟; ch<=‟Z‟; ch= ch + 2)
printf(“%c\n”, ch);
return 0;
}
11. WACP to find the GCD of two numbers using while and ternary
operator.
Program:
#include<stdio.h>
int main()
{
int M, N, GCD, P,Q;
printf(“Enter the value of M and N\n”);
scanf(“%d%d” , &M, &N);
P=M;
Q=N;
while (M != N)
(M>N) ? M = M – N : N = N – M ;
GCD=M;
printf(“ GCD ( %d, %d) = %d\n”, P,Q, GCD);
return 0;
}
12. WACP to find the GCD of two numbers using while and if else
statement.
Program:
#include<stdio.h>
int main()
{
int M, N, GCD, P,Q;
printf(“Enter the value of M and N\n”);
scanf(“%d%d” , &M, &N);
P=M;
Q=N;
while ( M != N )
{
if (M>N)
M = M – N;
else
N=N–M;
}
GCD=M;
printf(“ GCD ( %d, %d) = %d\n”, P, Q, GCD);
return 0;
}
{
printf(“%d is not a prime number\n”, N);
return 0;
}
}
printf(“%d is a prime number\n”, N);
return 0;
}