Вы находитесь на странице: 1из 17

Computer Programming (Unit III & IV)

Program for Matrix Multiplication


#include<stdio.h>
#include<conio.h>
void main()
{
int a[25][25], b[25][25], c[25][25], i , j, k, r, s, m, n;
clrscr();
printf(" Enter the row and columns of A matrix.......");
scanf("%d%d",&m,&n);
printf("Enter the row and columns of B matrix…….");
scanf("%d%d",&r,&s);
if(n!=r)
printf("\n The matrix cannot multipled");
else
{
printf(“\n Input for Matrix A”);
for(i=0;i<r;i++)
{
for(j=0;j<s;j++)
{
scanf("%d",&a[i][j]);
}
}
printf(“\n Input for Matrix B”);
for(i=0;i<r;i++)
{
for(j=0;j<s;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<s;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("The multiplication of two matrixes");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<s;j++)
1
{
printf("\t%d",c[i][j]);
}
}
getch();
}
}
OUTPUT:-
Enter the row and columns of A matrix ....... 3 3
Enter the row and columns of B matrix …… 3 3
Input for Matrix A
1 2 3 4 5 6 7 8 9
Input for Matrix B
1 2 3 4 5 6 7 8 9

The multiplication of two matrixes


30 36 42
66 81 96
102 126 150

Strings
 A string in C is a sequence of zero or more characters followed by a NULL '\0' character.
 All the string handling functions are prototyped in: string.h or stdio.h standard header file.

For example:
"c string tutorial"
Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character at the
end of string.

Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char s[5];

Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd"; OR,
char c[5]="abcd"; OR,
char c[]={'a','b','c','d','\0'}; OR;
char c[5]={'a','b','c','d','\0'};

2
Program1
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
scanf("%s",name); //Read the string
printf("Your name is %s",name); //Display the string
}
Output
Enter name: Dennis Ritchie
Your name is Dennis Ritchie

Program2
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
gets(name); //Read the string
printf("Your name is “);
puts(name); //Display the string
}
Output
Enter name: Dennis Ritchie
Your name is Dennis Ritchie

String handling functions

Function Work of Function


strlen() Calculates the length of string
strcpy() Copies a string to another string
strcat() Concatenates(joins) two strings
strcmp() Compares two string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase
strrev() Reverse the string

(i) strlen(s1);
Returns the length of string s1.
Program
#include<stdio.h>
#include<string.h>
void main()
{

3
char a[20]=”hello”;
printf(“\n Length of the string is :%d”,strlen(a));
}
Output
Length of the string is 5

(ii) strcpy(s1,s2);
Copying the string from s2 to s1.
Program
#include<stdio.h>
#include<string.h>
void main()
{
char a[20]=”hello”,b[20];
strcpy(b,a);
printf(“\n String a is %s & String b is %s, a, b);
}
Output
String a is hello & String b is hello

(iii) strcat(s1,s2);
This will concatnate s1 & s2 and assign it to s1.
Program
#include<stdio.h>
#include<string.h>
void main()
{
char a[20]=”hello”,b[20]=”welcome”;
strcat(a,b);
printf(“\n String a is %s & String b is %s, a, b);
}
Output
String a is hellowelcome & String b is welcome

(iv)strcmp(s1,s2);
This will compare the two string s1 & s2. If s1 is equal to s2 then it will return 0. Otherwise it
will return non zero.
Program
#include<stdio.h>
#include<string.h>
void main()
{
char a[20]=”hello”,b[20]=”welcome”;
if(strcmp(a,b)==0)
printf(“\n Strings are equal”);
else
printf(“\n Strings are not equal”);
}
4
Output
Strings are not equal

(v) strupr(s1);
It displays the string s1 in upper case.
Program
#include<stdio.h>
#include<string.h>
void main()
{
char a[20]=”hello”;
printf(“%s”,strupr(a));
}
Output
HELLO

(vi) strlwr(s1);
It displays the string s1 in lower case.
Program
#include<stdio.h>
#include<string.h>
void main()
{
char a[20]=”WELCOME”;
printf(“%s”,strlwr(a));
}
Output
Welcome

(vii) strrev(s1);
It displays the string s1 in reverse order.
Program
#include<stdio.h>
#include<string.h>
void main()
{
char a[20]=”welcome”;
printf(“%s”,strrev(a));
}
Output
emoclew

