0% found this document useful (0 votes)
22 views24 pages

Unit Ii

Unit 2

Uploaded by

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

Unit Ii

Unit 2

Uploaded by

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

UNIT – II

1.Control Statements
To control the flow of program execution c programming languages uses control
statements. C provides two styles of flow control:
∙ Branching (or) Selection statements (or) Decision making statements
∙ Looping ( or ) Iterative (or) repetitive statements
Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.

Selection statements
These are used to make one-time decisions in C Programming, that is, to execute some
code/s and ignore some code/s depending upon the test expression.
Simple IF STATEMENT
Syntax:
if (test expression)
{
statement/s to be executed if test expression is true;
}
The simple if statement checks whether the text expression inside parenthesis () is true or not. If
the test expression is true, statement/s inside the body of if statement is executed but if test is
false, statement/s inside body of if is ignored.

Example: write a program that prints the largest among three numbers.

#include <stdio.h>
int main()
{
int a, b, c, max;
printf(“\nEnter 3 numbers:”);
scanf(“%d %d %d”, &a, &b, &c);
max = a;
if(b > max)
max = b;
if(c > max)
max = c;
printf(“Largest No is %d”, max);
return 0;
}

Output 1
Enter 3 numbers: 4 5 8
Largest No is 8

IF...ELSE STATEMENT

The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false. Syntax of
if...else
if (test expression)
{
Statements to be executed if test expression is true;
}
else
{
Statements to be executed if test expression is false;
}

Example: Write a C program to check whether a number entered by user is even or odd

#include<stdio.h>
int main()
{
int n, r;
printf("Enter the number:\n");
scanf("%d", &n);
r=n%2;
if(r==0)
printf("%d is even.", n);
else
printf("%d is odd.", n);
return 0;
}

Output 1
Enter the number: 5
5 is odd.

Output 2
Enter the number: 2
2 is even.

IF –ELSE IF statement (if else ladder/else if statement)

The if else if statement is used when program requires more than one test expression.

Syntax:
if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 is true;
}
.
.
.
else
{
statements to be executed if all test expressions are false;
}
If the first test expression is true, it executes the code inside the braces { } just below it.
But if the first test expression is false, it checks the second test expression. If the second test
expression is true, it executes the statement/s inside the braces { } just below it. This process
continues. If all the test expression are false, code/s inside else is executed.
Example: Write a program to check whether a no given by the user is zero, positive or
negative.
#include<stdio.h>
int main()
{
int x;
printf(“\nEnter the number:”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive\n”);
else if(x == 0)
printf(“x is zero\n”);
else
printf(“x is negative\n”);
return 0;
}
Output:

Enter the number: 12


x is positive

Nested IF statement

When the if statement is written under another simple if statement, this cluster is called as nested if.

Example: Write a program to print two integer values using nested if statement.

#include <stdio.h>

int main ()
{
int a = 100;
int b = 200;
if( a == 100 )
{
/* if condition is true then check the following */ if( b == 200 )
{
/* if condition is true then print the following */ printf("Value of a is 100 and b is
200\n" );
}
}
printf("Exact value of a is: %d\n", a );

printf("Exact value of b is: %d\n", b );


return 0;
}

Output:
Value of a is 100 and b is 200
Exact value of a is: 100
Exact value of b is: 200

Nested IF ELSE statement

It is possible to include an if...else statement inside the body of another if...else statement.

Example: Write a program to find largest of 3 numbers using nested loop.

#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers:”);
scanf(“%d %d %d”, &a, &b, &c);
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 the three numbers: 4 7 6
7

SWITCH STATEMENT

Decision making are needed when, the program encounters the situation to choose a
particular statement among many statements. If a programmer has to choose one block of
statement among many alternatives, if else if can be used but, this makes programming logic
complex. This type of problem can be handled in C programming using switch statement.

Syntax:
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;

.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}

The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement. If
the n doesn't matches any of the constant in case, then the default codes are executed and control
moves out of switch statement.
Switch case checks the value of expression/variable against the list of case values and when
the match is found , the block of statement associated with that case is executed ∙ Expression
should be Integer Expression / Character
∙ Break statement takes control out of the case.
∙ Break Statement is Optional.

Example:

#include<stdio.h>
void main()
{
int roll = 3 ;
switch ( roll )
{
case 1:printf ( " I am Pankaj ");
break;
case 2:printf ( " I am Nikhil ");
break;
case 3:printf ( " I am John ");
break;
default:printf ( "No student found");
break;
}
}

