Anda di halaman 1dari 23

Chapter 3.

Functions & Arrays


1-Oct-07

1. Function : (What is function? Explain with example.)


Function is a part of program written to complete specific task. This gives
modularity to program. This makes very easy for finding the errors.
Syntax:
Return-type function-name(argument-list)
{
statement1;
statement2;
………….;
statementn;
}
// Program to add two numbers by using functions
int add(int a,int b) // Function Definition
{ int result;
result=a+b;
return(result);
}

void main()
{
int x, y, z;
cout<<”Enter two numbers “;
cin>>x>>y;
z=add(x,y); // Function call
cout<<”Addition of two numbers is “;
cout<<z;
}

2. Types of Functions: (What are types of functions?)


• Standard Library Functions
• User defined Functions

• Standard Library Functions


These functions are already defined by the language which are added
in header files.
Functions:
sin(x), cos(x), tan(x), pow(x,y), getch(), clrscr(), printf(), scanf()
Header files:
stdio.h, conio.h, math.h, ctime.h, cstdlib.h etc..

• User defined Functions


These functions are written by users to do specific work.
3. Scope Rules:
Local variables ( Used within a function where declared)
Global variables ( Used by any function & declared outside the funs)

CP Notes By Thombre D V Page 1 of 22


Chapter 3. Functions & Arrays
1-Oct-07
#include<iostream.h>
void show(int p)
{
int x=100; // Local variable declared
cout<<”Value of x is “<<x<<endl; // Used in this fun only
cout<<”Value of p is “<<p<<endl;
}

void main()
{ int m=50; // Local variable declared
show(); // Used in this fun only
}
#include<iostream.h>
int a,b; // Global variable used in any fun
void min()
{ int min=a;
if (a>b)
min=b;
cout<<”Minimum is “<<min;
}
void main()
{ cout<<”Enter the 2 values “;
cin>>a>>b;
min();
}
4. Function Prototypes: (What is function prototype?)
Prototype describes the function interface to the compiler by giving details
such argument passed, their types & return type.
Ex.
Return-Type Fun-Name(Arg-List);

float square(float x);


float volume(float y);
int add(int ,int);

#include<iostream.h>
void max(int x,int y); // Prototype
void main()
{ int a,b;
cout<<”Enter the values of “;
cin>>a>>b;
cout<<”\n Max No is “;
max(a,b); //Fucntion call
}
void max(int x,int y)
{ if(x>y)
return(x);
else
return(y);
}

CP Notes By Thombre D V Page 2 of 22


Chapter 3. Functions & Arrays
1-Oct-07
5. Parameter Passing (Function Call): (Explain parameter
passing.)
• Pass (Call) by value:
• Pass by reference

// Pass by value to exchange the values of vars


#include<iostream.h>
int swap(int,int);
void main()
{
int a=5, b=10;
cout<<”Print Original values \n“
cout<<a<<”\t”<<b<<endl;
swap(a,b);
cout<<”Print After swap fun call \n“
cout<<a<<”\t”<<b<<endl;
}
void swap(int x, int y)
{
int z=x;
x=y;
y=z;
cout<<”From Function\n”;
cout<<”x=”<<x<<”\t”<<” y=”<<y<<endl;
}
Here values of a & b are swapped but x & y are swapped again local to fun
swap.

// Pass by Ref. to exchange the values of vars


#include<iostream.h>
int swap(int*,int*);
void main()
{
int a=5, b=10;
cout<<”Print Original values \n“
cout<<a<<”\t”<<b<<endl;
swap(&a, &b);
cout<<”Print After swap fun call \n“
cout<<a<<”\t”<<b<<endl;
}
void swap(int *x, int *y)
{
int z=*x;
*x=*y;
*y=z;
}
The values of a & b are swapped.
Reference variable are declared as
int a=5; int &x=a; // Here x becomes another name for a (alias name)

CP Notes By Thombre D V Page 3 of 22


Chapter 3. Functions & Arrays
1-Oct-07

// Pass by Ref. to exchange the values of vars