//Program to sort the names in ascending order


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
5
int i,j,n;
char str[20][20],temp[20];
clrscr();
printf("\nEnter the no. of string to be sorted");
scanf("%d",&n);
printf(“\n Enter n strings:\n”);
for(i=0;i<=n;i++)
scanf(“%s”,str[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
printf(“%s”,str[i]);
getch();
}
Output
Enter the no. of string to be sorted:5

Enter n strings:
Balu
Vinoth
Priya
Sekar
Raju

The sorted string


Balu
Priya
Raju
Sekar
Vinoth

Searching
Searching is a method of finding the element or items is present in the given set or list. It can be
applied in many real life situations. For example, search a word in the dictionary, search a phone
number in the telephone directory, search the address in the street and so on.

6
Types of Searching
There are two types of searching methods are there:
 Linear search
 Binary search

(i) Linear Search


One of the most straightforward and elementary searches is the sequential search, also known as a
linear search. Linear search or sequential search is a method for finding a particular value in a list that
consists of checking every one of its elements, one at a time and in sequence, until the desired one is
found.

Algorithm
Step 1: Get the search item X and the input array A with size n.
Step 2: Compare the search item X and compare with the first item i.e., a[0]. If it is matched, then
return the corresponding position of the array element and exit from the program.
Step 3: Otherwise, increment the array index by 1 and compare the array element with X.
Step 4: Repeat the process, until we find the solution.
Step 5: If the element is not found in the given array, then display the eroro ar “ Element is not found”

Program for linear search


#include <stdio.h>
#include <conio.h>
void main()
{
int array[100], search, c, n;
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);

7
}
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);
getch();
}

Output
Enter the number of elements in array
5
Enter 5 elements
5
6
3
2
7
Enter the number to search
2
2 is present at location 4

(ii) Binary Search


A binary search or half-interval search algorithm finds the position of a specified value (the input
"key") within a sorted array.

8
Algorithm
Algorithm is quite simple. It can be done either recursively or iteratively:
1. get the middle element;
2. if the middle element equals to the searched value, the algorithm stops;
3. otherwise, two cases are possible:
o Searched value is less, than the middle element. In this case, go to the step 1 for the part of the
array, before middle element.
o Searched value is greater, than the middle element. In this case, go to the step 1 for the part of
the array, after middle element.

Program for binary search


#include<stdio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0;
u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
u=mid-1;
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
}
Output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.

9
Linear Search vs. Binary Search

Linear Search Binary Search


A linear search works by looking at each A binary search comes with the
element in a list of data until it either finds prerequisite that the data must be sorted.
the target or reaches the end.
A linear search starts at the beginning of a A binary search starts in the middle of a
list of values, and checks 1 by 1 in order for sorted array, and determines which side (if
the result you are looking for. any) the value you are looking for is on.
That "half" of the array is then searched
again in the same fashion, dividing the
results in half by two each time.
Linear search doesn't requires the input data Binary search requires the input data to be
to be sorted sorted
Linear search only requires equality Binary search requires an ordering
comparisons comparison
Linear search has complexity O(n) Binary search has complexity O(log n)
Linear search only requires sequential access Binary search requires random access

Unit – IV

Functions
Functions are smaller self-contained components which carry out some specific, well defined task. The
benefits are:
 It facilitates top-down modular programming
 It avoids the need for redundant code
 It facilitates reusability
 It can be used to build a customized library of frequently used routines

(i) Function Prototypes


Declaration of a function is called function Prototype. Prototype specifies the signature of the function,
the return type and number and data types of the arguments. Functions must be declared before it is
called. In C, prototyping is not mandatory; it is needed if a function call precedes function definition.

Syntax
return_type function_name (function arguments);

Example
int find_big(int,int);
Function find_big returns integer value, takes 2 integer arguments
void swap(int *,int *);
Function swap does not return any value, takes 2 pointer variables.
float add(float, int);
Function add returns float value, takes 1 float variable and 1 integer variable.

10
(ii) Function Definition
It is used to define the function with appropriate name, parameters, and the task to be carried out by
the function. It can be defined at any location in the program. A function definition has two principle
components: Function header (first line) and Function body.

Syntax
return-type fn-name(type arg1, type arg2, ……)
{
local variable declaration;
executable statement 1;
executable statement 2;
……………..
return expression;
}

A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function
does.

(iii) Function Call


Functions can be invoked by specifying its name, followed by a list of parameters enclosed within
parentheses.

Syntax
[vble name]= fn-name(actual arguments);

Program for function


