0% found this document useful (0 votes)
15 views110 pages

Unit 2

The document provides an overview of programming in C, focusing on statements, conditional statements, loops, and jump statements. It details the syntax and examples for various control structures like if-else, switch, while, for, and do-while loops, along with jump statements such as break and continue. Additionally, it introduces arrays, their declaration, and initialization methods.

Uploaded by

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

Unit 2

The document provides an overview of programming in C, focusing on statements, conditional statements, loops, and jump statements. It details the syntax and examples for various control structures like if-else, switch, while, for, and do-while loops, along with jump statements such as break and continue. Additionally, it introduces arrays, their declaration, and initialization methods.

Uploaded by

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

Unit-II

Programming in C
STATEMENTS
A statement causes the computer to carry out some definite action. There are three
different classes of statements in C:

Expression statements, Compound statements, and Control statements.

.
Selection Statement/Conditional
Statements/Decision Making Statements

C‟ language supports two conditional statements.


1: if
2: switch.

1: if Statement: The if Statement may be implemented in different forms.


1: simple if statement.
2: if –else statement
3: nested if-else statement.
4: else if ladder.

.
Simple if statement.

#include<stdio.h>
main()
{
int a=15,b=20;
if(b>a)
{
printf("b is greater");
}
}
Output
b is greater

.
If-else statement

#include <stdio.h>
int main()
{ int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer

.
Nested if-else statement
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
//Below – if-else is nested inside another if
block
if (var1 >var2)
{
printf("var1 is greater than var2");
}
else
{
printf("var2 is greater than var1");
}
}
else{
printf("var1 is equal to var2");
. }
Else if ladder
#include<stdio.h>
Syntax : if( condition-1) #include<conio.h>
{ void main(){
statement-1; int number=0;
} clrscr();
else if(condition-2) printf("enter a number:");
{ scanf("%d",&number);
statement-2; if(number==10){
} printf("number is equals to 10");
else if(condition-3) }
{ else if(number==50){
statement-3; printf("number is equal to 50");
} }
else if(condition-n) else if(number==100){
{ printf("number is equal to 100");
statement-n; }
} else{
else printf("number is not equal to 10, 50 or 100");
{ }
default-statement; getch();
} }
.statement-x;
Points to Remember
1. In if statement, a single statement can be included without enclosing it into curly
braces { }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one
statement inside if condition, then we must enclose them inside curly braces.
5. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not comparison.
if(a==7)
6. Other than 0(zero), all other values are considered as true.
7. if(27)
8. printf("hello");
In above example, hello will be printed.
.
Switch statement
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a=15,b=20; int a=15,b=20; // b=15 and a=20 same
if(b>a) answer
{ if(b>a);
printf("b is greater"); {
} printf("b is greater");
} }
Output }
b is greater Output
b is greater
Switch statement

