Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

#include<stdio.

h>
#include<string.h> Longest Word in a String
int main()
{
int length=0,lmax=0,windex=0,i,j;
char str[100], word[100];
printf("Enter a String"); if(length>lmax)
gets(str); {
for(i=0;str[i]!='\0';i++) lmax=length;
{ windex=i;
if(str[i] != ' ') }
{ j=0;
length++; for(i=windex-lmax; i<windex; i++,j++)
continue; {
} word[j]=str[i];
if(length>lmax)
{ }
lmax=length; word[j]='\0';
windex=i; printf("Longest Word:%s\n", word);
} return 0;
length=0; }
}
Arrange in Ascending Order
#include<stdio.h>
int main()
{ for(i=1;i<=32767;i++)
int i,j; {
int x[5]; for(j=0;j<5;j++)
for(i=0;i<5;i++) {
{ if(x[j]==i)
scanf("%d",&x[i]); {
} printf("%d",x[j]);
printf("\nInput Values are\n"); }
for(i=0;i<5;i++) }
{ }
printf("%d",x[i]);
} }
printf("\n");
#include <stdio.h> Arrange in Ascending Order
int main()
{
int arr[] = {5, 2, 8, 7, 1};
int temp = 0; printf("\n");
int length = sizeof(arr)/sizeof(arr[0]);
printf("Elements of array sorted in ascending order: \
printf("Elements of original array: \n"); n");
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
printf("%d ", arr[i]); printf("%d ", arr[i]);
} }
return 0;
for (int i = 0; i < length; i++) { }
for (int j = i+1; j < length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("enter the second matrix element=\n");
Matrix Multiplication for(i=0;i<r;i++)
{
#include<stdio.h> for(j=0;j<c;j++)
#include<stdlib.h> {
int main(){ scanf("%d",&b[i][j]);
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; }
system("cls"); }
printf("enter the number of row=");
printf("multiply of the matrix=\n");
scanf("%d",&r);
for(i=0;i<r;i++)
printf("enter the number of column="); {
scanf("%d",&c); for(j=0;j<c;j++)
printf("enter the first matrix element=\n"); {
for(i=0;i<r;i++) mul[i][j]=0;
{ for(k=0;k<c;k++)
for(j=0;j<c;j++) {
{ mul[i][j]+=a[i][k]*b[k][j];
scanf("%d",&a[i][j]); }
} }
} }
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
Unit 3
Functions, argument passing- call by value and call by reference
Functions
• C enables its programmers to break up a program into segments
commonly known as functions, each of which can be written more or
less independently of the others. Every function in the program is
supposed to perform a well-defined task. Therefore, the program
code of one function is completely insulated from the other functions
In the figure, we can see that main() calls a function named func1(). Therefore, main() is
known as the calling function and func1() is known as the called function. The moment
the compiler encounters a function call, the control jumps to the statements that are a
part of the called function. After the called function is executed, the control is returned
to the calling program.
function is..a self-contained subprogram that is meant to do some specific, well-
defined task. A ( program consists of one or more functions.

If a program has only one function, then it must be the main ) function.
Function Declaration
Before using a function, the compiler must know the number of parameters and the
type of parameters that the function expects to receive and the data type of value
that it will return to the calling program. Placing the function declaration statement
prior to its use enables the compiler to make a check on the arguments used while
calling that function

return_data_type function_name(data_type variable1, data_type variable2,..);


Function Definition
When a function is defined, space is allocated for that function in the memory. A function
definition comprises of two parts:
•Function header
•Function body

•The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..)


{ .............
statements
.............
return(variable);
}
Note that the number of arguments and the order of arguments in the function header
must be the same as that given in the function declaration statement
While return_data_type function_name(data_type variable1, data_type variable2,...) is
known as the function header, the rest of the portion comprising of program
statements within the curly brackets { } is the function body which contains the code to
perform the specific task.

Note that the function header is same as the function declaration. The only difference
between the two is that a function header is not followed by a semi-colon
Function Call
• The function call statement invokes the function. When a function is invoked, the
compiler jumps to the called function to execute the statements that are a part of
that function.

• Once the called function is executed, the program control passes back to the calling
function.

• A function call statement has the following syntax:


• function_name(variable1, variable2, ...);
The following points are to be noted while calling a function:

• Function name and the number and the type of arguments in the function call must be
same as that given in the function declaration and the function header of the function
definition. Names (and not the types) of variables in function declaration, function call,
and header of function definition may vary.

•Arguments may be passed in the form of expressions to the called function. In such a
case, arguments are first evaluated and converted to the type of formal parameter and
then the body of the function gets executed.

•If the return type of the function is not void, then the value returned by the called
function may be assigned to some variable as given below

•variable_name = function_name(variable1, variable2, ...);