Output:
I am John
CONDITIONAL OPERATOR

It has the following simple format:

expr1 ? expr2 : expr3

It executes by first evaluating expr1, which is normally a relational expression, and then evaluates
either expr2, if the first result was true, or expr3, if the first result was false.

Example: Write a program to check if the two numbers entered by user are equal or largest among
the both.
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\n Enter the two numbers:”);
scanf(“%d %d”, &a, &b);
c = a>b? a : b>a ? b :-1;
if(c == -1)
printf(“\n Both numbers are equal”);
else
printf(“\n Larger number is %d”, c);
return 0;
}
Output:
Enter the two numbers: 4 4
Both are equal

ITERATIVE / LOOPING / REPETITIVE statements


Loops cause program to execute the certain block of code repeatedly until test expression/
condition is false.

There are 3 types of loops in C programming:


1. for loop
2. while loop
3. do...while loop

for Loop Syntax


for(initialization statement; test expression; update statement)
{
code/s to be executed;
}

The initialization statement is executed only once at the beginning of the for loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But if
test expression is true then the code/s inside body of for loop is executed and then update
expression is updated. This process repeats until test expression is false.

Example: Write a program to find the sum of first n natural numbers where n is entered by
user. Note: 1,2,3... are called natural numbers.

#include<stdio.h>
int main()
{
int n, count, sum=0;
printf("\nEnter the value of n:");
scanf("%d", &n);
for(count=1;count<=n;++count)
{
sum+=count; /* this statement is equivalent to sum=sum+count */ }
printf("Sum=%d", sum);
return 0;
}
Output:

Enter the value of n: 19


Sum=190

WHILE LOOP STATEMENT:

Syntax of while loop,


while (test expression)
{
statement/s to be executed.
}
The while loop checks whether the test expression is true or not. If it is true, code/s inside the
body of while loop is executed, that is, code/s inside the braces { } are executed. Then again the
test expression is checked whether test expression is true or not. This process continues until the
test expression becomes false.
Example: Write a C program to find the factorial of a number, where the number is
entered by user. (Hints: factorial of n = 1*2*3*...*n)

/*C program to demonstrate the working of while loop*/ #include<stdio.h>


int main()
{
int number, factorial;
printf("\nEnter a number:");
scanf("%d", &number);
factorial = 1;
while(number>0)
{
factorial = factorial * number;
--number;
}
printf("Factorial=%d", factorial);
return 0;
}

Output

Enter a number: 5
Factorial=120
Do...while loop
In C, do...while loop is very similar to while loop. Only difference between these two loops is
that, in while loops, test expression is checked at first but, in do...while loop code is executed at
first then the condition is checked. So, the code are executed at least once in do...while loops.
Syntax of do...while loops,
do
{
some code/s;
}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true,
code/s inside body of do are executed again and the process continues until test expression
becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Example: Write a C program to add all the numbers entered by a user until user enters 0.

/*C program to demonstrate the working of do...while statement*/ #include<stdio.h>


int main()
{
int sum=0, num;
do /* Codes inside the body of do...while loops are at least executed once. */ {
printf("\nEnter a number:");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}

Output
Enter a number: 3
Enter a number: -2
Enter a number: 0
sum=1

In this C program, user is asked a number and it is added with sum. Then, only the test
condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0,
the body of do...while loop is again executed until num equals to zero.

Jump/ Special control Statements: break, continue, goto, return

BREAK & CONTINUE STATEMENT:

There are two statements built in C programming, break; and continue; to alter the normal
flow of a program. Loops perform a set of repetitive task until text expression becomes false but
it is sometimes desirable to skip some statement/s inside loop or terminate the loop immediately
without checking the test expression. In such cases, break and continue statements are used. The
break; statement is also used in switch statement to exit switch statement.
BREAK STATEMENT
In C programming, break is used in terminating the loop immediately after it is encountered.
The break statement is used with conditional if statement.
Syntax:
break;
The break statement can be used in terminating all three loops for, while and do...while
loops.
Example:
#include <stdio.h>
int main()
{
int c = 1;
while(c <= 5)
{
if(c == 3)
break;
printf(“\t %d”, c);
c++;
}
return 0;
}
Output:
12

CONTINUE STATEMENT

It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statements are used.
Syntax:
continue;
Just like break, continue is also used with conditional if statement.
Example:
#include <stdio.h>
int main()
{
int c = 0;
while(c <= 5)
{
c++;
if(c == 3)
continue;
printf(“\t %d”, c);
}
return 0;
}
Output:
12456

GOTO STATEMENT:

In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code below
it.
Example: The following program is used to find the factorial of a
number. #include <stdio.h>
int main()
{
int n, c;
long int f=1;
printf(“\n Enter the number:”);
scanf(“%d”,&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“\n FACTORIAL IS %ld”, f);
end:
return 0;
}

Output:
Enter the number: 4
FACTORIAL IS 24
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement
is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of
goto statement. All programmers should try to avoid goto statement as possible as they can.

RETURN STATEMENT

The return type is used in the definition of a function to set its returned value and the return
statement is used to terminate execution of the function.

Syntax:
return expression;

exit
In C, exit() terminates the calling process without executing the rest code which is after the
exit() function.
Example:
// C program to illustrate exit() function.
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
printf("START");

exit(0); // The program is terminated here

// This line is not printed


printf("End of program");
}
Output: START
Questions:

1. Explain Selection statements with Programming Examples.

2. Explain Looping /Iteration statements with Programming Examples

3. Distinguish between while &amp; do- while statements

4. Explain switch statement with example.

5. Distinguish between break &amp; continue statements

6. Explain goto statement with example.

ARRAYS
In C programming, one of the frequently arising problems is to handle similar types
of data. For example: If the user wants to store marks of 100 students. This can be done by
creating 100 variables individually but, this process is rather tedious and impracticable. This
type of problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous values (same type). C allows a user to store
the elements of same data type in the continuous memory locations using arrays.

Def: An array is defined as a collection of data elements of same type.

Arrays are of two types:


1. One-dimensional arrays
2. Multi-dimensional arrays

One-dimensional arrays

Declaration of ID-arrays,
data_type array_name[array_size];

For example: int age[5];

Here, the name of array is age. The size of array is 5, that is, there are 5 items
(elements) of array age. All elements in an array are of the same type (int, in this case).

Array elements

Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program. For example:

int age[5];

Note that, the first element is numbered 0 and so on. And 0, 1, 2, 3, 4, 5 are index numbers.
Here, the size of array age is 5 times the size of int because there are 5 elements.

Initialization of one-dimensional array


Arrays can be initialized at declaration time in this source code as:

int age[5]={2,4,34,3,4};

It is not necessary to define the size of arrays during initialization.

int age[]={2,4,34,3,4};

In this case, the compiler determines the size of array by calculating the number of
elements of an array.

Accessing array elements In C programming, arrays can be accessed and treated like
variables in C. For example.

scanf("%d",&age[2]);

scanf("%d",&age[i]);
printf("%d",age[0]);

printf("%d",age[i]);

Example:
#include<stdio.h>
void main()
{
int array[5];
printf(“Enter 5 numbers to store them in array \n”); for(i=0;i<5;i++)
{
scanf(“%d”, &array[i]);
}
printf(“Element in the array are: \n”);
for(i=0;i<5;i++)
{
printf(“Element stored at array[%d]=%d \n”, i, array[i]); }
getch();
}

Output

Enter 5 numbers to store them in array: 23 45 32 25 45


Elements in the array are:
Element stored at array[0]:23
Element stored at array[1]:45
Element stored at array[2]:32
Element stored at array[3]:25
Element stored at array[4]:45

Multi-dimensional arrays

C programming language allows programmer to create arrays of arrays known as


multidimensional arrays.
Declaration of 2D arrays:
Syntax: data_type array_name[x][y];
For example:
float a[2][6];

Here, a is an array of two dimension, which is an example of multidimensional array.

For better understanding of multidimensional arrays, array elements of above


example can be imagined as below:
Initialization of 2D-arrays:

In C, multidimensional arrays can be initialized in different number of ways.

int c[2][3]={{1,3,0}, {-1,5,9}};


OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};

Example 1: WAP to demonstrate a two dimensional array


#include<stdio.h>
int main()
{
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
int i, j;
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
printf(“a[%d][%d] : %d\n”, i, j, a[i][j]);
}
}
return 0;
}

Output:
a[0][0] : 0
a[0][1] : 0
a[1][0] : 1
a[1][1] : 2
a[2][0] : 2
a[2][1] : 4
a[3][0] : 3
a[3][1] : 6
a[4][0] : 4
a[4][1] : 8

Initialization Of three-dimensional Array