Syntax:
switch(expression)
{
case value-1:
statement/block-1;
break;
case value-2:
statement/block t-2;
break;
case value-3:
statement/block -3;
break;
case value-4:
statement/block -4;
break;
default:
default- statement/block t;
break; }}
Switch statement
#include<stdio.h> printf("You chose Two");
int main() break;
{ case 3:
int a; printf("You chose Three");
printf("Please enter a no between 1 and 5: break;
"); case 4:
scanf("%d",&a); printf("You chose Four");
switch(a) break;
{ case 5: printf("You chose Five.");
case 1: break;
printf("You chose One"); default :
break; printf("Invalid Choice. Enter a no between
case 2: 1 and 5"); break;
}}
Switch statement
Switch statement

Rules for writing switch()


statement.
1 : The expression in switch statement must
be an integer value or a character constant.
2 : No real numbers are used in an
expression.
3 : The default is optional and can be placed
anywhere, but usually placed at end.
4 : The case keyword must terminate with
colon ( : ).
5 : No two case constants are identical.
6 : The case labels must be constants.
7: It isn't necessary to use break after each
Output : A B C
block, but if you do not use it, all the 8: default case can be placed anywhere in
consecutive block of codes will get executed the switch case. Even if we don't include the
after the matching block. default case switch statement works.
Switch statement
Write a C program to find whether a given year is a leap
year or not.

Leap year -A year is a leap year if it is divisible by


4, unless it is also divisible by 100, but not 400.
Iterative/Repetitive loops
C language provides three iterative/repetitive loops.

1 : while loop
2 : do-while loop
3 : for loop
Iterative/Repetitive loops
Example:
For Loop:
#include<stdio.h>
#include<conio.h>
Syntax : for(initialization; condition; void main( )
increment/decrement) {
{
Statements;
int x;
} for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Iterative/Repetitive loops
For Loop:
• This is an entry controlled looping statement.
• In this loop structure, more than one variable can be initialized.
• One of the most important features of this loop is that the three actions can be taken at a
time like variable initialization, condition checking and increment/decrement.
• The for loop can be more concise and flexible than that of while and do-while loops.
Iterative/Repetitive loops
While Loop #include<stdio.h>
Syntax : #include<conio.h>
variable initialization ; void main( )
while (condition) {int x=1;
{ while(x<=10)
statements ; {
variable increment or decrement ; printf("%d\t", x);
} x++;
}
getch();
}

Output
1 2 3 4 5 6 7 8 9 10
Iterative/Repetitive loops
For Loop While Loop

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {int x=1;
int x; while(x<=10)
for(x=1; x<=10; x++) {
{ printf("%d\t", x);
printf("%d\t",x); x++;
} }
getch(); getch();
} }
Output
1 2 3 4 5 6 7 8 9 10 Output
1 2 3 4 5 6 7 8 9 10
Iterative/Repetitive loops
While Loop
The while loop is an entry controlled loop
statement, i.e means the condition is evaluated
first and it is true, then the body of the loop is
executed.
Iterative/Repetitive loops
do-while loop #include<stdio.h>
#include<conio.h>
void main()
Syntax : variable initialization ; {
do{ int a,i;
statements ; a=5;
variable increment or decrement ; i=1;
}while (condition); do
{
printf("%d\t",a*i);
i++;
}while(i <= 10);
getch();
}

Output
5 10 15 20 25 30 35 40 45 50
Iterative/Repetitive loops
do-while loop
The do-while loop is an exit controlled loop
statement The body of the loop are executed first
and then the condition is evaluated. If it is true,
then the body of the loop is executed once again.
Nested for loop
#include<stdio.h>
#include<conio.h> Output
void main( ) 1
{ 21
int i,j; 321
for(i=1;i<5;i++) 4321
{ 54321
printf("\n") ;
for(j=i;j>0;j--)
{
printf("%d",j);
}
}
getch();
}
Nested for loop
#include<stdio.h>
#include<conio.h>
void main() Output
{ 1
int i,j,n; 12
clrscr(); 123
printf("Enter number of rows: "); 1234
scanf("%d",&n); 12345
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
}
Nested for loop
#include<stdio.h>
#include<conio.h>
void main() Output
{ 54321
int i,j,n; 4321
clrscr(); 321
printf("Enter number of rows: "); 21
scanf("%d",&n); 1
for(i=n;i>=1;i--)
{
for(j=i;j>=1;j--)
{
printf("%d ",j);
}
printf("\n");
}
getch();
}
Nested for loop
#include<stdio.h> for(i=n;i>=1;i--)
#include<conio.h> {
void main() for(j=1;j<=i;j++)
{ {
int i,j,n; printf("%d ",j);
clrscr(); }
printf("Enter number of rows: "); printf("\n");
scanf("%d",&n); }
for(i=1;i<=n;i++) getch();
{ }
for(j=1;j<=i;j++) Output
{ 1
12
printf("%d ",j); 123
} 1234
12345
printf("\n"); 1234
} 123
12
1
Jump Statements
Jumping statements are used to transfer the program‟s control from one location to another, these are
set of keywords which are responsible to transfer program‟s control within the same block or from one
function to another.

There are four jumping statements in C language:


•  goto statement
•  return statement
•  break statement
•  continue statement
Jump Statements
goto statement

goto statement doesnot require any condition. This statement passes control
anywhere in the program i.e, control is transferred to another part of the program without testing
any condition.

Syntax : goto label;


.....
.....
label:
statements;
Jump Statements
int main()
goto statement {
int age;
Vote:
printf("you are eligible for voting");
NoVote:
printf("you are not eligible to vote");
printf("Enter you age:");
scanf("%d", &age);
if(age>=18)
goto Vote;
else
goto NoVote;
Output return 0;
Enter you age:19 }
you are eligible for voting
Enter you age:15
you are not eligible to vote
Jump Statements

Break Statement

Break is a keyword. The break statement


terminates the loop (for, while and do...while loop)
immediately when it is encountered. The break
statement is used/ associated with decision making
statement such as if ,if-else.
Jump Statements

Break Statement #include <stdio.h>


#include <conio.h>
void main(){
int i=1;
clrscr();
for(i=1;i<=10;i++){
printf("%d ",i);
if(i==5){
break;
}
}
getch();
}

Output
12345
Jump Statements

Continue Statement

Continue is keyword exactly opposite to break. The


continue statement is used for continuing next
iteration of loop statements. When it occurs in the
loop it does not terminate, but it skips
some statements inside the loop / the statements
after this statement. . The continue statement is
used/ associated with decision making statement
such as if ,if-else.
Jump Statements

Flowchart of continue Statement #include <stdio.h>


#include <conio.h>
void main(){
int i=1;
clrscr();
for(i=1;i<=10;i++){
if(i==5){
continue;
}
printf("%d",i);
}
getch();
}

Output
1234678910
Jump Statements
#include <stdio.h> printf("\nThe loop with continue produces output
as: \n");
int main() for (int i = 1; i <= 7; i++) {
{

printf("The loop with break produces output as: \n");


if (i == 3)
continue;
for (int i = 1; i <= 7; i++) { printf("%d ", i);
}
if (i == 3) return 0;
break; }
else
printf("%d ", i); Output
}
The loop with break produces output as:
12
The loop with continue produces output as:
124567
Jump Statements
#include <stdio.h> #include <stdio.h>
void main() void main()
{ {
int i = 0;
int i = 0;
int j = 0;
for (i = 0;i < 5; i++)
for (i = 0;i < 5; i++)
{ if (i < 4)
for (j = 0;j < 4; j++) {
{ printf("Hello");
if (i > 1) break;
continue; }
printf("Hi \n"); }
}
}
Output
}
Output
Hello
Hi print 8 times
ARRAYS
Declaration of an Array
An array is a group (or collection) of same data types. data-type variable-name[size/length of array];
Or
An array is a collection of data that holds fixed number
For example:
of values of same type.
Or
int arr[10];
Array is a collection or group of elements (data). All the
elements of array are homogeneous (similar). It has
contiguous memory location.
ARRAYS
Compile time Array initialization
After an array is declared it must be initialized.
Otherwise, it will contain garbage value(any random Example
value). An array can be initialized at either compile time
int age[5]={22,25,30,32,35};
or at runtime.

int marks[4]={ 67, 87, 56, 77 }; //integer array initialization


float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; //Compile time error
ARRAYS

for(j=0;j<4;j++)
Runtime Array initialization
{
An array can also be initialized at runtime using scanf() printf("%d\n",arr[j]);
function. }
Example getch();
#include<stdio.h> }
#include<conio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i=0;i<4;i++)
{
scanf("%d",&arr[i]); //Run time array initialization
}
ARRAYS

1 : Initializing all specified memory locations :


Different ways of initializing arrays

int a[5]={10,20,30,40,50};
1 : Initializing all specified memory locations During compilation, 5 contiguous memory locations are
2 : Partial array initialization. reserved by the compiler for the variable a and all these
3 : Intilization without size. locations are initialized.
4 : String initialization. a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
1000 1002 1004 1006 1008

If the size of integer is 2 bytes, 10 bytes will be allocated


for the variable a.
ARRAYS

1 : Initializing all specified memory locations :


Different ways of initializing arrays

char b[4] = {‘C’,’O’,’M’,’P’};


1 : Initializing all specified memory locations During compilation, 4 contiguous memory locations are
2 : Partial array initialization. reserved by the compiler for the variable a and all these
3 : Intilization without size. locations are initialized.
4 : String initialization. b[0] b[1] b[2] b[3]
C O M P
1000 1001 1002 1003

If the size of char is 1bytes, 4 bytes will be allocated for


the variable a.
ARRAYS

2 : Partial Array Initilization


Different ways of initializing arrays
int a[5]={10,20};

1 : Initializing all specified memory locations Eventhough compiler allocates 5 memory locations,
2 : Partial array initialization. using this declaration statement, the compiler initializes
3 : Intilization without size. first two locations with 10 and 20, the next set of
4 : String initialization. memory locations are automatically initialized to zero.

a[0] a[1] a[2] a[3] a[4]


10 20 0 0 0
1000 1002 1004 1006 1008
If the size of integer is 2 bytes, 10 bytes will be allocated
for the variable a.
ARRAYS

Different ways of initializing arrays 3 : Initilization without size :


int a[]={10,20,30,40,50};

1 : Initializing all specified memory locations


2 : Partial array initialization. a[0] a[1] a[2] a[3] a[4]
3 : Intilization without size. 10 20 30 40 50
4 : String initialization.
1000 1002 1004 1006 1008

If the size of integer is 2 bytes, 10 bytes will be allocated


for the variable a.
ARRAYS

Different ways of initializing arrays 4. Array Initilization with a String


char a[ ] = “COMP”;

1 : Initializing all specified memory locations


2 : Partial array initialization. a[0] a[1] a[2] a[3] a[4]
3 : Intilization without size. C O M P \0
4 : String initialization.
1000 1001 1002 1003 1004

If the size of char is 1 bytes, 5 bytes will be allocated for


the variable a.
Here, the string length is 4 bytes. But , string size is 5
bytes. So the compiler reserves 5+1 memory locations
and these locations are initialized with the characters in
the order specified. The string is terminated by \0 by the
compiler.
Output Based Question
ARRAYS

}
Runtime Array initialization
for(j=0;j<4;j++)
An array can also be initialized at runtime using scanf() {
function. printf("%d\n",arr[j]);
Example }
#include<stdio.h> getch();
#include<conio.h> }
void main()
{
int arr[]; //error
int arr[1],b;
int i, j;
printf(“Enter the no of element”);
printf("Enter array element");
scanf(“%d”,&b);
for(i=0;i<b;i++)
{
scanf("%d",&arr[i]); //Run time array initialization
Two‐Dimensional Arrays

The two dimensional array in C language is represented


in the form of rows and columns, also known as matrix.
It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other
dimensional arrays are also known as multidimensional
arrays.
Declaration of two dimensional Array

data_type array_name[size1][size2];
Example

int twodimen[4][3];

Example :

int a[3][4];
Two‐Dimensional Arrays

Output
Initialization of 2D Array
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
arr[0][0] = 1
arr[0][1] = 2
Accessing Two-Dimensional Array Elements arr[0][2] = 3
Example arr[1][0] = 2
1. #include <stdio.h> arr[1][1] = 3
2. #include <conio.h> arr[1][2] = 4
3. void main(){ arr[2][0] = 3
4. int i=0,j=0; arr[2][1] = 4
5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
arr[2][2] = 5
6. clrscr();
7. for(i=0;i<4;i++){
arr[3][0] = 4
8. for(j=0;j<3;j++){ arr[3][1] = 5
9. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][2] = 6
10. }//end of j
11. }//end of i
12. getch();
13. }
Two‐Dimensional Arrays
Example Write a C program Addition of Two Matrices printf("\nThe elements of A matrics");
#include<stdio.h>
for(i=0;i<m;i++)
#include<conio.h>void main()
{ {
int a[25][25],b[25][25],c[25][25],i,j,m,n; printf("\n");
clrscr(); for(j=0;j<n;j++)printf("\t%d",a[i][j]);
printf("enter the rows and colums of two matrics:\n"); }
scanf("%d%d",&m,&n); printf("\nThe elements of B matrics");
printf("\nenter the elements of A matrics"); for(i=0;i<m;i++)
for(i=0;i<m;i++) {
{ printf("\n");
for(j=0;j<n;j++)
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]);
} printf("\t%d",b[i][j]);
printf("\nenter the elements of B matrics"); }
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]);
Two‐Dimensional Arrays
printf("\nThe additon of two matrics");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]);
}
}
getch();
}
Multidimensional Arrays
Initialization of a three dimensional array. printf("\nDisplaying values:\n");
for(i = 0; i < 2; ++i) {
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, for (j = 0; j < 3; ++j) {
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} } for(k = 0; k < 2; ++k ) {
}; printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j]
#include <stdio.h> [k]);
int main() }
{ }
// this array can store 12 elements }
int i, j, k, test[2][3][2]; return 0;
printf("Enter 12 values: \n");
}
for(i = 0; i < 2; ++i) {
for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
scanf("%d", &test[i][j][k]);
}
}
}
Multidimensional Arrays
Output