#include<iostream.h>
int swap(int &x,int &y);
void main()
{
int a=5, b=10;
cout<<”Print Original values \n“
cout<<a<<”\t”<<b<<endl;
swap(a, b);
cout<<”Print After swap fun call \n“
cout<<a<<”\t”<<b<<endl;
}
void swap(int &x, int &y) // The values of a & b are swapped.
{ int z=x;
x=y;
y=z;
}
6. In-line Functions: ( What is inline function? give example.)
One of disadvantage of fun is it needs a switching time to jump towards
fun & while returning from fun. To reduce this time inline funs are used
where at compile time its code is embedded in main program to reduce
switching time. This is similar to C macro but macro is not compiled
where as functions are compiled.

inline function-Name(Arg-List)
{
Fun Body;
}

#include<iostream.h>
inline int square(int x)
{ return(x*x);
}
void main()
{
cout<<”Square of 10 is “<<square(10);
}
7. Default arguments:
Default values can be provided to arguments through prototypes.

int add(int a,int b=10);

//Providing default values to arguments


#include<iostream.h>
int add(int a,int b,int c=10,int d=5);
void main()
{
cout<<”Addition “<<endl;
cout<<add(10,10,15);

CP Notes By Thombre D V Page 4 of 22


Chapter 3. Functions & Arrays
1-Oct-07
}
int add(int m,int n,int o,int p)
{
return(m+n+o+p);
}

Rules:
Default values should be provided from right to left side.

void fun(int a,int b,int c=10);


void fun(int a,int b=5,int c=10);
void fun(int a=0,int b=5,int c=10);
void fun(int a=10,int b,int c=10); //Not valid
void fun(int a=10,int b,int c); //Not valid

8. Function Overloading: (What is function overloading? )


Functions can be overloaded by providing more definitions.

// Fun Overloading
#include<iostream.h>
int add(int x,int y);
float add(float ,float);
void main()
{
cout<<Addition of 10 & 15 “<<endl;
cout<<add(10,15);
cout<<Addition of 10.5 & 15.5 “<<endl;
cout<<add(10.5,15.5);
}
int add(int x,int y)
{
return(x+y);
}
float add(float x, float y)
{
return(x+y);
}

// Volume of cube , cylinder & rectangle


#include<iostream.h>
int volume(int x);
double volume(double, int);
long volume(long ,int,int);
void main()
{
cout<<volume(10)<<endl;
cout<<volume(2.5,5)<<endl;
cout<<volume(200L,15,5)<<endl;
}

CP Notes By Thombre D V Page 5 of 22


Chapter 3. Functions & Arrays
1-Oct-07

int volume(int x) //Cube


{
return(x*x*x);
}
double volume(double r, int h) // Cylinder
{
return(3.14*r*r*h);
}
long volume(long l,int b, int h) // Cylinder
{
return(l*b*h);
}

9. Recursion: (Explain recursion with example)


Recursion is a process in which a function calls itself.

#include<iostream.h>
int fact(int x);
void main()
{
cout<<”Factorial of a Number “<<endl;
cout<<”Enter a no “<<endl;
cin>>no;
cout<<fact(no);
}
int fact(int n)
{
if (n==1)
return(1);
else
return(n*fact(n-1));
}

// Calculate 1+2+3+………+n-1+n
#include<iostream.h>
int sum(int x);
void main()
{
cout<<”Sum upto n “<<endl;
cout<<”Enter a no “<<endl;
cin>>no;
cout<<sum(no);
}
int sum(int n)
{
if (n==1)
return(1);
else
return(n+sum(n-1));

CP Notes By Thombre D V Page 6 of 22


Chapter 3. Functions & Arrays
1-Oct-07
}
10. Storage classes: (What do U mean by storage classes?)
• Automatic
• Register
• Static
• External
Automatic
Storage is memory. Scope is local to fun. Initial value undefined.
#include<iostream.h>
void main()
{
auto int I, J;
cout<<I<<endl;
cout<<J<<endl;
}
any garbage value printed

Register
Scope is local to fun. Initial value undefined. This is used to store the value
directly into CPU registers so that speed of execution increased.
#include<iostream.h>
void main()
{
register int I=5, J=5;
cout<<I<<endl;
cout<<J<<endl;
}
Static
Storage is CPU register. Default value is 0. Scope local to fun.
#include<iostream.h>
void incr();
void main()
{ Output if i Non static
incr(); 1 1
incr(); 2 1
incr(); 3 1
}
void incr()
{ static int i=1;
cout<<i<<endl;
i++;
}
External
Storage is memory. Default value is 0. Scope is global.
#include<iostream.h>
int x=21;
void main()
{ extern int x;
cout<<x<<endl;
}