int arr[3][2][4]={
{{1, 2, 3, 4}, {2, 7, 9, 2}},
{{9, 6, 5, 4}, {2, 4, 0, 5}},
{{8, 3, 2, 1}, {1, 2, 3, 6}}
};

Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold
i*j*k*m numbers of data.

Similarly, the array of any dimension can be initialized in C programming.

Example 2: Write a C program to find sum of two matrix of order 2*2 using multidimensional
arrays where, elements of matrix are entered by user.
#include <stdio.h>
int main()
{
int a[2][2], b[2][2], sum[2][2];
int i,j;
printf("Enter the elements of 1st matrix a:\n"); for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
scanf("%d", &a[i][j]);
}
printf("Enter the elements of 2nd matrix b:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
scanf("%d", &b[i][j]);
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
sum[i][j]=a[i][j]+b[i][j];
}
for(i=0;i<2;++i)
{
printf(“\n”);
for(j=0;j<2;++j)
{
printf("\t%d", sum[i][j]);
}
printf("\n\t");
}
return 0;
}
Output:

Enter the elements of 1st matrix a: 1 1 1 1


Enter the elements of 2nd matrix b: 2 3 4 5
Sum Of Matrix:
34

56

Questions:

1. Define array. Explain the its types.

2. Explain One- dimensional array (1D array) with programming example

3. Explain Two- dimensional array (2D array) with programming example

4. Explain switch statement with example.

5. Distinguish between 1D & 2D arrays.

Strings
Array of characters that are used to store characters are known as Strings.

Def: Strings are defined as the character arrays in which each character is stored using one byte
in the memory. The end of the string is denoted by the null character i.e \0

Syntax: char arr_name[dimension];


Example: char msg[6];
Initialization of a string:
char msg[6]={ 'H', 'e', 'l', 'l', 'o', '\0'};
Example program:
/* A program to demonstrate a string */
#include<stdio.h>
#include<conio.h>
void main()
{
char msg[6]=”Hello”;
printf(“\n Greeting Message : %s \n”, msg);
getch();
}
Output:
Greeting message: Hello

String input /output functions


C programming language provides many of the built-in functions to read given input and write
data on screen, printer or in any file.
gets() & puts() functions
The gets() function reads a line from stdin until either a terminating newline or EOF (end of
file). The puts() function writes the string to stdout.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
printf(“Enter a String :”);
gets(str);
puts(str);
getch();
}
Output:
Enter a String: Programming is fun
Programming is fun
Difference between scanf() and gets() functions
The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space as character too.
String handling/manipulation functions in string.h:
C supports a wide range of functions that manipulate null-terminated strings

Function & Purpose


1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

Examples:

#include <stdio.h>

#include <string.h>

int main()

char str1[100] = "This is ",

char str2[] = "B.Sc(Honors) Class";

strcat(str1, str2);

puts(str1);

puts(str2);
return 0;

Output:
This is B.Sc(Honors) Class

B.Sc(Honors) Class

#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Output

Enter 1st string: hello

Enter 2nd string: hello

Strings are equal


#include <stdio.h>

#include <string.h>

int main()

char str1[20] = "C programming";

char str2[20];

strcpy(str2, str1);

puts(str2);

return 0;

Output

C programming

#include <stdio.h>

#include <string.h>

int main()

char str1[100] = "This is ",

int x;

strlen(str1);

printf(“%d”,x);

return 0;

Output:
7

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf(“\nEnter string 1:”);
scanf(“%s”,str1);
printf(“Enter string 2:”);
scanf(“%s”,str2);
if(strcmp(str1,str2)< 0)
printf(“\n %s is greater than %s”, str1,str2);
else
printf(“\n %s is greater than %s”, str2,str1);
getch();
}

Output:
Enter string1: hardware
Enter string2: software
hardware is greater than software

Character functions in ctype.h

Here, c is the character argument


1. isdigit(c) returns non-zero if c is a digit, 0 to 9
2. isalpha(c) returns non-zero if c is alphabetic
3. isalnum(c) returns non-zero if c is a alphabetic or numeric
4. islower(c) returns the lowercase version if c is a capital letter otherwise returns c
5. isupper(c) returns the capital letter version if c is a lowercase character, otherwise returns c
6. toupper(c) converts lower case to uppercase
7. tolower(c) converts upper case to lowercase

Examples: follow notebook programs.


Questions:

1. Define String. How to declare and initialize the strings. Explain with an example.

2. Explain string input & output functions with examples.

3. Explain string handling functions with examples.

4. Explain character functions with examples.

You might also like