PC UNIT-2 Material
PC UNIT-2 Material
Syllabus
Strings.
Decision statements (or) selection statements (or) conditional statements:
If statement
Switch statement
These statements are popularly known as decision-making statements. Since these statements
control the flow of execution, they are also known as control statements.
The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. It takes the following form:
If (test-expression)
It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is true or false, it transfers the control to a particular statement.
simple – if statement
if – else statement
nested – if else statement
Else – if ladder
Switch statement
1. Simple – if statement
Syntax :
if (condition)
Statement-block;
Statement-x;
Note: When the condition is true, both the statement-block and the statement-x are executed
in sequence.
Flow chart
Con
True ditio False
Statement (s)
main ( )
int a;
if (a>50)
Output
2. if … else statement
The if … else statement is an extension of simple if statement. It takes the following general
form
Syntax:
if (condition)
else
statement-x
If the condition is true, then the true-block statement(s), immediately following the if
statements are executed.: otherwise, the false-block statements are executed. In either case,
either true-block or false-block will be executed, not both. In both cases, the control is
transferred subsequently to the statement-x.
Flow chart
Program
main ( )
int n;
if (n%2 ==0)
else
Output
If---else statement inside another if---else statement is called as nested if---else statement.
When a series of decisions are involved, we may have to use more than one if…else
statement in nested form.
Syntax:
if (condition1)
if (condition2)
stmt1;
else
{
stmt2;
else
if (condition3)
stmt3;
else
stmt4;
Flow chart
main ( )
int a,b,c;
if (a>b)
I f (a>c)
else
else
if (b>c)
Output
enter 3 numbers = 10 20 30
30 is largest
4. Else – if ladder
This is the most general way of writing a multi-way decision. A multi-way decision is a chain
of ifs in which the statement associated with else is an if. It takes the following general form
Syntax
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
else if (condition n)
stmnt;
else
stmt x ;
flow chart
Stmt1
------
Stmt2
Cond
True ition False
Stmt n Stmt x
#include <math.h>
main ( )
int a,b,c,d;
float r1, r2
printf (“enter a,b,c values”);
d= b*b – 4*a*c
if (d>0)
r1 = (-b+sqrt(d)) / (2*a);
r2 = (-b-sqrt(d)) / (2*a);
else if (d= = 0)
r1 = -b / (2*a);
r2 = -b/ (2*a);
else
Output
Root 1 = -1
Root 2 = -3
Root 2 = -1
Switch statement
C has a built-in multiway decision statement known as switch. It is used to select one among
multiple decisions. The switch statement tests the value of a given variable (or expression)
against a list of case values and when a match is found, a block of statements associated with
that case is executed.
Syntax
switch (expression)
break;
break;
------
default : stmt – x;
}
Flow chart
Switch
(express
ion)
Exp =value2
Stmt2
default Stmt-x
When the switch is executed, the value of the expression is successfully compared
against the values value-1,valu-2,---. If a case is found whose values match with value of the
expression, then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes exit from the switch statement, transferring the control to the statement-x following
the switch.
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values. If not present, no action takes place if
all matches fail and the control goes to the statement-x.
Program
main ( )
int n;
switch (n)
break;
break;
Output
enter a number
1
one
It i1s possible to nest the switch statements. That is, a switch may be part of a case statement.
ANSI C permits 15 levels of nesting.
Looping or iterative statements are used for running a particular set of code for any number
of times. Iterative statements consist two parts—head and body. The head of the statement
decides the number of times the body of the statements are to be executed.
In looping, a sequence of statements are executed until some conditions for the termination of
the loop are satisfied.
They are
for loop
while loop
do-while loop
for loop
The for loop is an entry-controlled loop that provides loop control structure. The general form
of the for loop is
Syntax
Flow chart
False
Initialization Increment/
condition decrement
True
initialization is usually an assignment statement that is used to set the loop control variable
The condition is a relational expression that determines when the loop will exit.
The increment/decrement part defines how the loop control variable will change each time
loop is repeated
Once the condition is false, program continues with the next statement after for loop.
1) Initialisation of the control variable is done first, using assignemnt statements such as i=1
and count=0. The variables i and count are known as loop-control variabels.
2) The value of the control variable is tested using the test-condition. The test-condition os a
relational expression, such as i<10 that determines when the loop will exit. If the condtiion is
true, the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
3) When the body of the loop is executed, the control is transfered back to the for statemetn
after evaluating the last staement in the loop. Now the control variable is incremented using
an assignement statement such as i=i+1 and the new value of the control variable is again
tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of
the loop is again executed. This process continues till the value of the control variable fails to
satisfy the test-condition.
Program
main( )
Output
{
1
3
4
int k;
printf (”%d”,k);
Note that the initialization section has two parts i=1 and j=0 seperated by comma.
Like the initialization section, the increment section may also have more than one
part. The multiple arguments in the increment section are separated by commas.
Ex: for(i=1 , j=10; i <= j; i++, j--)
Further, the test-condition may have any compound relation and the testing need not
be limited only to the loop control variable.
Ex:
sum = 0;
{
sum=sum + i;
Another unique aspect of for loop is that one or more sections can be omitted, if
necessary.
Ex:
m = 5;
for( ; m != 100 ; )
m = m + 5;
Here both initialization and increment sections are omitted in the for statement. The
initilisation has been done before the for statement and the control variable is incremented
inside the loop. In such cases the sections are left blank. However, the semicolons separating
the sections must remain. If the test-condtion is not present, the for statement sets up an
infinite loop.
Nesting of loops, that is, one for statement within another for statement, is allowed in C. For
example two loops can be nested as shown bellow
-----------------------------------
------------------------------------
----------------------
for( j = 1; j != 5; ++j)
-----------------------
-----------------------
------------------------------
-----------------------------
while loop
Syntax
while (condition)
The while is an entry-controlled loop statement. The condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test-
condition is once again evaluated and if it is true, the body is executed once again. This
process of repeated execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop. On exit, the program continues with the
statement immediately after the body of the loop.
Flow chart initialization
Is
expressio False
True
Incr/ dec
Program
main( )
Output
{
1
int k;
2
k = 1;
3
4
while (k< = 5)
printf (”%d”,k);
k++;
do-while loop
The while loop construct, makes a test of condition before the loop is executed. Therefore,
the body of the loop may not be executed at all if the condition is not satisfied at the very first
attempt. In some situations it might be necessary to execute the body of the loop before the
test is performed. Such situations can be handled with the help of the do- while statement.
Syntax
Initialization
do
inc/ dec
} while (condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At
the end of the loop, the condition in the while statement is evaluated. If the condition is true,
the program continues to evaluate the body of the loop once again. This process continues as
long as the condition is true. When the condition becomes false, the loop will be terminated
and the control goes to the statement that appears immediately after the while statement.
Since the condition is evaluated at the bottom of the loop, the do---while construct provides
an exit-controlled loop and, therefore, the body of the loop is always executed atleast once.
Flow chart
initialization
True
Is
expressio
Incr/ dec
Flase
Program
main( )
Output
{
1
int k;
2
k = 1;
3
do
4
{
printf (”%d”,k);
k++;
} while (k == 5);
break
continue
goto
An early exit from a loop can be accomplished by using the break statement or goto
statement. break statement can be used within while, do-while, for and switch statement. The
use of break in loops is illustrated in following fig:
Summary:
It is a keyword used to terminate the loop (or) exit from the block
The control jumps to next statement after the loop (or) block
When break is used in nested loops then only the innermost loop is terminated
When a break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are
nested, the break would only exit from the loop containing it. That is, the break will exit only
a single loop.
Program
main( )
Output
{ int i;
1
3
for (i=1; i<=5; i++)
if (i= =3)
break;
Like the break statement, C supports another similar statement called the continue
statement. However, unlike the break statement that causes the loop to be terminated, the
continue, as the name implies, causes the loop to be continued with the next iteration after
skippin any statements in between. The continue statement tells the compiler, “skip the
following statements and continue with the next iteration”.
Syntax
Stmt1;
Stmt2;
continue;
Stmt3;
Stmt4;
}
Program
Output
main( )
1
{
3
int i;
4
for (i=1; i<=5; i++)
5
{
if (i= =2)
continue,
printf(“%d”, i)
3) goto
C supports the goto statement to branch unconditionally from one point to another in the
program. The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid name, and must be followed by a colon( : ) . The label is placed
immediately before the statement where the control is to be transferred. The general form of
goto is shown in fig
---- ----
---- ----
---- ----
The label : can be anywhere in the program either before or after the goto label; statement.
During running of a program when a statement like goto begin; is met, the flow of control
jumps to the statement immediately following the label begin. This happens unconditionally.
Note that a goto breaks the normal sequential execution of the program. If the label: is
before the statement goto label; a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is
placed after the goto label; some statements will be skipped and the jump is known as a
forward jump.
Program
Output
main( )
Hello
{
you
printf(’Hello”);
goto l1;
printf(”How are”);
l1: printf(”you”);
}
Introduction to Arrays
ARRAYS
Array: An array is a sequenced collection of related data items that share a comman
name
A particular value in an array is identified using its “index number” or “subscript”
Advantage
The ability to use a single name to represent a collection of items and to refer to an item by
specifying the item number enables the user to develop concise and efficient programs
An array must be declared and defined before it can be used. Array declaration and definition
tell the compiler the name of the array, the type of each element, and the size or number of
elements in the array.
Eg:
2. int group[10]
int a[5];
a[1]
a[2]
a[3]
a[4]
First element is identified by subscript ‘zero’ i.e., a[0] represents first element of the
array.
If there are ‘n’ elements in array then subscripts range from 0 to n-1
Array Initialization
Here 5 elements are stored in array ‘a’. The array elements are stored sequentially in separate
locations.
Reading of array elements begins from ‘0’. Array elements are called by array names
followed by the element numbers.
Ex: a[0]
Any reference to the arrays outside the declared limits would not necessarily cause an error.
Rather it might result in unpredictable program results.
Character array
The C language treats character strings simply as arrays of characters. The size in a character
string represents the maximum number of characters that the string can hold.
declares the name as a character array(sring) varalbe that can hold a maximum of 10
characters. Suppose we read the following string constant into the string variable name.
“WELL DONE”
Each character of the string is treated as an element of the array name and is stored in the
memory as follows
‘W’
‘E’
‘L’
‘D’
‘O’
‘N’
‘E’
‘\0’
When the compiler sees a character string, it terminates it with an additional null character(‘\
0’). Thus, the element name[10] holds the null character ‘\0’. When declaring character
arrays, we must allow one extra element space for the null terminator.
Types of arrays
We can use arrays to represent not only simple lists of values but also tables of data in two,
three or more dimensions.
Like any other variable , arrays must be declares before they are used so that the compiler can
allocate space for them in memory.
The datatype specifies the type of element that will be contained in the array, such as int,
float, or char and the size indicates the maximum number of elements that can be stored
inside the array.
After an array is declared, its elements must be initialized. Otherwise, they will contain
“garbage”.
The values in the list are separated by commas. For example, the statement
int number[3] = { 0 , 0 , 0 };
will declare the variable number as an array of size 3 and will assign zero to each
element.
If the number of values in the list is less than the number of elements, then only that
many elements will be initialized. The remaining elements will be set to zero
automatically.
For ex: int total[5]= {10,20,30} will initialize the first three elements to 10, 20
and 30 and the remaining two elements to zero.
If the number of values in the list is greater than the number of elements, then it will
show a syntax error that too many initializations for this array.
The size may be omitted. In such cases, the compiler allocates enough space for all
initialized elements. For example the statement
will declare the counter array to contain four elements with initil values 1,1,3 and 1 .
declares the name to be an array of five characters, initialized with the string “JOHN”
ending with the null character. Alternatively , we can assign the string literal directly as
under:
If we have more initializers than the declared size, the compiler will produce an error. That
is the statement
The total size in bytes for a single dimensional array is computed as shown below.
main ( ) storing
int i; a[1] 20
clrscr ( ); a[2] 30
getch ( );
}
accessing
10 20 30 40 50
Program for runtime initialization and sequential access using for loop
main ( )
{
int a[5],i;
clrscr ( );
printf(”%d ”, a[i]);
getch ( );
output
enter 5 elements 10 20 30 40 50
Note :
The output of compile time initialized program will not change during different runs of the
program
The output of run time initialized program will change for different runs because user is
given a chance of accepting different values during execution.
These are used in situations where a table of values have to be stored (or) in matrices
applications
Declaration Syntax :
datatype array_ name [rowsize] [column size];
Eg: int a[5] [5];
No of elements in array = rowsize *columnsize = 5*5 = 25
Initialization :
int table[2][3] = { 0, 0, 0, 1, 1, 1 };
initializes the elements of the first row to zero and the second row to one. The initialization is
done row by row. The above statement can be equivalently written as
commas are required after each brace that closes off a row, except in the case of the last row.
When the array is completely initialized with all values, explicitly, we need not specify the
size of the first dimension. That is the statement
{ 0, 0, 0 },
{ 1, 1, 1 }
};
is permitted.
If the values are missing in an initilizer, they are automatically set to zero. For example, the
statement
int table[2][3]= { { 1, 1} , { 2} );
will initialize the first two elements of the first row to one, the first element of the second row
to two, and all other elements to zero.
When all the elements are to be initialized to zero, the following short-cut method may be
used.
int m[3][5] = { { 0 }, { 0 }, { 0 } };
The first element of each row is explicitly initialized to zero while other elements are
automatically initialized to zero. The following statement will also achieve the same result.
Program for compile time initialization and sequential access using nested for loop
main ( )
printf(“\n”);
getch ( );
}
output
10 20 30
40 50 60
70 80 90
Program for runtime initialization and sequential access using nested for loop
main ( )
clrscr ( );
} 10 20 30
for ( i=0; i<3; i++) a[2] [0] a[2] [1] a[2] [2]
{ 70 80 90
printf(“\n”)
getch( );
output
1 2 3
4 5 6
7 8 9
main ( )
{
int a[2][2] [2] = {1,2,3,4,5,6,7,8};
int i,j,k;
clrscr ( );
getch( );
STRINGS
Introduction to strings
A string is a series of characters treated as a unit. C does not support strings as a data type.
However, it allows us to represent strings as character arrays. In C, therefore a string variable
is any valid C variable name and is always declared as an array of characters.
C strings :
H E L L O \0
The following fig shows the difference between a character stored in memory and a one-
character string stored in memory. The character requires only one memory location. The one
character string requires two memory locations: one for the data and one for the delimeter.
String literals
Ex: “Hello”
When string literals are used in a program, C automatically creates an array of characters,
initializes it to a null delimited string, an stores it, remembering its address.
Declaring strings :
Since strings are a sequence of characters, it is only natural way that the structure used to
store string variables is the character array.
Syntax:
In defining the array to store a string we must provide enough space for the data and the
delimiter. The storage structure, therefore must be one byte larger than the maximum data
size. A string declaration for an eight character string, including its delimeter, is shown below
char str [ 9 ] ;
Like numeric arrays, character arrays may be initialized when they are declared.
char city [ 9 ] = { ‘N’ , ‘e’ , ‘w’ , ‘ ‘ , ‘Y’, ‘o’ , ‘r’ , ‘k’ ,’\0’ };
The reason that city had to be 9 elements long is that the string New York contains 8
characters and one element space is provided for the null terminator.
Note that when we iniitlaize character array by listing its elements, we must supply explicitly
the null character.
C also allows us to initialize a character array with out specifying the number of elements. In
such cases, the size of the array will be determined automatically, based on the number of
elements initialized. For example the statement
We can also declare the size much longer than the string size in the initialize. That is the
statement
is permitted. In this case, the computer creates a character array of size 10, places the value
“Good” in it, terminates with the null character, and initializes all other elements to null. The
storage will look like:
Also note that we can’t separate the initialization form declaration. That is,
char strr3[ 5 ];
str[ 5 ] = “Good” ; is not allowed.
Similarly,
char s2[4 ];
s2 = s1; //Error
is not allowed.
Char *ptr=”good day”; This creates a string for the literal and then stores its address
in the string pointer variable, ptr
Accessing
There is a control string “%s” used for accessing the string till it encounters ‘\0’
Program
main ( )
clrscr ( );
getch ( );
Statement (s)
Condition? Condition?
First, we can read and write strings with the formatted input/output functions, scanf/fscanf
and printf/fprintf.
Second, we can use a special set of string only functions, get string(gets/fgets) and put string
(puts/fputs).
The familiar input/output function scanf can be used with %s format specification to read in a
string of characters.
Ex: char address[10];
Scanf(“%s” , address);
An address operator( & ) is not required, since it is already a pointer constant. Infact, it would
be an erroe to use one.
The scanf function automatically terminates the string that is read with a null character and
therefore the character array should be large enough to hold the input string plus the null
character. We can also specify the field width using the form %ws in the scanf statement for
reading a specified number of characters from the i/p string.
(1) The width w is equal to or greater than the number of characters typed in. The entire
string will be stored in the string variable.
(2) The width w is less than the number of characters in the sring. The excess characters
will be truncated and left unread.
Consider the following statements:
char name[ 10 ];
The printf function with %s format prints strings to the screen. The format %s can be used to
display an array of characters that is termiantaed by a null character.
However, if we include the minus sign in the specification (Ex: % - 10.45), the string will be
printed left justified.
Ex:
Void main()
Printf(“%15.0s\n”, country);
(1) When the field width is less than the length of the string, the entire string is printed.
(2) The integer value on the right hand side of the decimal point specifies the number of
characters to be printed.
(3) When the number of characters to be printed is specified as zero, nothing is printed.
(4) The minus sign in the specification causes the string to be printed left-justified.
(5) The specification %ns prints the first n characters of the string.
gets( )
Another and more convenient method of reading a string of text containing white spaces is to
use the library function gets available in the <stdio.h> header file. This is a simple function
with one string parameter and called as under
gets( str );
str is a string variable declared properly. It reads characters into str from the keyboard until a
new-line character is encountered and then appends a null character to the string. Unlike
scanf, it does not skip white spaces.
char line[ 80 ];
gets(line);
printf(“%s” , line);
reads a line of text from the keyboard and displays it on the screen.
C does not provide operators that work on strings directly. For instance, we cannot assign one
string to another directly.
String = “ABC”;
Puts( )
Another and more convenient way of printing string values is to use the function puts
declared in the header file <stdio.h>. This is a one parameter function and invoked as under
Puts ( str );
Where sr is a string variable containing a string value. This prints the value of the string
variable str and then moves the cursor to the beginning of the next line on the screen.
Char line[ 80 ];
gets( line );
puts( line );
reads a line of text from the keyboard and displays it on the screen.
program : using printf ( ) and scanf ( ) for reading & writing strings.
main ( )
char a[30];
scanf ( “%s”,a);
getch ( );
Output
Note :
1. ‘&’ is not used for accepting string because name of the string itself specifies the base
address of the string
2. space is not accepted as a character by scanf( )
3. ‘\0’ is automatically placed by the compiler at the end.
Program : Using gets ( ) and puts ( ) for reading and writing strings.
main ( )
{
char a[30];
gets (a);
puts (a);
Out put
There are some predefined functions designed for handling strings which are available
in the library “string.h”
They are :
1) strlen ( ) 6. strcmp ( )
2) strcpy ( ) 7. strncmp ( )
3) strncpy ( ) 8. strrev ( )
4) strcat ( )
5) strncat ( )
1). strlen ( )
This function gives the length of the string i.e. the number of characters in a
string.
Syntax:
#include <string.h>
main ( )
int l;
l = strlen (a);
Output
2). strcpy ( )
This function is used for copying source string into destination string
The length of the destination string must be greater than (or) equal to that of the
source string
Syntax: strcpy (Destination string, Source String);
Eg:
#include <string.h>
main ( ) a
{
H E l l o to
char a[50], b[50];
clrscr ( )
H E l l o to
b
scanf(“%s”, a);
strcpy ( b,a);
Output
3) strncpy ( )
This function is used for copying ‘n’ characters of source string into destination
string
The length of the destination string must be greater than (or) equal to that of the
source string
Syntax:
strncpy (Destination string, Source String, n);
program
#include <string.h>
main ( ) a
{
H E l l o \o
char a[50], b[50];
clrscr ( ) b
H E l \o
printf (“enter a string”);
gets (a);
strncpy (b,a,3);
b[3] = ‘\0’;
Output
s1
J a n 1 0 2 0 1 0 \0
1 0 \o
result[2] = ‘\0’ result
o/p :Result = 10
4) strcat ( ):
program
#include <string.h>
main()
clrscr ( );
strcat (a,b);
getch ( );
Output
5) strncat ( ):
This is used for combining or concatenating n characters of one string into another.
The length of the destination string must be greater than the source string
The resultant concatenated string will be in the source string.
Syntax:
program
#include <string.h>
main ( )
clrscr ( );
strncat (a,b,4);
a [9] = ‘\0’;
getch ( );
Output
String comparison
6) strcmp
This function compares 2 strings
It returns the ASCII difference of the first two non – matching characters in both the
strings.
Syntax
eg:
strcmp (a,b);
t h e i r \0
strcmp (a,b);
t h e r e \0
strcmp (a,b);
t h e i r \0
strcmp (a,b)
t h e \0
strcmp (a,b);
t h e r e \0
Program
main ( )
int d;
clrscr( );
printf (“enter 2 strings”);
d = strcmp (a,b);
if (d==o)
else if (d>0)
else if (d<0)
getch ( );
7. strncmp ( )
strncmp (a,b,3);
8. strrev( )
main ( )
char a[50] ;
clrscr( );
gets (a);
strrev (a);
getch ( );
Reverstring = olleH
Arrays of strings
Arrays of strings is used to represent a list of srings or list of character arrays i.e list of names
of students in a class, list of names of employees in an organization e.t.c
These names can be treated as a list of strings and they can be implemented as a 2-D array.
Each row in that array represents a name and column represents number of characters in the
array i.e the length of each row.
Here name represents a list of 10 names, each name having the size of 20.
Ex:
#include<stdio.h>
Void main()
Int I;
Scanf(“%s”, &name[i]);
It is an array whose elements are pointers to the base address of the string
It is declared and initialized as follows
char *a[ ] = {“one”, “two”, “three”};
o n e \0 t w o \0 t h r e e \0
a [1] 1238
a [2] 1242
Array of pointers
Advantage :
main ( )
int i;
clrscr ( );
getch ( );
Output
Declaration
input functions
scanf ( )
ouput functions
getchar ( )
printf ( )
getch ( )
putchar ( )
getche ( )
putch ( )
eg: char a;
There are some predefined functions available in “ctype.h” library for analyzing the
character input and converting them.
Analysis functions
Converting functions
Function
Program
#include <ctype.h>
main ( )
char a = ‘D’;
clrscr ( );
if ( isalpha (a))
else
getch ( );
}
Output
D is an alphabet
%s
02 01 2010
- o/p
%d %d %d
Program
main ( )
clrscr( );
getch ( );
Output
Day = 02
Month = 01
Year = 2010
sprintf( ) takes different numeric values as input and converts it into a single string
Syntax :
- o/p
02/01/2010
%s
Program
main ( )
char a[50];
crlscr( );
getch ( );
Output
String/Data conversion
It may be required for us to convert strings to equivalent data values( of int or float type) and
vice versa. This can be achieved using certain built-in functions of C, as described in table:
Converts a string to an
atol ( ) equivalent long integer value long atoi(const char* s);
Converts a string to an
atof( ) equivalent long integer value float atoi(const char* s);
Ecvt and fcvt differ in their int ndig, int *dec, int *sign)
representation of the
argument ndig. In case of
ecvt, it specifies the total
number of characters in the
equivalent string; however in
case of fcvt it specifies the
equivalent number of
characters after the decimal
point.