Enter 12 values:
123456789101112
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
FUNCTIONS
Definition: A function is a block of code/group of
statements/self contained block of statements/
basic building blocks in a program that performs a
particular task. It is also known as procedure or
subroutine or module, in other programming languages.

Advantage of functions
1) Code Reusability
By creating functions in C, you can call it many times. So
we don't need to write the same code
again and again.
2) Code optimization
It makes the code optimized we don't need to write
much code.
3) Easily to debug the program.
FUNCTIONS
Types of Functions
There are two types of functions in C programming: 2. User-defined functions: are the functions which are
created by the C programmer, so
1. Library Functions: are the functions which are that he/she can use it many times. It reduces complexity
declared in the C header files such as of a big program and optimizes
scanf(), printf(), gets(), puts(), ceil(), floor() etc. You just the code. Depending upon the complexity and
need to include appropriate header files to use these requirement of the program, you can create
functions. These are already declared and defined in C as many user-defined functions as you want
libraries.
Points to be Remembered
System defined functions are declared in header files
System defined functions are implemented in .dll files.
(DLL stands for Dynamic Link Library).
To use system defined functions the respective header
file must be included.
FUNCTIONS
FUNCTIONS
ELEMENTS OF USER-DEFINED FUNCTIONS

In order to write an efficient user defined function, the