// Program for swapping the two numbers using functions
#include <stdio.h>
#include <conio.h>
void swap( int p1, int p2 ); /* function declaration or prototyping.*/
int main()
{
int a = 10, b = 20;
clrscr();
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( a, b ); /* function call */
11
printf("After: Value of a = %d and value of b = %d\n", a, b );
getch();
}
void swap( int p1, int p2 ) /* function definition */
{
int t;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Output
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b (p2) = 10
After: Value of a = 10 and value of b = 20

Recursion
A function which call by itself is called recursion. A recursive function must have the following
properties: The problem must be written in a recursive form. There must be a base criteria
(terminating condition) for which the function doesn’t call itself.

// Program for finding factorial using recursive functions


#include <stdio.h>
#include <conio.h>
int fact(int);
int main()
{
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

Output
Enter a number: 5
Factorial of 5 is: 120

12
Types of Function

Functions can be calssified into four categories based on arguments passed and the return type. They
are
 Functions with no arguments and no return value
 Functions with no arguments but return value
 Functions with arguments but no return value
 Functions with arguments and return value

(i) Functions with no arguments and no return value


 Called function does not have any argument
 Not able to get any value from the clling function
 Not returning any value
 There is no data transfer between calling function and called function

Program
#include<stdio.h>
void add(); //Function Prototype
void main()
{
add(); //Function Call
}
void add() //Function Definition
{
int a,b,c;
printf(“\n Enter a & b:”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“\n Result is %d”,c);
}

Output
Enter a& b:
3
4
Result is 7

(ii) Functions with no arguments and return value


 Does not get any value from the calling function
 Can give a return value to calling program

Program
#include<stdio.h>
int add(); //Function Prototype
void main()
{
int c;
13
c=add(); //Function Call
printf(“\n Result is %d”,c);

}
int add() //Function Definition
{
int a,b;
printf(“\n Enter a & b:”);
scanf(“%d%d”,&a,&b);
c=a+b;
return c;
}

Output
Enter a & b:
3
4
Result is 7

(iii) Functions with arguments but no return value


 A function has arguments
 A calling function can pass value to function called, but calling function not receive any value
 Data transferred from calling function to the called function but no data is transferred from the
called function to the calling function
 Output is displayed in the called function
 A function that does not return any value

Program
#include<stdio.h>
void add(int,int); //Function Prototype
void main()
{
int a,b;
printf(“\n Enter a & b:”);
scanf(“%d%d”,&a,&b);
add(a,b); //Function Call
}
void add(int x,int y) //Function Definition
{
int c;
c=x+y;
printf(“\n Result is %d”,c);
}

Output
Enter a & b:
3
4
14
Result is 7

(iv) Functions with arguments and return value


 Argument are passed by calling function to the called function
 Called function return any value to the calling function
 Data returned by the function can be used later in the program

Program
#include<stdio.h>
int add(int,int); //Function Prototype
void main()
{
int a,b,c;
printf(“\n Enter a & b:”);
scanf(“%d%d”,&a,&b);
c=add(a,b); //Function Call
printf(“\n Result is %d”,c);
}
int add(int x,int y) //Function Definition
{
return (x+y);
}

Output
Enter a & b:
3
4
Result is 7

Parameter Passing

A function is referenced by using its name and providing appropriate values for the arguments. There
are two approaches to pass the information to a function via arguments. They are:
 Call by Value
 Call by Reference

(i) Call by Value


This method copies the actual value of an argument into the formal parameter of the function. In this
case, changes made to the parameter inside the function have no effect on the argument.

Sample Program
#include <stdio.h>
void swap(int, int); // function declaration
void main ()
{
int a = 100, b=200;
printf("Before swap, value of a : %d\n", a );

15
printf("Before swap, value of b : %d\n", b );
swap(a, b); //Function Call
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
}
void swap(int x, int y) //function definition
{
int temp;
temp = x;
x = y;
y = temp;
}

Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

(ii) Call by Reference


This method copies the address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.

Sample Program
#include <stdio.h>
void swap(int *, int *); // function declaration
void main ()
{
int a = 100, b=200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(&a, &b); //Function Call
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
}
void swap(int *x, int *y) //function definition
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
16
Actual parameter Vs formal parameter

Actual parameter Formal parameter


Parameters which are in calling subprogram Parameters which are in called
are actual parameters. subprogram are formal
parameters.
Actual parameters can be constants Formal parameters are only variables.
,variables or expression
Actual parameters sends value to the formal Formal parameters receive values from
parameters actual parameters.

Call by Value Vs Call by Reference

Call by Value Call by Reference


This method copies the actual value of an This method copies the address of an argument
argument into the formal parameter of the into the formal parameter.
function.
changes made to the parameter inside the changes made to the parameter affect the
function have no effect on the argument. argument.
Example: Example:
void swap(int,int); //Function prototype void swap(int *,int *); //Function prototype
swap(a,b); //Function Call swap(&a,&b); //Function Call
void swap(int x, int y) //Function definition void swap(int *x, int *y) //Function definition
{ {
} }

17

Вам также может понравиться