#include<stdio.h>
void drawline () ; /*Function Declaration* /
void main( )
{
draw1ine( ); /*Function Call*/
}

void drawline () / *Function Definition* /


{
int i;
for(i=1;i<=80;i++)
print f (“*" ) ;
}
#include<stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main()
{ int evenodd(int a) // FUNCTION HEADER
int num, x; {
printf("\n Enter the number : "); if(a%2 == 0)
scanf("%d", &num); return 1;
else
x = evenodd(num); //FUNCTION CALL retun 0;
}
if (x == 1)
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
return 0;
}
Function Arguments

• The calling function sends some values to the called function for communication;
these values are called arguments or parameters.

• Actual arguments: The arguments which are mentioned in the function call are known
as actual arguments, since these are the values which are actually sent to the called
function.

• Actual arguments can be written in the form of variables, constants or expressions or


any function call that returns a value For example- " fun(x), fun(a*b, c*d+k)
• func( 22, 43 )
Formal arguments

• The name of the arguments, which are mentioned in the function definition are
called formal or dummy arguments. since they are used just to hold the values
that are sent by the calling function.

• These, formal arguments are simply like other local variables of the function
which are created when the function call starts and are destroyed when the
function ends.
Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a program.

o We can call C functions any number of times in a program and from any place in a program.

o We can track a large C program easily when it is divided into multiple functions.

o Reusability is the main achievement of C functions.

o However, Function calling is always a overhead in a C program.


Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such
as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
User..Defined Functions

Users can create their own functions for performing any specific task of the program.
These types of functions are called user-defined functions.

1. Function definition .
2. Function declaration
3. Function call
Return Value

A C function may or may not return a value from the function. If you don't have to return
any value from the function, use void for the return type.

void hello();
#include<stdio.h>
int main()
{
hello();
return 0;
}

void hello()
{
printf("Function with no return value");
}
Different aspects of function calling

A function may or may not accept any argument. It may or may not return any value.
Based on these facts, There are four different aspects of function calls.

1. function without arguments and without return value


2. function without arguments and with return value
3. function with arguments and without return value
4. function with arguments and with return value
Function without arguments and without return value

Example 1

#include<stdio.h>
void printfn();
int main ()
{
printf("fn without arg and without return
value\n");
printfn();
}
void printfn()
{
printf("Hello Class");
}
Example 2

#include<stdio.h>
void sum();
int main()
{
printf("\nAdd two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Function without argument and with return value
#include<stdio.h>
void sum();
int main()
{
int result;
printf("\nAdd two numbers:");
result = sum();
printf("%d",result);
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a + b;
}
Function with argument and without return value
#include<stdio.h>
void sum(int, int);
int main()
{
int a,b,result;
printf("\nAdd two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int x, int y)
{
printf("\nThe sum is %d",x+y);
}
Function with argument and with return value

#include<stdio.h>
int sum(int, int);
int main()
{
int a,b,result;
printf("\nAdd two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int x, int y)
{
return x+y;
}
Program to check whether a number is even or odd (with argument and with return value)

Program to calculate the average of five numbers (with argument and without return value)

Program to calculate the area of the square (without argument and with return value)
Call by value and Call by reference in C

Call by value in C

• In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.

• In call by value method, we can not modify the value of the actual parameter by the
formal parameter.

• In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.

• The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(x);
printf("After function call x=%d \n", x);
return 0;
}
#include <stdio.h>
void swap(int , int);
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}
Call by reference in C

• In call by reference, the address of the variable is passed into the function call as the
actual parameter.

• The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.

• In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value
stored at the address of the actual parameters, and the modified value gets stored at
the same address.
#include<stdio.h>
void change(int *num)
{
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}

int main()
{
int x=100;
printf("Before function call x=%d \n", x);
change(&x);
printf("After function call x=%d \n", x);
return 0;
}
#include <stdio.h>
void swap(int *, int *);
int main() {
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Call By Value Call By Reference
A copy of the value is passed into the An address of value is passed into the
function function
Changes made inside the function is Changes made inside the function validate
limited to the function only. The values of outside of the function also. The values of
the actual parameters do not change by the actual parameters do change by
changing the formal parameters. changing the formal parameters.
Actual and formal arguments are created Actual and formal arguments are created
at the different memory location at the same memory location
Passing Arrays to Functions
Just like variables, array can also be passed to a function as an argument .
The array name itself is the address of first element of that array. For example if array name
is arr then you can say that arr is equivalent to the &arr[0].

Passing array to function using call by value method

int main()
#include <stdio.h>
{
void disp( char ch)
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
{
for (int x=0; x<10; x++)
printf("%c ", ch);
{
}
disp (arr[x]);
}

return 0;
}
Passing array to function using call by reference

When we pass the address of an array while calling a function then this is called function
call by reference. When we pass an address as an argument, the function declaration
should have a pointer as a parameter to receive the passed address.
#include <stdio.h> int main()
void disp( int *num) {
{ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
printf("%d ", *num); for (int i=0; i<10; i++)
} {
disp (&arr[i]);
}

return 0;
}
Methods to declare a function that receives an array as an argument

1. The receiving parameter of the array may itself be declared as an array

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


int add(int array[5]) int arr[5] = {2,3,4,5,6};
printf("Array sum is %d\n", add(arr));
{
return 0;
int sum = 0; }
for (int i = 0; i < 5; i++)
{
sum += array[i];
}
return sum;
}
2. The receiving parameters may be declared as an unsized array

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


int arr[5] = {76,89,67,23,24};
int findMin(int arr[], int size) printf("The minimum element is %d\n ", findMin(arr, 5));
{ return 0;
int min = arr[0]; }
for (int i = 1; i < size; i++)
{
if (min > arr[i])
{
min = arr[i];
}
}
return min;
}
#include<stdio.h> int greatest(int b[])
int greatest(int []); {
int n; int i=1,num1;
int main() num1=b[0];
{ while(i < 5)
int a[5],num,i; {
printf(" Input elements in the array"); if(num1<b[i])
for(i=0;i<5;i++) num1=b[i];
{ i++;
scanf("%d",&a[i]); }
} return num1;
num=greatest(a); }

printf(" The largest element is : %d",num);


return 0;
}
3. The receiving parameters can be declared as a pointer
#include <stdio.h> int main() {
void reverseArray(int * arr, int start, int end) int arr[] = {1,2,3,4,5,6};
{
while (start < end) { int n = sizeof(arr) / sizeof(arr[0]);
int temp = arr[start];
arr[start] = arr[end]; printArray(arr, n);
arr[end] = temp;
start++; reverseArray(arr, 0, n - 1);
end--;
} printf("Reversed array is\n");
}
void printArray(int * arr, int size) { printArray(arr, n);
for (int i = 0; i < size; i++)
printf("%d ", arr[i]); return 0;
}
printf("\n");
}
Recursion in C
Recursion is a method of solving the problem where the solution to a problem depends
on solutions to smaller instances of the same problem.

Any function which calls itself is called recursive function, and such function calls are
called recursive calls. However, it is important to impose a termination condition of
recursion.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that
can be defined in terms of similar subtasks.
Program to Display counting from 1 to 10 without loop
#include <stdio.h>
int counting(int k);
int main() {
counting(1);

return 0;
}

int counting(int k)
{
if (k <= 10)
{
printf("%d",k);
counting(k+1);
}
}
Program to find the sum of first 10 numbers
int sum(int );

#include<stdio.h>
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int x) {
if (x > 0) {
return x + sum(x - 1);
} else {
return 0;
}
}
Factorial of a number using Recursion

#include <stdio.h> int fact(int n)


int fact (int); {
int main() if (n==0)
{ {
int n,f; return 0;
printf("Enter the number"); }
scanf("%d",&n); else if ( n == 1)
f = fact(n); {
printf("factorial = %d",f); return 1;
} }
else
{
return n*fact(n-1);
}
}
Scope Rules in C
Scope rules in C or scope of a variable means that from where the variable may directly be
accessible after its declaration. Outside this region, we cannot access the variable and it is
treated as an undeclared identifier.

There are three places where variables can be declared in C programming language −

1. Inside a function or a block which is called local variables.


2. Outside of all functions which is called global variables.
3. In the definition of function parameters which are called formal parameters.
Local Scope in C #include <stdio.h>
The local scope refers to the region
inside a block or a function. It is int main () {
the space enclosed between the { } int a, b;
braces. int c;
a = 10;
The variables declared within the b = 20;
local scope are called local c = a + b;
variables. printf ("value of a = %d, b = %d and c = %d\n",
Local variables are visible in the a, b, c);
block they are declared in and
other blocks nested inside that return 0;
block. }
Local scope is also called Block
scope.
Global Scope in C #include <stdio.h>
int x = 5;
The global scope refers to the region void display()
outside any block or function. {
printf("%d\n", x);
The variables declared in the global }
scope are called global variables. int main()
{
Global variables are visible in every part printf("Before change within main: ");
of the program. display();

Global is also called File Scope as the printf("After change within main: ");
scope of an identifier starts at the x = 10;
beginning of the file and ends at the end display();
of the file. }
Using Extern Keyword

Prg1.c Prg2.c

#include <stdio.h> #include<stdio.h>


int a; #include "prg1.c"
extern int a;
int main(void)
{ int myfun()
a=10; {
printf("%d",a); printf("%d", a);
} }

You might also like