programmer must familiar with the
following three elements.
1 : Function Declaration. (Function Prototype).
2 : Function Call.
3 : Function Definition
FUNCTIONS
ELEMENTS OF USER-DEFINED FUNCTIONS
Function Declaration. (Function Prototype).
In order to write an efficient user defined function, the
programmer must familiar with the A function declaration is the process of tells the compiler
following three elements. about a function name.
1 : Function Declaration. (Function Prototype).
2 : Function Call. Syntax
3 : Function Definition return_type function_name(parameter/argument);
return_type function-name();

Ex : int add(int a,int b);


int add();
FUNCTIONS
ELEMENTS OF USER-DEFINED FUNCTIONS
Calling a function/function call
In order to write an efficient user defined function, the When we call any function control goes to function body
programmer must familiar with the and execute entire code.
following three elements.
1 : Function Declaration. (Function Prototype). Syntax : function-name();
2 : Function Call. function-name(parameter/argument);
3 : Function Definition return value/ variable =
function-name(parameter/argument);

Ex : add(); // function without parameter/argument


add(a,b); // function with parameter/argument
c=fun(a,b); // function with parameter/argument and
return values
FUNCTIONS
ELEMENTS OF USER-DEFINED FUNCTIONS
Defining a function.
In order to write an efficient user defined function, the Defining of function is nothing but give body of function
programmer must familiar with the that means write logic inside function body.
following three elements.
1 : Function Declaration. (Function Prototype). Syntax
2 : Function Call. return_ type function-name(parameter list) // function
3 : Function Definition header.
{
declaration of variables;
body of function; // Function body
return statement; (expression or value) //optional
}
Eg: int add( int x, int y) {
int z;
z = x + y; }
Eg: int add( int x, int y)
{
return ( x + y );
}
FUNCTIONS
Example:
#include<stdio.h> Example:
#include<conio.h> #include <stdio.h>
void sum(); // declaring a function int addNumbers(int a, int b); // function prototype
clrsct(); int main()
int a=10,b=20, c; {
void main() int n1,n2,sum;
{ printf("Enters two numbers: ");
sum(); // calling function scanf("%d %d",&n1,&n2);
} sum = addNumbers(n1, n2); // function call
void sum() // defining function printf("sum = %d",sum);
{ return 0;
c=a+b; }
printf("Sum: %d", c); int addNumbers(int a,int b) // function definition
} {
int result;
Output result = a+b;
Sum:30 return result; // return statement
}
FUNCTIONS
FUNCTIONS