CP Notes By Thombre D V Page 7 of 22


Chapter 3. Functions & Arrays
1-Oct-07

11. Arrays: (Discuss arrays with examples.)


Arrays are used to store the similar type of elements. More than one
element are stored in a array which occupies consecutive memory
locations.
One dimensional
Two or Multi dimensional
Syntax
data-type array-name[dimension] ; // One dim
data-type array-name[dimension] [dimension] ; // Two dim
arrays can be initialized
int Odd[10]={1,3,5,7,9};
char Today[10]={‘M’,’O’,’N’,’D’,’A’,’Y’};
char Today[]=”Monday”;

#include<iostream.h>
void main()
{
int RollNo[3];
RollNo[0]=100;
RollNo[1]=101;
RollNo[2]=102;
cout<<RollNo[0]<<endl;
cout<<RollNo[1]<<endl;
cout<<RollNo[2]<<endl;
}
// Passing array elements to function
void display(int);
void main()
{
int RollNo[]={11,13,14,15,17};
for(int i=0;i<5;i++)
display(RollNo[i]);
}
void display(int x)
{
cout<<”\t”<<x;
}
//Accessing Array by Pointers
void main()
{
int Roll[ ]={11,12,13,14,15};
int *ptr;
ptr=&Roll[0];
for(int i=0;i<5;i++)
{
cout<<”\t”<<*ptr
j++;

CP Notes By Thombre D V Page 8 of 22


Chapter 3. Functions & Arrays
1-Oct-07
//Passing array to function
void display(int *,int);
void main()
{
int Roll[]={1,2,3,4,5};
display(&Roll[0],5);
}
void display(int *j,int n)
{
for(int i=0;i<n;i++)
{
cout<<”\t”<<*j;
j++;
}
}
//WAP to arrange numbers in ascending order
void main()
{
int Num[100],n,x;
cout<<”How many Numbers “;
cin>>n;
cout<<”Enter the “<<n<< “Numbers”<<endl;
for(int i=0; i<n;i++)
cin>>Num[i];
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{ if(Num[j]>Num[j+1])
{ x=Num[j];
Num[i\=Num[j+1];
Num[j+1]=x;
}
}
for(int i=0;i<n;i++)
cout<<Num[i]<<”\t”;
}
// Add two matrix
void main()
{
int mat1[3][4]={ { 1,2,3,4},
{5,6,7,8},
{4,5,6,7} };
int mat2[3][4]={ {1,2,3,4},
{5,6,7,8},
{4,5,6,7} };
int mat3[3][4];
for(int i=0;i<3;i++)
{ for(int j=0;j<4;j++)
{ mat3[i][j]=mat1[i][j]+mat2[i][j];
cout<<mat3[i][j]<<”\t”;
} cout<<endl;
}

CP Notes By Thombre D V Page 9 of 22


Chapter 3. Functions & Arrays
1-Oct-07
//WAP for Matrix Multiplication
void main()
{ int mat1[3][2], mat2[2][4], mat3[3][4];
// Reading
cout<<”Enter vallues 3X2 first matrix “<<endl;
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
cin>>mat1[i][j];

cout<<”Enter vallues 2X4 second matrix “<<endl;


for(int i=0;i<2;i++)
for(int j=0;j<4;j++)
cin>>mat2[i][j];
//Display
cout<<”Display First Matrix”<<endl;
for(int i=0;i<3;i++)
{ for(int j=0;j<2;j++)
cout<<mat1[i][j]<<”\t”;
cout<<endl;
}

cout<<”Display Second Matrix”<<endl;


for(int i=0;i<2;i++)
{ for(int j=0;j<4;j++)
cout<<mat2[i][j]<<”\t”;
cout<<endl;
}
//Generate third matrix
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
for(int k=0;k<4;k++)
mat3[i][k] +=mat1[i][j]*mat2[j][k];
}
}
// Display 3rd matrix
cout<<”Display Third Matrix”<<endl;
for(int i=0;i<3;i++)
{ for(int j=0;j<4;j++)
cout<<mat3[i][j]<<”\t”;
cout<<endl;
}
}

12. Strings: (Explain string functions with examples)


Character arrays are called as strings. String end with Null char i.e. \0.
Hence no of chars in string are more by one char i.e. \0.

CP Notes By Thombre D V Page 10 of 22


Chapter 3. Functions & Arrays
1-Oct-07
#include<iostream.h>
void main()
{
char Str[]=”Dnyanesh”;
int i=0;
char *ptr;
while(Str[i] !=’\0’)
{
cout<<Str[i];
i++;
} // last value of I becomes length of string
cout<<”Length of string is “ <<i;
// By using Pointer
ptr=Str ;
while(*ptr !=’\0’)
{
cout<<*ptr;
ptr++;
}
}

Functions gets & puts can be used for strings to read & display.
// Copy a one string into other
#include<iostream.h>
void main()
{
char string1[50],string2[50];
int i=0;
cout<<”Enter first string “<<endl;
gets(string1);
while(string[i] !=’\0’)
{ string2[i]=string1[i];
i++;
}
cout<<”The Copied string is “;
puts(string2);
}
// Concatenation of two strings into one
#include<iostream.h>
void main()
{
char string1[50],string2[50],string3[100];
int i=0,j=0;
cout<<”Enter first string “<<endl;
gets(string1);
cout<<”Enter Second string “<<endl;
gets(string2);
while(string1[i] !=’\0’)
{ string3[i]=string1[i];
i++;
}

CP Notes By Thombre D V Page 11 of 22


Chapter 3. Functions & Arrays
1-Oct-07
while(string2[j] !=’\0’)
{ string3[i]=string1[j];
i++; j++;
}
cout<<”The Third string is “;
puts(string3);
}

Standard Library Functions:

strlen(s) String length in int strrchr(s1,c) search last char in s1


strlwr(s) Convert to lower case strstr(s1,s2) search s2 into s1 rtn ptr
strcat(s1,s2) append s1 by s2 strset(s1,c) set all char of s1 to c
strcmp(s1,s2) compares value 0 - + strncat(s1,s2,n) append s1 by s2 upto n chars
strcpy(s1,s2) copy s2 into s1 strncmp(s1,s2,n) compares first n chars
strcmpi(s1,s2) compare ignore case strncmpi(s1,s2,n) compares n chars ignore case
strupr(s) convert to uppercase strncpy(s1,s2,n) copy n chars of s2 to s1
strdup(s) duplicates into self strnset(s1,c,n) replace s1 by c upto n char
strchr(s1,c) search 1st char in s1 strrev(s) reverse a string

#include<iostream.h>
#include<string.h>
void main()
{
char str1[20]=”Dnyanesh”;
char str2[]=”Thombre”;

//Display string
cout<<str1<<” “<<str2<<endl;
cout<<”Chars in str1 & str2 “<<endl
cout<<strlen(str1)<<” “<<strlen(str2)<<endl;
cout<<”Concatenation “<<endl;
strcat(str1,str2);
cout<<str1<<endl;
strcpy(str1,str2); // string copy
cout<<str1<<endl;
cout<<strcmp(str1,str2); //Compare strings
}

13. Preprocessor Directive: (What is preprocessor directivs?)


These are the directions to the pre-processor. These are not the part of
instruction sets. These directives are executed first then program starts
executing the instructions. These starts with # sign.
#include<iostream.h> // Header file directive
#define size 10 //constant is seze with value 10
#define PI 3.14
#define square(x) (x*x)
#define MIN(a,b) ((a)>(b)?(b):(a))

CP Notes By Thombre D V Page 12 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Macro makes program faster where as function slows down the program.
Macro is pre-processor directive. Function used for modular programming.

#ifdef print
cout<<”This will be displayed if print is defined”<<endl;
cout<<”End of ifdef stmt “;
#else
cout<<”This will be displayed if print is not defined”<<endl;
cout<<”End of else stmt “;
#endif

#define print
similar are #if #else #endif
// Program for
#define pi 3.14
void main()
{
#if pi==3.14
cout<<”PI is defined “ <<pi<<endl;
#else
cout<<”PI is undefined “;
#endif
}

#undef // To remove declaration


#pragma inline // To add assembly code into c prog
asm {
}

#pragma startup myfun // call fun at startup

Standard Library Functions


Header File ctype.h
int isalnum(int c) // returns nonzero if true else zero
int isalpha(int c)
int iscntrl(int c)
int isdigit(int c)
int isgraph(int c) //printing char
int islower(int c)
int isprint(int c)
int ispunct(int c)
int isspace(int c)
int isupper(int c)
int isxdigit(int c) //Hex digit
tolower(int c)
toupper(int c)

CP Notes By Thombre D V Page 13 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Header File math.h
acos(x) asin(x) atan(x) ceil(x) cos(x)
exp(x) fabs(x) floor(x) log(x)
log10(x) pow(x,y) sin(x) sqrt(x) tan(x)

Header File process.h


abort(); exit(); // use to terminate the process
Header File stdlib.h
atoi() ascii to int
atoll() to long
itoa() int to ascii
labs() long abs
ltoa() long to ascii
max() find max value
min() find min value
rand() generate random value.
__________________________________________________________

CP Notes By Thombre D V Page 14 of 22


Chapter 3. Functions & Arrays
1-Oct-07

Ex1.
/* Program to find Recursive function power(x,y) to find x^y */
# include <iostream.h>
# include<conio.h>
int power ( int x, int y);
void main( )
{
int x, y ;
cout<< "\n Enter value of x & y : ";
cin>>x>>y;
cout<<"\n"<<x<<" ^ "<<y<<" = "<< power(x,y);
}
int power (int x, int y) // Recursive
power function
{
if (y ==1)
return x;
else
return(x * power(x,y-1));
}
Ex2
/* Program to compute GCD &LCM */
# include <iostream.h>
# include<conio.h>
void swap(int &, int &);
long LCM (long, long) ;
long GCD(long, long);
void main( )
{
int m,n;
cout<<"\n Enter two positive integers : ";
cin >> m >> n ;
cout<<"GCD ( " << m <<", "<<n<<" ) = " <<GCD(m,n)<<endl;
cout<<"LCM ( " << m <<", "<<n<<" ) = " <<LCM(m,n)<<endl;
}
void swap(int & x, int & y)
{
//exchange the values of x and y
int temp = x;
x = y;
y = temp;
}
long GCD(long m, long n)
{
if(m<n)
swap(m,n);
while (n > 0)
{
int r = m % n;
m = n;
n = r ;
}
return m;
}
long LCM(long m, long n)
{
return m * n/GCD(m, n);
}
Ex3.

CP Notes By Thombre D V Page 15 of 22


Chapter 3. Functions & Arrays
1-Oct-07
/* Program to perform sorting and to display largest and second
largest elements in the list */
# include <iostream.h>
# include<conio.h>
# define TRUE 1
#define FALSE 0
#define MAX 20
void bubble(int x[ ], int n)
{
int hold, j, pass;
int switched = TRUE;
for(pass=0; pass<n-1&&switched==TRUE; pass++)
{ // Outer loop controls the number of passes
switched = FALSE;
// Initially no interchange have been made on this pass
for(j=0; j<n-pass-1; j++)
// Inner loop governs each individual pass
if (x[j] > x[j+1])
{ //Interchange elements if they are out of order
switched = TRUE;
hold=x[j];
x[j] = x[j+1];
x[j+1] = hold;
} //end if
} // end for
} // end bubble function
void main( )
{
int i, n;
int x[MAX];
cout<<"\n Enter numbers of elements :";
cin>>n;
cout<<"\n Enter Numbers in any order : \n";
for(i=0; i<n; i++)
{ cout<<"\n Element["<<i<<"] = ";
cin>>x[i];
}
bubble(x,n);
cout<<"\n \nSorted Elements are : \n";
for(i=0; i<n; i++)
cout<<"\n Element["<<i<<"] = "<<x[i];
// Displays the largest and 2nd largest element from sorted list
cout<<"\n\n Largest Element is : "<<x[n-1];
cout<<"\n Second largest Element is : "<<x[n-2];
}
Ex4.
#include<iostream.h>
#include<conio.h>
#include<math.h>
double power(double m, int n = 2);
void main()
{ int m,n;
cout << "\n Enter value of m & n";
cin >> m >> n;
cout << " power("<< m <<", "<< n <<") = "
<< power (m, n);
cout << "power(" << m <<", 2)" << power (m);
getch( );
}
double power (double m, int n)
{ return(pow(m, n));
}

CP Notes By Thombre D V Page 16 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Ex.5
#include<iostream.h>
#include<conio.h>
#include<string.h>
float ADD (float, float);
int ADD (int, int);
char * ADD (char *, char *);
char S1 [50] , S2 [50], S3 [100];
void main ( )
{ int n = ADD (4, 6);
float d = ADD (4.7, 8.4)
;
cout << " Add (4, 6) = " << n ;
cout << " Add (4.7, 8.4) = " << d << " \n" ;
strcpy (S1, " Object oriented ");
strcpy (S2, " Database model ");
strcpy (S3, ADD (S1, S2));
cout << S1 << " + " << S2 << " = " << S3 ;
getch( ) ;
}
float ADD (float a, float b)
{
return (a + b);
}
int ADD (int a, int b)
{
return (a + b);
}
char * ADD (char* S1, char* S2)
{
strcat (S1, S2) ;
return S1;
}
Ex.6
//main file funcall.cpp
#include<conio.h>
#include<iostream.h>
#include "log_x10.cpp"
#include"expo.cpp"
void main()
{ logx10();
expo();
}
//logx_10.cpp
# include<math.h>
# include<iostream.h>
void logx_10()
{ int n=0;
cout<<"Enter number;";
cin>>n;
cout<<"The log value is "<<log(n);
}
//expo.cpp
# include<math.h>
# include<iostream.h>
void expo()
{ int n=0;
cout<<"Enter number:";
cin>>n;
cout<<"\n Exponential value="<<exp(n);
}

CP Notes By Thombre D V Page 17 of 22


Chapter 3. Functions & Arrays
1-Oct-07

Ex.7
# include<iostream.h>
# include<conio.h>
void main()
{ int j=0;
clrscr();
void extend(double[], double[],double[]);
double qty[10]={3,9.7,6.40,4.5,5.6,6.2,7,2.8,15.0,18.0};
double
price[10]={10.20,11.30,13.14,16.9,18.1,2.71,7.55,15.12,9.45,17.0};
double amount[10]={1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0};
double tamount[10];
extend(qty,price,amount);
for (j = 0; j <= 9; j++)
{ tamount[j] = amount[j];
}
for(j=0;j<=9;j++)
{ cout<<tamount[j]<<"\n";
}
getch();
}
void extend(double q[], double p[], double amount[])
{ int i=0;
for(i=0;i<=9;i++)
{
amount[i]=q[i]*p[i];
}
}
Ex.8
# include<iostream.h>
# include<conio.h>
void main()
{ int no=0,pos=0;
void delchar(char[],int,int);
char string[10];
cout<<"Enter string";
cin>>string;
cout<<"Enter no. of characters to delete";
cin>>no;
cout<<"Enter starting position";
cin>>pos;
pos = pos - 1;
delchar(string,no,pos);
getch();
}
void delchar(char s[], int n, int p)
{
int i, c;
for(i=p,c=0;c<n;i++)
{
s[i]=' ' ; c++;
}
while (s[i]!='\0')
{
s[p] = s[i];
p++; i++;
}
s[p]='\0';
cout<<"\nNow string is :" << s;
}

CP Notes By Thombre D V Page 18 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Ex.9
#include<iostream.h>
#include<conio.h>
void main ( )
{ char a [20], ch ;
int i , count ;
cout<< "\n Enter a String : " ;
cin>>a;
cout<<"\nEnter a character to check its frequency in given
string :";
cin>>ch;
i = 0 ;
while (a[i]!='\0')
{
if ( ch == a [ i ] )
count = count +1 ;
i = i + 1 ;
}
cout<< "\nFrequency of given letter is "<<count ;
getch ( ) ;
}
Ex.10
/*// Program to find s2 in s1 where s1 is the main string and s2 is
substring */
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<stdio.h>
void main ( )
{ char s [ 20 ], s1 [ 20 ], s2 [ 20 ], *p = " " ;
int i ;
clrscr();
cout<< "\n Input string :" ;
gets ( s );
cout<< "\n Enter second string " ;
gets ( s2 );
strcpy ( s1, s );
p = strtok ( s2, " " ) ;
for ( i = 0; p ; i ++ )
{
if ( strcmp ( p, s2 ) == 0 )
cout << "\n string found " ;
p = strtok ( NULL, " " ) ;
}
getch ( ) ;
}
Ex.11
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main ( )
{ char s [ 15 ] ;
int i , p ;
cout<< "\nEnter any string : ";
cin>>s;
p = strlen ( s ) ;
for ( i = 0; i < p ; i ++ )
cout<< "\nElement at position "<<i+1<<" is"<<
s[i] ;
getch ( ) ;
}

CP Notes By Thombre D V Page 19 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Ex.12
#include<iostream.h>
#include<conio.h>
void main()
{
int x[100],i=1,avg=0,max=0,min=0,sum=0;
cout<<"\nEnter the values in the array X";
for(i=0; i<100; i++)
cin>>x[i];
for(i=0;i<100;i++)
cout << "Element ["<< i + 1 <<" ] = " << x[i];
for(i=0;i<100;i++)
sum=sum+x[i];
cout<<"\n Sum of array elements is : "<<sum;
avg=sum/100;
cout<<"\n Average of array elements is : "<<avg;
for(i=0; i<100; i++)
{
if (x[i]>avg) max++;
else min++;
}
cout<<"\n Total "<<max<<" numbers are present in array X ";
cout<<"\nwhich are greater than average";
cout<<"\nTotal "<<min<<" numbers are present in array X ";
cout<<"\nwhich are less than average";
getch( );
}
Ex.13
#include<iostream.h>
#include<math.h>
#define MAX 5
#include<conio.h>
void main( )
{
float mean=0,variance=0;
int i,x[MAX];
clrscr();
for(i=0;i<MAX;i++)
{
cout<<"\n Enter array elements: ";
cin>>x[i] ;
mean = mean+x[i];
}
mean = mean/MAX;
cout<<"\n Mean : "<<mean ;
for(i=0;i<MAX;i++)
variance = variance + (x[i]-mean)*(x[i]-mean);
variance = variance/MAX;
cout<<"\nVariance : "<<variance ;
cout<<"\n Standard Deviation : "<<sqrt(variance);
}

CP Notes By Thombre D V Page 20 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Ex.14
#include <iostream.h>
#include <math.h>
#include<conio.h>
int ack (int m, int n);
void main ( )
{
int x, y, z;
cout<< "\n Enter values of x and y" ;
cin>>x>>y;
z = ack (x, y);
cout<<z;
getch ( );
}
int ack ( int m, int n )
{
int p;
if ( m == 0 )
return ( n + 1 );
else if ( n == 0 && m > 0 )
p = ack ( m - 1, 1 );
else if ( m >= 0 && n >= 0 )
p = ack ( m - 1, ack ( m, n - 1 ) );
return (p);
}
Ex.15
/* Program to compute combination Function */
# include <iostream.h>
# include<conio.h>
long comb( int n, int r);
void main( )
{
for ( int i = -1; i < 6; i++)
{
for( int j = -1; j <= i+1; j++)
cout<<" "<<comb(i,j);
cout<<endl;
}
}
long fact( int n);
long comb( int n, int r)
{
if ( n < 0 || r < 0 || r > n)
return 0;
return fact(n) / ( fact (r) * fact (n -r));
}

long fact (int n)


{
if (n < 2) return 1;
long f = 1;
for (int i = 2; i <= n; i++)
f *= i;
return f;
}

CP Notes By Thombre D V Page 21 of 22


Chapter 3. Functions & Arrays
1-Oct-07
Ex.16
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 5

int main()
{
int a[MAX][MAX],i,j;
cout<<"\nEnter the matrix row wise :";

for(i=0;i<MAX;i++)
{
for(j=0;j<MAX;j++)
{
cout<<"\n Enter a["<<i<<"]["<<j<<"]element : ";
cin>>a[i][j];
}
}

for(i=0;i<MAX;i++)
{
for(j=0;j<MAX;j++)
{
if(i!=j && a[i][j]!=0)
{
cout<<"\nMatrix is not diagonal matrix";
getch(); exit(0);
}
}
}
cout<<"\nMatrix is diagonal matrix";
getch();
return(0);
}

CP Notes By Thombre D V Page 22 of 22


Filename: Chap 3.doc
Directory: E:\dvt\Subjects\F.E\Notes CP
Template: C:\Documents and Settings\Thombre\Application
Data\Microsoft\Templates\Normal.dotm
Title:
Subject:
Author: SHRI
Keywords:
Comments:
Creation Date: 10/1/2007 3:57:00 PM
Change Number: 30
Last Saved On: 3/25/2010 10:47:00 AM
Last Saved By: Thombre D v
Total Editing Time: 420 Minutes
Last Printed On: 3/25/2010 10:53:00 AM
As of Last Complete Printing
Number of Pages: 22
Number of Words: 3,668 (approx.)
Number of Characters: 20,912 (approx.)

Anda mungkin juga menyukai