PPS FINAL UNIT-2 Notes
PPS FINAL UNIT-2 Notes
1
Example program to illustrate operator precedence
Associativity:
Associativity can be left-to-right or right-to-left.
Left-to-right associativity evaluates the expression by starting on the left and moving to the right.
Right-to-left associativity evaluates the expression by starting on the right and moving to the left.
Remember, associativity is used only when there are operators with same precedence level in occur in a
complex expression.
2
CONDITIONAL BRANCHING (DECISION CONTROL STATEMENTS)
Decision is nothing but selecting the right choice between multiple alternatives.
In computers always the decision will be made based on conditions, for a condition there are two
possibilities, either true or false.
Always for every possibility of the decision, there will be action or set of actions defined. Based on the
condition result the possible path way will be selected.
The decision is described to the computer as a conditional statement that can be answered either true or
false.
If the answer is true, one or more action statements are executed.
If the answer is false, then a different action or set of actions is executed.
Types of decision control structures:
if
if..else
nested if…else
else if ladder
dangling else
switch statement
if (condition)
{
Following are the properties of an if statement: statement-
block;will be executed.
If the condition is true then the statement-block
If the condition is false it does not do anything ( or the statement is skipped)
}
The condition is given in parentheses and must be evaluated as true (nonzero value) or false (zero value).
If a compound statement is provided, it must be enclosed in opening and closing braces.
Flowchart
3
Ent
er
Co
Bodyndit
of the IF
ion
Statement
Exi
Example: t
main()
{
int a=10,b=20;
if(a>b)
{
printf(“%d”,a);
}
printf(“%d”,b);
}
4
A Simple if...else Statement
5
Decision Control Statement: else if ladder
if (condition1)
statements1;
else if (condition2)
statements2;
else if
(condition3)
statements3;
The conditions are evaluated from the top to down.
else if
6
(condition4)
As soon as a true condition is found the statement associated with it is executed and the control is
transferred to the statements by skipping the rest of the ladder.
When all n conditions become false, final else containing default statement that will be executed.
7
void main()
{
float m1,m2,m3,m4;
float perc;
printf(“enter marks\n”);
scanf(“%f%f%f
%f”,&m1,&m2,&m3,&m4);
perc=(m1+m2+m3+m4)/
4;
if(perc>=75)
printf(“\
nDistinction”);
else if(per<75 &&
per>=60)
printf(“\
nFirst Class”);
else if(per<60 &&
per>=50)
printf(“\nSecond Class”);
else
if(per<50 && per>=40)
printf(“\nThird Class”);
else
printf(“\nFail”);
8
}//main
Dangling else problem:
dangling else
problem place the
inner if stat ement e
Da ngl ing elsthe
with in
Dangling else curDan g else
glinces
ly bra .
Decision Control Statement: switch Solution
It is a multi-way conditional statement
generalizing the if…else statement.
It is a conditional control statement that allows
(contd…)
some particular group of statements to be chosen from several available groups.
A switch statement allows a single variable to be compared with several possible case labels, which are
represented by constant values.
If the variable matches with one of the constants, then an execution jump is made to that point.
A case label cannot appear more than once and there can only be one default expression.
Note: switch statement does not allow less than ( < ), greater than ( > ).
ONLY the equality operator (==) is used with a switch statement.
The control variable must be integral (int or char) only.
When the switch statement is encountered, the control variable is evaluated.
Then, if that evaluated value is equal to any of the values specified in a case clause, the statements
immediately following the colon (“:”) begin to run.
Default case is optional and if specified, default statements will be executed, if there is no match for the
case labels.
Once the program flow enters a case label, the statements associated with case have been executed, the
program flow continues with the statement for the next case. (if there is no break statement after case label.)
9
General format of switch:
10
Example 2 for switch statement:
Concept of a loop:
The real power of computers is in their ability to repeat an operation or a series of operations many times.
This repetition, called looping, is one of the basic structured programming concepts.
Each loop must have an expression that determines if the loop is done.
If it is not done, the loop repeats one more time; if it is done, the loop terminates.
11
In a post-test loop, the condition is checked at the end of each iteration.
Loops in C
C has three loop statements: the while, the for, and the do…while. The first two are pretest loops, and the
third is a post-test loop.
A looping process, in general, would include the following four steps:
1) Before a loop start, the loop control variable must be initialized; this should be done before the first
execution of loop body.
2) Test for the specified condition for execution of the loop, known as loop control expression.
3) Executing the body of the loop, known as actions.
4) Updating the loop control variable for performing next condition checking.
While loop: is a generalized looping structure that employs a variable or expression for testing the
condition.
It is a repetition statement that allows an action to be repeated while some conditions remain true.
The body of while statement can be a single statement or compound statements.
It doesn’t perform even a single operation if condition fails.
12
Compound while Statement
13
do while: is a repetition statement that allows an action to be done at least once and then the condition is
tested.
On reaching do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, condition statement is evaluated.
If the condition is true, it evaluates the body of the loop once again.
This process continues up to the condition becomes false.
Example 3: To print fibonacci sequence for the given number using do while statement
#include<stdio.h>
void main()
{
int a=0,b=1,c,i;
i=1;
printf("%d %d",a,b);
do
{
c=a+b;
i++;
printf("%3d",c);
a=b;
b=c;
}while(i<=10);
}
for loop: is a repetitive statement used when a loop is to be executed a known number of times.
We can do the same thing with a while loop, but the for loop is easier to read and more natural for counting
loops.
General form of the for is:
for( initialization; test-condition; updation)
{
Body of the loop
}
15
We can write the for loop in the following ways:
Option 1:
for(k=1;k<=10;)
{
printf(“%d”, k);
k = k + 1;
}
Here the increment is done within the body of the for loop and not in the for statement. Note that the semicolon
after the condition is necessary.
Option 2:
int k = 1;
for (; k< = 10; k++)
{
printf(“%d”, k);
}
Here the initialization is done in the declaration statement itself, but still the semicolon before the condition is
necessary.
16
Option 3: The infinite loop
One of the most interesting uses of the for loop is the creation of the infinite loop. Since none of the three
expressions that form the for loop are required, it is possible to make an endless loop by leaving the conditional
expression empty.
For example: for (; ;)
printf(“The loop will run forever\n”);
Actually the for (; ;) construct does not necessarily create an infinite loop because C’s break statement, when
encountered anywhere inside the body of a loop, causes immediate termination of the loop.
Program control then picks up the code following the loop, as shown here:
for (; ;)
{
ch = getchar( ); /* get a character */
if (ch = = ‘A’)
break ;
}
printf (“you typed an A”);
This loop will run until A is typed at the keyboard.
break: When a break statement is enclosed inside a block or loop, the loop is immediately exited and program
continues with the next statement immediately following the loop.
When loop are nested break only exit from the inner loop containing it.
The format of the break statement is:
Continue: When a continue statement is enclosed inside a block or loop, the loop is to be continued with the next
iteration.
The continue statement tells the compiler, skip the following statements and continue with the next iteration.
The format of the continue statement is:
18
ARRAYS
ARRAY: An array is a fixed-size sequenced collection of elements of same type.
To process large amount of data, C uses a powerful data structure called array.
An array is a collection of elements of the same data type.
Array elements can be initialized, accessed and manipulated using the indexing.
Example:
int score[10] :
Here score will contain 10-elements
Array index always start at ‘0’ and end at total-number of elements minus one.
In our example the index for score will start at 0 and end at 9.
Using Arrays in C
C provides two different types of arrays
One-Dimensional arrays.
Two-Dimensional arrays.
In One-dimensional arrays the data are organized linearly in only one direction.
In Two-Dimensional arrays the data are organized in rows and columns, like a matrix.
ONE-DIMENSIONAL ARRAYS:
Array declaration and definition
Like every other object in C, an array must be declared, defined and initialized before it can be used in the
program.
Array declaration tells the compiler the name of the array.
Array definition specifies the size or number of elements in the array. In a fixed length array, the size of the
array is a constant and must have a value at the compile time.
Example: type arrayname[array_size];
19
The declaration and definition format for a variable length is same as like a fixed length array except the
size is a variable. The array size will be determined when the program is executed. Once the size is
determined it cannot be changed.
Initialization:
Array elements in a fixed-length array can be initialized when they are declared. For variable-length arrays
they cannot be initialized when they are defined.
To initialize the array elements with a set of values, they must be enclosed in braces and separated by
commas.
It is a compile error to specify more values than elements in the array.
The initialization can be done in the following ways:
(a) Basic initialization: int scores[5]={3,7,12,24,45};
(b) Initialization without size: int scores[]={3,7,12,24,45};
(c) Partial initialization: int scores[5]={3,7,0,0,0};
(d) Initialization to all zeros: int scores[5]={0};
The first example array the score array will have 5-elements and they contain specific set of
values.
In the second example, when the array is completely initializing then the size attribute can be
omitted.
In the third example, if the array is initialized with partial values rest of the elements will be
initialized to zero.
In the fourth example can be used to initialize all the elements to zeros.
Inputting values:
An array can be initialized from the keyboard. The values can be read from the keyboard and initialized to
array.
The most appropriate loop to use with arrays is the for loop.
for(i=0;i<9;i++)
scanf(“%d”,&scores[i]);
Assigning values:
20
Array elements can be assigned individually by using a set of values, with the help of assignment operator.
Example: scores[4]=10;
Assigning one array to another array is not possible even if they match fully in type and size. To do so we
have to copy all the elements individually from one array to another.
for(i=0;i<10;i++)
scores[i]=temp[i];
Printing values:
To print the contents of the array, a normal for loop can be used.
Example: for(i=0;i<10;i++)
printf(“%d “,scores[i]);
21
//Program to calculate sum of all the array elements.
#include <stdio.h>
void main()
{
int a[10];
int i, size, total=0;
printf("\n Enter the size of the array : ");
scanf("%d", &size);
printf("\n Enter the elements of an array : ");
for (i = 0; i < size ; i++)
scanf("%d",&a[i]);
for (i = 0; i < size ; i++)
total += a[i];
printf(“Sum of all array elements: %d", total);
}
TWO-DIMENSIONAL ARRAYS
In One-dimensional arrays the data are organized linearly in only one direction.
Many applications require data to be stored in more than one dimension.
Matrices require an array that consists of rows and columns as shown in the following figure, which is
generally called as two-dimensional array.
In C-language a two dimensional array will be considered as an array of arrays. That is a two dimensional
array is an array of one-dimensional arrays.
Declaration:
Two-dimensional arrays like One-dimensional arrays must be declared and defined before being used.
Declaration tells the compiler the name of the array; definition specifies the type and size of each
dimension.
The size of a two array must be a constant and must have a value at compile time.
Example: int scores[5][4];
Initialization:
The definition of a Two-Dimensional array only reserves the memory for the elements in the array.
No values will be stored in the locations. The locations will generally contain unpredictable values or
garbage values without initialization.
22
Initialization of array can be done when the array is defined.
The values for the array must be enclosed in braces.
Example: int scores[3][2]={2,3,5,4,6,9};
Nested braces must be used to show the exact number of rows and columns.
Example: int scores[3][2]={{2,3,5},{4,6,9}};
In a Two-Dimensional array, if the array is completely initialized with values, only the first dimension can
be omitted. The second dimension must need to be specified.
Example: int scores[][2]={{2,3,5},{4,6,9}};
The whole array can be initialized to zeros.
Example: int scores[5][4]={0};
Inputting Values:
Another way to initialize the values is, we can read them from the keyboard.
In Two-Dimensional array, it usually requires nested for loops.
The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
Example: for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”,&scores[i][j]);
Outputting values:
The values inside a Two-Dimensional array can be printed using two nested loops.
The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
To print the matrix in a table format, a newline is printed at the end of each row.
Example: for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“ %d”,scores[i][j]);
printf(“\n”);
}
Accessing values:
Individual elements can be initialized using the assignment operator.
scores[2][0]=23;
scores[2][2]=scores[1][1]+12;
}
}
// Displaying the result
printf("\nMatrix 1:\n");
for(i=0; i<r; ++i)
{
for(j=0; j<c; ++j)
printf("%d ", a[i][j]);
printf("\n");
}
printf("\nMatrix 2:\n");
for(i=0; i<r; ++i)
{
for(j=0; j<c; ++j)
printf("%d ", b[i][j]);
printf("\n");
}
printf("\nOutput Matrix:\n");
for(i=0; i<r; ++i)
{
for(j=0; j<c; ++j)
printf("%d ", result[i][j]);
24
printf("\n");
}
getch();
return 0;
}
STRINGS
A string is a series of characters treated as a single unit.
String is a variable length piece of data. Strings are divided into two major categories.
o Fixed length strings.
o Variable length strings.
Variable-Length strings:
A much preferred solution is to create a structure that can expand and contract according to the size of the
value we want to store.
Example: To store a person name with only three characters the structure should contract and provide three
characters and to store a person name with 30-characters the structure should expand and provide 30-
characers.
Here also there is a problem: as we are using a variable length structure in computers memory, there must be
a way to indicate the end of the string.
Two common techniques are used to indicate the end of the string.
o Length-Controlled Strings
o Delimited Strings
Length-Controlled Strings:
In this type of strings a count is used as the first character in the string that specifies the number of
characters in the string.
This count then be used by string manipulation functions to determine the length of the string.
Delimited Strings:
In this type of strings the end is specified by a special character known as delimiter, hence the name
delimited strings.
This concept is similar to using a full stop (.) at the end of a sentence in English. Where each sentence is of
variable length and a special symbol full stop is used to indicate the end of the sentence.
The disadvantage of using a delimiter is that it eliminates one character from being used for data in the
string.
25
The most common delimiter is a null character (\0).
All C strings are of variable length and delimited once.
C-Strings
A C string is a variable length array of characters that is delimited by the null character.
A string is stored in an array of characters and delimited by a null character (\0).
As a string is stored in an array, the name of the string is a pointer to the beginning of the string.
There is a big difference between how a character is stored in memory and a one-character string is stored.
The character requires only one memory location, but the one-character string requires two memory
locations one for actual character and one for delimiter.
To store an empty string in memory also requires one memory location to store the delimiter.
String Constants:
A string literal or a string constant is a sequence of characters enclosed in double quotes.
When string constants are used in a program, C automatically creates an array of characters, initializes to a
null delimited string, and stores it.
Example: “C is a programming language”
“Hello World”
A string literal is stored in memory like any other object. It has an address, and can be referred by using a
pointer. Here the string literal as it is a sequence of characters, itself a pointer constant to the first element.
The string itself can be used to refer the individual characters by using index.
Example: “hello”[1] e
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
C provides different predefined set of string functions which are helpful in manipulating the strings.
String Length
strlen () function:
This function counts and returns the number of characters in a string. It takes the form
Syntax: int n=strlen(string);
Where n is an integer variable, which receives the value of the length of the string. The counting ends at the
first null character.
The string length function (strlen) returns the length of a string that is the number of characters in the string
excluding the null character.
If the string is empty then the string length function returns zero.
String Copy
The String copy functions strcpy(); copies the contents from one string including the null character to
another string.
There are two string copy functions:
I. Basic string copy strcpy();
II. String copy length controlled strncpy();
I. Basic string copy strcpy();
The basic string copy function strcpy(); copies the contents of the from one string fromstr including
the null character to another string tostr.
Syntax: strcpy(string1,string2);
If fromstr is longer than the tostr then, the data in memory after tostr is destroyed.
The destination string should be large enough to hold the source string.
If fromstr is longer than tostr, the data in memory after tostr is destroyed.
The function returns the address of tostr.
28
II. String copy length controlled strncpy();
String copy length controlled strncpy(); function copies the content of one sting to another, but it sets
a maximum number of characters that are to be copied.
This function contains a parameter that specifies the maximum number of characters that can be
copied at a time.
Syntax: strncpy(string1,string2,size);
If the actual size of the fromstr is equal or greater than size parameter, then size number of characters
are copied.
If the fromstr size is smaller than the size parameter, the entire string is copied and then null
characters are inserted into the tostr until the size parameter is satisfied.
If the fromstr is longer than the size the copy stops after size bytes have been copied. In this case the
destination variable tostr may not be a valid string; that is it may not have a delimiter.
Sring Compare
C has two string compare functions:
I. Basic string compare strcmp();
II. String compare length controlled strncmp();
String Concatenation
The string concatenation function appends one string to the end of another string.
The size of the destination string should be large enough to hold the resulting string. If it is not the data at
the end of the destination string will be destroyed.
C has two string concatenation functions:
I. Basic string concatenation strcat();
II. String concatenation length controlled strncat();
I. Basic string concatenation strcat();
The function copies str2 to the end of str1, beginning at the delimiter. That is the delimiter is replaced with
the first character of the str2. The delimiter from str2 is copied to the resulting string.
Syntax: strcat(str1, str2);
The resulting string length is the sum of the length of str1 plus the length of str2.
The function returns the address pointers to the resulting string.
#include <stdio.h>
#include <string.h>
void main( )
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strcat ( str1, str2) ;
printf ( "%s", str1 ) ;
}
Output
HyderabadISL
/*Define functions- length of a string, copy, concatenate, convert into uppercase letters, compare two strings
for alphabetical order- over strings and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
void main() {
char str1[15],str2[15],str3[10];
int n,c,len,i;
printf("\n Enter the string1 ");
gets(str1);
puts(str1);
printf("\n Enter the string2 ");
31
gets(str2);
puts(str2);
printf("Enter the string 3 ");
scanf("%s",str3);
printf("%s",str3);
printf("\n***************************");
printf("\n 1. String Length ");
printf("\n 2. String Copy ");
printf("\n 3. String Comparison ");
printf("\n 4. String Concat ");
printf("\n 5. UpperCase ");
printf("\n***************************");
printf("\n Enter the choice u want to perform");
scanf("%d",&n);
switch(n)
{
case 1: len=strlen(str1);
printf("\n The length of the string entered is %d",len);
break;
case 2: strcpy(str1,str2);
printf("\n 1st string =%s,2nd string=%s",str1,str2);
break;
case 3: c=strcmp(str1,str2);
if(c==0)
printf("\n Both are equal");
else
printf("\n Both are different");
break;
case 4: printf("\n The resultant string is: %s",strcat(str1,str2));
break;
case 5: for(i=0;i<strlen(str1);i++)
str1[i]=toupper(str1[i]);
printf("%s",str1);
break;
default: printf("\n Enter correct choice");
}
}
OUTPUT:
Enter the string1: abcd
abcd
Enter the string2: efgh
efgh
Enter the string3: pqr
pqr
***************************
32
1. String Length
2. String Copy
3. String Comparison
4. String Concat
5. UpperCase
***************************
Enter ur choice 4
The resultant string is: abcdefgh
33