PARAMETERS : 2 : Formal Parameters :These are the parameters


transferred into the calling function (main program)
parameters provides the data communication
from the called function(function).
between the calling function and called function.
The parameters specified in calling function are said to
They are two types of parametes be Actual Parameters.The parameters declared in called
function are said to be Formal Parameters.The value of
1 : Actual parameters. actual parameters is always copied into formal
parameters.
2 : Formal parameters.

1 : Actual Parameters : These are the parameters


transferred from the calling function (main
program) to the called function (function).
FUNCTIONS
FUNCTIONS

1 : Functions with no Parameters and no Return Values.


2 : Functions with no Parameters and Return Values.
3 : Functions with Parameters and no Return Values.
4 : Functions with Parameters and Return Values.
FUNCTIONS

1 : Functions with no Parameters and no Return Values :

#include<stdio.h> void sum()

#include<conio.h> {

void sum(); int a,b,c;

void main() printf("enter the values of a and


b");
{
scanf("%d%d",&a,&b);
sum();
c=a+b;
getch();
printf("sum=%d",c);
}
}
FUNCTIONS

2 : Functions with no Parameters and Return Values.


getch();
#include<stdio.h> }
#include<conio.h> int sum()
int sum(); { int a,b,c;
void main() printf("enter the values of a and
b");
{
scanf("%d%d",&a,&b);
int c;
c=a+b;
clrscr();
return c;
c=sum();
}
printf("sum=%d",c);
FUNCTIONS

3 : Functions with Parameters and no Return Values.


sum(m,n);
#include<stdio.h> getch();
#include<conio.h> }
void sum(int a,int b); void sum(int a,int b)
void main() {
{ int c;
int m,n; c=a+b;
clrscr(); printf("sum=%d",c);
printf("Enter m and n values:"); }
scanf("%d%d",&m,&n);
FUNCTIONS

4 : Functions with Parameters and Return Values.


c=sum(m,n);
#include<stdio.h> printf("sum=%d",c);
#include<conio.h> getch();
int sum(int a,int b); }
void main() int sum(int a,int b)
{ {
int m,n,c; int c;
clrscr(); c=a+b;
printf("Enter m and n values"); return c;
scanf("%d%d",&m,&n); }
FUNCTIONS

C provides two mechanisms to pass parameters to a function.

1 : Pass by value (OR) Call by value.

2 : Pass by reference (OR) Call by Reference


FUNCTIONS

1 : Pass by value (OR) Call by value : printf("After swapping:%d%d\n",i,j);


getch();
}
void swap(int a,int b)
Any changes made inside functions having formal {
parameter are not reflected in the actual parameters of int temp;
the caller. temp=a;
a=b;
b=temp;
#include<stdio.h>
}
void swap(int ,int );
void main()
{
int i,j; Output
printf("Enter i and j values:"); Enter i and j values: 10 20
scanf("%d%d",&i,&j); Before swapping: 10 20
printf("Before swapping:%d%d\n",i,j); After swapping: 10 20
swap(i,j);
FUNCTIONS

2 : Pass by reference (OR) Call by printf("After swapping:%d%d\n",i,j);


}
Reference : void swap(int *a,int *b)
{
Any changes made inside functions having formal int temp;
parameter are reflected back in the actual parameters of temp=*a;
the caller. *a=*b;
*b=temp;
}
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{ Output
int i,j; Enter i and j values: 10 20
printf("Enter i and j values:"); Before swapping: 10 20
scanf("%d%d",&i,&j); After swapping: 20 10
printf("Before swapping:%d%d\n",i,j);
swap(&i ,&j);
Storage Classes
There are four storage classes in C programming.
In C language, each variable has a storage class which is 1 : Automatic Storage class.
used to define scope and life time of a variable. 2 : Register Storage class.
Storage: Any variable declared in a program can be stored 3 : Static Storage class.
either in memory or registers. 4 : External Storage class.

Registers are small amount of storage in CPU. The data


stored in registers has fast access compared to data
stored in memory.
Storage Classes

1: Automatic Storage class :


• To define a variable as automatic storage class, the keyword auto is used.

• By defining a variable as automatic storage class, it is stored in the memory.

• The default value of the variable will be garbage value.

• Scope of the variable is within the block where it is defined .

• the life of the variable is until the control remains within the block.

Example:

void main()

int detail;

or
Storage Classes
void function1()
1: Automatic Storage class : {
int x=10;
void function1();
printf(“%d”,x);
void function2(); }
void function2()
void main() {
int x=0;
{ function1();
int x=100; printf(“%d”,x);
}
function2();

printf(“%d”,x);

}
Storage Classes

2: Register Storage class :


• To define a variable as register storage class, the keyword register is used.

• When a variable is declared as register, it is stored in the CPU registers.

• The default value of the variable will be garbage value.

• Scope of the variable is within the block where it is defined .

• the life of the variable is until the control remains within the block.

Register variable has faster access than normal variable. Frequently used variables are kept in

register. Only few variables can be placed inside register.

Ex: register int i;


Storage Classes

2: Register Storage class :


void demo(); void demo()
{
void main() register int i=20;
printf(“%d\n”,i);
{ i++;
}
demo();

demo();

demo();

}
Storage Classes

3 : Static Storage class :


• When a variable is declared as static, it is stored in the memory

• The default value of the variable will be zero value.

• Scope of the variable is within the block where it is defined .

• he life of the variable persists between different function calls.

• To define a variable as static storage class, the keyword static is used.

A static variable can be initialized only once, it cannot be reinitialized.

Syntax : static data_type variable_name


Storage Classes

3 : Static Storage class :


void demo(); void demo()
{
void main() static int i=20;
printf(“%d\n”,i);
{ i++;
}
demo();

demo();

demo();

}
Storage Classes

4 : External Storage class :


When a variable is declared as extern, it is stored in the memory

• The default value of the variable will be zero value.

• The scope of the variable is global .

• the life of the variable is until the program execution comes to an end.

• To define a variable as external storage class, the keyword extern is used. An extern variable is also called as a global
variable

Systax : extern data_type variable_name;

extern int i;
Storage Classes

4 : External Storage class :


Storage Classes
Recursion

When function is called within the same function, it is known as recursion in C. The function which calls the
same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail
recursion, we generally call the same function with return statement.

Features :
•  There should be at least one if statement used to terminate recursion.

•  It does not contain any looping statements.


Recursion

Advantages :

 It is easy to use.

 It represents compact programming structures.

Disadvantages :

 It is slower than that of looping statements because each time function is called.
Recursion

#include<stdio.h> void main(){


int fact=0;
#include<conio.h> clrscr();
int factorial (int n) fact=factorial(5);
printf("\n factorial of 5 is %d",fact);
{
getch();
if ( n < 0) }
return -1; /*Wrong value*/

if (n == 0)

return 1; /*Terminating condition*/

return (n * factorial (n -1));

}
STRINGS

String is an array of characters that is terminated by \0 (null character). This null character indicates the end
of the string. Strings are always enclosed by double quotes ( " " ). Whereas, character is enclosed by single
quotes.

Ex- char a[9];

Using this declaration the compiler allocates 9 memory locations for the variable a ranging from 0 to 8.
Initializing Array string

char str[5]={'5','+','A'};

str[0]; ---> 5

str[1]; ---> +

str[2]; ---> A

str[3]; ---> NULL

str[4]; ---> NULL

Note: In initialization of the string we can not initialized more than size of string elements.

Ex:

char str[2]={'5','+','A','B'}; // Invalid


String

Different ways of initialization can be done in various ways :

1 : Initilizing locations character by character.

2 : Partial array initialization.

3 : Intilization without size.

4 : Array initialization with a string .


1 : Initializing locations character by character.

Consider the following declaration with initialization,

Char b[9]={’C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’};

The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized with the
characters in the order specified. The remaining locations are automatically initialized to null characters.
2 : Partial Array Initilization :

If the characters to be initialized is less than the size of the array, then the characters are stored sequentially
from left to right.The remaining locations will be initialized to NULL characters automatically.

int a[10]={‘R’,’A’,’M’,’A’ };
3 : Initilization without size :
:consider the declaration along with the initialization

char b[]={‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’};

In this declaration, The compiler will set the array size to the total number of initial values i.e 8. The
character will be stored in these memory locations in the order specified.
4) Array Initilization with a String :
consider the declaration with string initialization.

char b[ ] = “COMPUTER”;

Here, the string length is 8 bytes. But , string size is 9 bytes. So the compiler reserves 8+1 memory
locations and these locations are initialized with the characters in the order specified. The string is
terminated by \0 by the compiler.
String Handling Functions

All these functions are defined in string.h header file.


1 : strlen(string) – String Length :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[]="JBREC";
int len1,len2;
clrscr();
len1=strlen(name);
len2=strlen("JBRECECE");
printf("The string length of %s is: %d\n",name,len1);
printf("The string length of %s is: %d","JBRECECE",len2);
getch();
}

OUTPUT :
The string length of JBREC is : 5
The string length of JBRECECE is :8
2 : strcpy(string1,string2) – String Copy :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[]="REDDY";
char str2[10];
strcpy(str2,str1);
printf("The string1 is :%s\n",str1);
printf("The string2 is :%s\n",str2);
strcpy(str2,str1+1);
printf("The string1 is :%s\n",str1);
printf("The string2 is :%s",str2);
}
OUTPUT :
The string1 is : REDDY
The string2 is : REDDY
The string1 is : REDDY
String Copy(w/o string function) :
#include<stdio.h>
#include<conio.h>

void main()
{
char str1[10],str2[20];
int index;
printf("Enter the string\n");
scanf(“%s”,str1);
for(index=0;str1[index]!='\0';index++)
str2[index]=str1[index];
str2[index]='\0';
printf("String1 is :%s\n",str1);
printf("String2 is :%s\n",str2);
getch();
}
OUTPUT :
Enter the string : cprogramming
String1 is : cprogramming
String2 is : cprogramming
3: strcat(string1,string2) – String Concatenation :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()

void main()
{
{
char str1[10]="jbrec";
char str2[]="ece";
strcat(str1,str2);
printf("%s\n",str1);
printf("%s\n",str2);
getch();
}

OUTPUT : jbrecece
ece
String Concatenation (W/O using String function)

#include<stdio.h>
void main(void)
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
4 : strlwr(string) – String LowerCase
: #include<stdio.h>
#include<conio.h>
#include<string.h>
void main()

void main()
{
char str[]="JBREC";
clrscr();
strlwr(str);
printf("The lowercase is :%s\n",str);
getch()
}

OUTPUT :
The lowercase is : jbrec
string LowerCase w/o using string
function
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
int index;
printf("Enter the string:");
scanf("%s",str);
for(index=0;str[index]!='\0';index++)
{
if(str[index]>='A' && str[index]<='Z')
str[index]=str[index]+32;
}
printf("After conversionis :%s",str);
getch()
}

OUTPUT : Enter the string : SUBBAREDDY


After conversion string is :subbareddy
5 : strupr(string) – String
UpperCase
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[]="jbrec";
strupr(str);
printf("UpperCase is :%s\n",str);
getch();
}

OUTPUT : UpperCase is : JBREC


String UpperCase w/o using
function
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
int index;
printf("Enter the string:");
scanf("%s",str);
for(index=0;str[index]!='\0';index++)
{
if(str[index]>='a' && str[index]<='z')
str[index]=str[index]-32;
}
printf("After conversionis :%s",str);
getch();
}
OUTPUT : Enter the string : subbareddy
After conversion string is :SUBBAREDDY
6:strcmp(string1,string2) String
Comparision
#include<stdio.h>
:
#include<string.h>
void main()
{
char str1[]="reddy";
char str2[]="reddy";
int i,j,k;
i=strcmp(str1,str2);
j=strcmp(str1,"subba");
k=strcmp(str2,"Subba");
printf("%d%d%d\n",i,j,k);
}

OUTPUT : 0 -1 32
String Comparision w/o using string
function
#include<stdio.h>
#include<conio.h> if(str1[index]!=str2[index])
#include<string.h>
{
void main()
flag=0;
{
break;
char str1[10],str2[20];
}
int index,l1,l2,flag=1;
}
printf("Enter first string:");
}
scanf("%s",str1);
else
printf("Enter second string:");
flag=0;
scanf("%s",str2);
if(flag==1)
l1=strlen(str1);
printf("Strings are equal");
l2=strlen(str2);
else
printf("Length of string1:%d\n",l1);
printf("Strings are not equal");
printf("Length of string2:%d\n",l2);
}
if(l1==l2)
{
for(index=0;str1[index]!='\0';index++)
{
7 : strrev(string) - String Reverse :
#include<stdio.h>
#include<conio.h> OUTPUT : Enter the string :subbareddy
#include<string.h> The string reversed is : ydderabbus
void main()
{
char str[20];
printf("Enter the string:");
scanf("%s",str);
printf("The string reversed is:%s",strrev(str));
getch();
}
String reverse w/o using string
function
include <stdio.h>
OUTPUT : Enter the string :subbareddy
#include <string.h>
The string reversed is : ydderabbus
void main(){
char string[20],temp;
int i,length;
printf("Enter String : ");
scanf("%s",string);
printf("%d", strlen(string)/2);
length=strlen(string)-1;
for(i=0;i<strlen(string)/2;i++){
temp=string[i];
string[i]=string[length];
string[length--]=temp;
}
printf("Reverse string :%s",string);

You might also like