Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Page 1 of 45

ARRAY

An array is a collection of related data items sharing same name and same
data type.

We need arrays to store a group of elements as a single data structured. This


helps to reduce the storage space and makes the accessing of element
easier.

Types of arrays:

1) One-dimensional array

2) Two-dimensional array

3) Multi-dimensional array

One dimensional arrays:

An array with one dimension or one index, with same name and same
type is called one dimensional array.

Syntax:

datatype array_name[size];

Here datatype is a type of data user wants to use. It may be int, char, float
etc.

Array Initialization

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

Memory representation of One-Dimensional array:

10 20 30 40 50

0 1 2 3 4

Here A is an array of elements .The elements are 10, 20,30,40,50. Each


element is stored in memory locations.

Index or Subscript value: it is used to refer a particular element in an array.

In the above example 0,1,2,3,4 are called index values.

A[0]=10, A[1]=20, A[2]=30, A[3]=40, A[4]=50


Page 2 of 45

The characteristic of subscript of an array

subscript should be an integer.


subscript should start from zero.
subscript value cannot be negative.

To read and display One-dimensional array

To read
int A[5],i; for(i=0;i<5;i++)
scanf(“%d”,&A[i]);

To display
int A[5],i; for(i=0;i<5;i++)
printf(“%d”,A[i]);

Write a program to find the sum of array elements


#include<stdio.h>
#include<conio.h>
void main()
{
int A[50],i,n,sum=0;
clrscr();
printf("Enter the size of Array\n");
scanf("%d",&n);
printf("Enter the elements of Array\n");
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++)
sum=sum+A[i][j];
printf(“Sum=%d”,sum);
getch();
}
Page 3 of 45

Write a program to search an element in an array using Liner Search.

#include<stdio.h>
#include<conio.h>
void main()
{
int A[50],i,n,SE,pos=-1;
clrscr();
printf("Enter the size of Array\n");
scanf("%d",&n);
printf("Enter the elements of Array\n");
for(i=0;i<n;i++)
scanf("%d",&A[i]);
printf("Enter the element to Search in Array\n");
scanf("%d",&SE);
for(i=0;i<n;i++)
{
if(A[i]==SE)
{
pos=i;
break;
}
}
if(pos>-1)
printf("Element found in %d Position",pos+1);
else
printf("Element not found");
getch();
}
Page 4 of 45

Write a program to sort the element in Ascending and descending order.

void main()
{
int A[100], n, i, j, temp;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &A[i]);

for (i = 0 ; i < ( n - 1 ); i++)


{
for (j = 0 ; j < n - i - 1; j++)
{
if (A[j] > A[j+1])
{
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
}

printf("\n Sorted list in ascending order:\n");

for ( i = 0 ; i < n ; i++ )


printf("%d\t", A[i]);
printf("\n Sorted list in descending order:\n");

for ( i = n-1 ; i >= 0 ; i-- )


printf("%d\t", A[i]);

getch();
}
Page 5 of 45

Two–dimensional Arrays:

An array with two dimensions is called two dimensional arrays. or

An array having two dimensions or two indexes, with same name and same
type is called two-dimensional arrays.

Syntax: datatype array_name[rowsize][columnsize];

Here datatype is a type of data user wants to use. It may be int, char, float
etc.

Example: int A[3][2];

A contains 3 rows and 2 columns of integer values.

float x[2][6];

X contains 2 rows and 6 columns of float values.

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


array. This array has 2 rows and 6 columns

For better understanding of multidimensional arrays, array elements of above


example can be thinked of as below:

Two dimensional arrays are also called as matrix.

If number of rows is equivalent to number of columns, then it is said to be


square matrix.

If number of rows is not equivalent to number of columns, then it is said to


be rectangular matrix.
Page 6 of 45

Two-dimensional array initialization

int A[2][2]={1,2,3,4};

Here A is two dimensional array which contains 2 rows and 2 columns and
the assignments would be

A[0][0]=1 A[0][1]=2

A[1][0]=3 A[1][1]=4

To read and display Two-dimensional array

To read
int A[3][3],i,j;

for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&A[i][j]);

To display
int A[3][3],i,j;

for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”,A[i][j]);

Write a Program to add 2 matrices


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

void main()
{
int i,j,m, n, A[10][10], B[10][10], C[10][10];
clrscr();

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
Page 7 of 45

scanf("%d", &A[i][j]);
}

printf("Enter the elements of second matrix\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
scanf("%d", &B[i][j]);
}

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
{
C[i][j] = A[i][j] + B[i][j];
}
}

printf("Addition of two matrices:\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
printf("%d\t", C[i][j]);

printf("\n");
}
getch();

Write a Program to Subtract 2 matrices


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

void main()
{
int i,j,m, n, A[10][10], B[10][10], C[10][10];
clrscr();

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
Page 8 of 45

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
scanf("%d", &A[i][j]);
}

printf("Enter the elements of second matrix\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
scanf("%d", &B[i][j]);
}

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
{
C[i][j] = A[i][j] - B[i][j];
}
}

printf("Subtraction of two matrices:\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
printf("%d\t", C[i][j]);

printf("\n");
}
getch();

}
Page 9 of 45

Write a Program to find the Product of MXN Matrices

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

void main()
{
int m, n, p, q, i, j, k, sum = 0;
int A[10][10], B[10][10], C[10][10];
clrscr();

printf("Enter the number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);

if ( n != p )
{
printf("Matrices multiplication is not possible\n");
printf("Column of first matirx should be same as row of second matrix\n");
}
else
{
printf("Enter the elements of first matrix\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < n ; j++ )
scanf("%d", &A[i][j]);
}

printf("Enter the elements of second matrix\n");

for ( i = 0 ; i < p ; i++ )


{
for ( j = 0 ; j < q ; j++ )
scanf("%d", &B[i][j]);
}

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < q ; j++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + A[i][k]*B[k][j];
}
Page 10 of 45

C[i][j] = sum;
sum = 0;
}
}

printf("Product of entered matrices:-\n");

for ( i = 0 ; i < m ; i++ )


{
for ( j = 0 ; j < q ; j++ )
printf("%d\t", C[i][j]);
printf("\n");
}
}

getch();
}
Page 11 of 45

Write C program to find the trace and normal of a matrix

Trace is defined as the sum of main diagonal elements and


Normal is defined as square root of the sum of all the elements

#include <stdio.h>
#include<conio.h>
#include <math.h>
void main ()
{
int A[10][10];
int i, j, n, sum = 0, trace=0;
float normal;
clrscr();
printf("Enter the order of the matrix\n");
scanf("%d",&n);
printf("Enter the n coefficients of the matrix \n");
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &A[i][j]);
sum = sum + A[i][j] * A[i][j];
}
}
normal = sqrt(sum);
printf("The normal of the given matrix is = %.2f\n", normal);

for (i = 0; i < n; ++i)


{
trace = trace + A[i][i];
}

printf("Trace of the matrix is = %d\n", trace);


getch();
}

Multi-Dimensional Array

Collection of elements which shares same name and same data type of order
of N dimensions.
Syntax:
datatype arrayname[s1][s2][s3] ............ *sn+;

Example :
int A[10][10][10];
Page 12 of 45

STRING

A String is a sequence of character enclosed in a double quotes ( “ “ ).

Syntax:-

char array_name[size];

Example : char str[50];

Memory representation of String

char str[ ]=”GKMV”;

G K M V \0
str

0 1 2 3 4

Every time the last index value of a string is a NULL character ( \0 )

Note:-

a) The Null character (\0) signifies the end of the string.

b) The purpose of Null character is to indicate the end of the string.

c) The format specifier used for the string is %s.

Array of String

An array of string is a two dimensional array.

Consider an example that initializes 5 names in an array of strings and


prints them.

void main()
{
char name[5][20];
int i;
clrscr();
printf("Enter 5 names \n");
Page 13 of 45

for(i=0;i<5;i++)
gets(name[i]);
printf("The 5 Names entered are :\n");
for(i=0;i<5;i++)
puts(name[i]);
printf("\n");
getch();
}

Output
Enter 5 names
VARSHA G
KALYAN
MOHITH G
KALYAN
EENCHARA
NISARGA
RAM KUMAR

The memory representation is shown


below.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

V A R S H A G K A L Y A N \0

M O H I T H G K A L Y A N \0

E E N C H R A \0

N I S R A G A \0

R A M K U M A R \0

The string is an array; and name is an array of strings. It can be represented by a


two dimensional array of size [5][20] as shown above.
ie it contains 5 names of each length 20(including terminate character \0) and each
name is accessed by name[i]. here, we do not need the second index.
Name[i] is sufficient to access string number j in array.
Page 14 of 45

Draw back of scanf() function in a string

Multiple words or more than one word cannot be accepted using scanf()
function.

Reason

because scanf() function terminate the string when ever blank space is

encountered. to overcome this drawback gets() is used.

Example-1

X=”VARSHA G KALYAN”

What is the value stored in X with the following input statements.

a) gets(X);

b) scanf(“%s”,X)

Answer

gets( ) will have “VARSHA G KALYAN”

scanf( ) will have “VARSHA”

Example-2

str=”Computer Science”

What is the value stored in str with the following input statements.

a) gets(str);

b) scanf(“%s”,str)

Answer

gets( ) will have “Computer Science”

scanf( ) will have “Computer”


Page 15 of 45

gets( ) and puts( )

gets( )

gets( ) is an unformatted input function used to input a line of


text.

syntax

gets(string_name)

Example:-

char str[50];

gets(str);

puts( )

puts( ) is an unformatted output function used to display the


contents of the string.

syntax

puts(string_name)

Example:-

char str[50];

puts(str);

Different methods of inputting a string

a) gets( ) b) scanf( )

Example-1 char str[50];

gets(str);

Example-2 char str[50];

scanf(“%s”, str);
Page 16 of 45

Different methods of outputting a string

a) puts( ) b) printf( )

Example-1 char str[50];

puts(str);

Example-2 char str[50];

printf(“%s”, str);

STRING FUNCTION

Strings in C are represented by arrays of characters. The end of the string is


marked with a special character, the null character, The null or string-
terminating character is represented by another character escape sequence,
\0.

Also, at the top of any source file where we're using the standard library's
string-handling functions we must include the header file as shown below.

#include <string.h>

1. strlen( )

strlen( ) stands for string length function. strlen( ) is used to find


the length of a string.

Syntax

variable = strlen(string_name);

Example-1:

int Len;

Len=strlen(“GKMV”);

output:

Len=4
Page 17 of 45

Example-2:

int Len;

Len=strlen(“MGK VGK”);

output:

Len=7 (blank space is also considered as one character)

2. strrev( )

strrev( ) stands for string reverse function. strrev( ) is used to reverse


the content of

the string.

Syntax

strrev(string_name);

Example-1:

strrev(“GKMV”);

output:

VMKG

Example-2:

strrev(“MGK VGK”);

output:

KGV KGM

3. strlwr( )

strlwr( ) stands for string lower case function. strlwr( ) is used to


convert the upper case characters in a string to the lower case
characters.

Syntax

strlwr(string_name);
Page 18 of 45

Example-1:

strlwr(“GKMV”);

output:

gkmv

Example-2:

strlwr(“gKmv”);

output:

gkmv

4. strupr( )

strupr( ) stands for string upper case function. strupr( ) is used to convert
the lower case characters in a string to the upper case characters.

Syntax

strupr(string_name);

Example-1:

strupr(“gkmv”);

output:

GKMV

Example-2:

strupr(“GKmv”);

output:

GKMV

5. strcpy( )

strcpy( ) stands for string copy function. strcpy( ) is used to copy the
contents from Source string to Destination string.
Page 19 of 45

Syntax

strcpy(string2, string1);

string1 is Source string, string2 is Destination string.

The content of string1 will be assigned (copied) to string2.

Example-1:

char str[5];

strcpy(str, “GKMV”);

output:

the string str will be assigned with GKMV

6. strcat( )

strcat( ) stands for string concatenate function. strcat( ) is used to


combine two string. What it really does is append one string onto the
end of another string.

Syntax

strcat(string1, string2);

Example-1:

char str1[10]=”MGK”;

char str2[50]=”VGK”

strcat(str1, str2);

output:

str1 will have MGKVGK

str2 will have VGK

7. strcmp( )

strcmp( ) stands for string compare function. strcmp( ) is used to


compare two strings with ASCII values.

if both strings are equal strcmp returns 0. The value will be negative if
Page 20 of 45

string1 is less than string2, or positive in the opposite case.

Syntax

strcmp(string1, string2);

Example-1:

char str1[5]="GKMV";

char str2[5]="gkmv";

strcmp(str1,str2)

strcmp(str2,str1)

strcmp(str1,str1)

output:

-32
32
0

8. strcmpi( )

strcmpi( ) stands for string compare by ignoring the case.


strcmpi( ) is used to compare two strings by ignoring the case.

If the string are same(neglecting the case) it returns 0 otherwise nonzero.

Syntax

strcmpi(string1, string2);

Example-1:

char str1[5]="GKMV";

char str2[5]="gkmv";

strcmpi(str1,str2)

output:

0
Page 21 of 45

OPERATIONS ON CHARACTER

Programs that work with characters and strings often need to classify a
character--is it alphabetic, is it a digit, is it whitespace, and so on--and
perform case conversion operations on characters.

The functions in the header file `ctype.h' are provided for this purpose.

At the top of any source file where we're using the standard library's
character handling functions we must include the line

#include <ctype.h>

1. isaplha( )

isalpha( ) is used to test whether the character is an alphabetic character


or not.

Example:

isalpha(„G‟)
Output: True(1)
isalpha(„4‟)
Output: False(0)

2. isdigit( )

isdigit( ) is used to test whether the character is a digit or not.

Example:

isdigit(„5‟)
Output: True(1)
isdigit(„K‟)
Output: False(0)

3. islower( )

islower( ) is used to check whether a character is a lower case character or


not.

Example:
islower(„b‟)
Output: True(1)
islower(„B‟)
Output: False(0)
Page 22 of 45

4. isupper( )

isupper( ) is used to check whether a character is a upper case character


or not.

Example:

isupper(„G‟)
Output: True(1)
isupper(„g‟)
Output: False(0)

5. isspace( )

isspace( ) is used to test whether a character is a blank space


character or not.

Example:

isspace(„ „)
Output: True(1)
isspace(„H‟)
Output: False(0)

7. isalnum( )

isalnum( ) is used to check whether a character is a alphanumeric


character or not.

Example:

isalnum(„5‟)
Output: True(1)
isalnum(„G‟)
Output: True(1)
isalnum(„g‟)
Output: True(1)
isalnum(„+‟)
Output: False(0)
Page 23 of 45

8. tolower( )

tolower( ) is used to convert upper case character to lowercase


character.

Example:

tolower(„A‟)
Output: a
tolower(„a‟)
Output: a

8. toupper( )

toupper( ) is used to convert lower case character to uppercase


character.

Example:

toupper(„G‟)
Output: G
toupper(„g‟)
Output: G

WRITE A PROGRAM TO COUNT NUMBER VOWELS AND CONSONANTS IN A


GIVEN STRING

#include<ctype.h>

void main()
{
char str[100];
int i,vowels=0,consnts=0;
printf("Enter the Text\n");
gets(str);
for(i=0;str[i]!='\0';i++)
switch(toupper(str[i]))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U': vowels++;
Page 24 of 45

break;
default : consnts++;
}
printf("\n Number of Vowels = %d",vowels);
printf("\n Number of Consonants = %d",consnts);
}

PROGRAM TO READ A STRING AND CHECK WHETHER IT IS PALINDROME


OR NOT

#include<string.h>
void main()
{
char str[50],rstr[50];
clrscr();
puts("Enter the String");
gets(str); strcpy(rstr,str);
strrev(rstr);
if(strcmp(str,rstr)==0)
puts("String is Palindrome");
else
puts("String is not a Palindrome");
getch();
}

PROGRAM TO FIND THE LENGTH OF STRING WITHOUT USING BUILT-IN


FUNCTION

void main()
{
char str[50];
int i,len=0;
clrscr();
printf(“Enter a String “);
gets(str);
for(i=0;str[i]!='\0';i++)
len=len+1;
printf("lenght of string=%d",len);
getch();
}
Page 25 of 45

Write a c program to find if a character is alphabetic or numeric or


special character

#include<ctype.h>

void main()
{
char ch;
clrscr();
printf("Enter a character \n");
ch=getchar();
if(isalpha(ch))
printf("Character is Alphabetic ");
else if(isdigit(ch))
printf("Character Numeric");
else
printf("Special character");
getch();
}

Write a c program to accept a sentence and convert all lowercase to


upper case and vice-versa.

#include<ctype.h>
void main()
{
char str[50];
int i;
clrscr();
printf("Enter a string");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(isupper(str[i]))
str[i]=str[i]+32;
else if (islower(str[i]))
str[i]=str[i]-32;
}
printf("Converted String is ");
puts(str);
getch();
}
Page 26 of 45

Write a C Program to sort the name in alphabetic order


#include<stdio.h>
#include<conio.h>
#include<string.h>

void main()
{
char s[50][50], t[50];
int i,j,n;
clrscr();
printf("How many names do you like to enter\n");
scanf("%d",&n);

printf("Enter %d names:\n",n);
for (i=0;i<n;i++)
scanf("%s",&s[i]);

for (i = 1; i < n; i++)


{
for (j = 1; j < n; j++)
{
if (strcmp(s[j - 1], s[j]) > 0)
{
strcpy(t, s[j - 1]);
strcpy(s[j - 1], s[j]);
strcpy(s[j], t);
}
}
}

printf("\nStrings in Alphabetical order are : \n");


for (i = 0; i < n; i++)
printf("%s\n",s[i]);

getch();
}
Page 27 of 45

FUNCTIONS

Function is a self contained block of statement that performs a specific


task or job.

C program does not execute the functions directly. It is required to


invoke or call that functions. When a function is called in a program then
program control goes to the function body. Then, it executes the statements
which are involved in a function body. Therefore, it is possible to call function
whenever we want to process that functions statements.

Properties of functions:

□ Every function has a unique name. This name is used to call function
from main().
□ A function is independent and it can perform its task without
interfering with other parts of the program.
□ A function can be called from within another function.
□ A function performs a specific task.
□ Function can return only one value to the calling function via return.

Advantages of using functions:

There are many advantages in using functions in a program they are:

□ It is easy to use.
□ Debugging is more suitable for programs.
□ It reduces the size of a program.
□ It is easy to understand the actual logic of a program.
□ Highly suited in case of large programs.
□ By using functions in a program, it is possible to construct modular
and structured programs.

Types of functions:

1) Built-in functions or Pre-Defined functions


2) User-Defined functions
Page 28 of 45

Built-in functions or Pre-Defined functions

A function defined by the C complier. It is also called as Library functions


or Pre-Defined function or Built-in functions.

Example: printf(), scanf(),strcpy(),strlwr(),strcmp(),strlen(),strcat()

User-Defined functions:

C allows programmer to define their own function according to their


requirement. These types of functions are known as user-defined functions.

Arguments/Parameters: The variables which are inside the function call


are called arguments or parameters.

Function Prototype(declaration)

Every function in C programming should be declared before they are used. These
type of declaration are also called function prototype. Function prototype gives
compiler information about function name, type of arguments to be passed and
return type.

Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n) argument(n));

In the below example,

int addgk(int a, int b); is a function prototype which provides following information
to the compiler:

1. name of the function is addgk()


2. return type of the function is int.
3. two arguments of type int are passed to function.

Function prototype are not needed if user-definition function is written before main()
function.
Page 29 of 45

Function call
Control of the program cannot be transferred to user-defined function unless it is
called invoked.

Syntax of function call

function_name(argument(1), ... argument(n));

In the above example, function call is made using statement addgk(num1,num2);


from main(). This makes the control of program jump from that statement to
function definition and executes the codes inside that function.

Function definition
Function definition contains programming codes to perform specific task.

Syntax of function definition


return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}

Function definition has two major components:

1. Function declarator
Function declarator is the first line of function definition. When a function is
called, control of the program is transferred to function declarator.

Syntax of function declarator


return_type function_name(type(1) argument(1),....,type(n) argument(n))

Syntax of function declaration and declarator are almost same except, there is
no semicolon at the end of declarator and function declarator is followed by
function body.

In above example, int addgk(int a,int b) in line 12 is a function declarator.

2. Function body

Function declarator is followed by body of function inside braces.


Page 30 of 45

Passing arguments to functions


In programming, argument(parameter) refers to data this is passed to
function(function definition) while calling function.
In above example two variable, num1 and num2 are passed to function during
function call and these arguments are accepted by arguments a and b in
function definition.

Arguments that are passed in function call and arguments that are accepted in
function definition should have same data type. For example:

If argument num1 was of int type and num2 was of float type then, argument
variable a should be of type int and b should be of type float,

i.e., type of argument during function call and function definition should be
same.

A function can be called with or without an argument.

Return Statement
Return statement is used for returning a value from function definition to
calling function.

Syntax of return statement

return (expression);
Page 31 of 45

For example:
return a;
return (a+b);

In above example, value of variable add in add() function is returned and that
value is stored in variable sum in main() function. The data type of expression
in return statement should also match the return type of function.

Function Parameter:

Function parameters are the means of communication between the calling and
the called functions.

They are classified into Actual parameter and Formal parameters.

Actual parameters are specified in the function call often known as arguments.
Formal parameters are the parameters given in the function declaration and
function definitions.

Number of actual parameters should be equivalent to the number of formal


parameters.
Data types of the actual and formal parameters should be same.
The variable name of the formal parameters may be same as the actual parameters
or different.
Page 32 of 45

Scope:

Scope of a variable can be defined as the region over which the variable is
visible or valid.

Variable scope can be local and global.

Local variable, which are declared inside the function and restricted to the
function in which they are declared.

Global variable, which are declared outside all the functions and can be
accessed by all the functions.

Example

Output:

X=10 b=5

X=10 a=2
Page 33 of 45

In the above example a and b are called local variable, since they cannot be
accessed out their function. x is global variable, since it is accessed in main()
and gkmv() function.

Types of User-Defined Functions or Types of Functions:

1) Function with no arguments and no return value


2) Function with argument and no return value.
3) Function with no argument and return value.
4) Function with argument and return value
5) Recursions.

Function with no arguments and no return value:

When a function has no arguments, it does not receive any data from the
calling function. Similarly, when it does not return a value, the calling function
does not receive any data from the called function. So, there is no data
transfer between the calling function and the called function.

Example to illustrate Function with no arguments and no return value:

void main()
{
printf("Hello\n");
gkmv( );
printf("I am fine\n");
}
void gkmv( )
{
printf("How are you?\n");
}
Page 34 of 45

Output:

Hello
How are you?
I am Fine

Function with argument and no return value:

In this category, there is data transfer from the calling function to the called
function using the arguments. But, there is no data transfer from the called
function to the calling function. When arguments are passed, the function can
receive values from the calling function. When the function does not return a
value, the calling function cannot receive any value from the called function.

Example to illustrate Function with arguments and no return value:

void main()
{
void gkadd(int, int)

int a=10,b=5;
gkadd(a, b);
}

void gkadd(int a, int b)

{
printf(“Sum=%d”,a+b);

}
Page 35 of 45

Output

Sum=15

Function with no argument and return value:

In this category, there is no data transfer from the calling function to the
called function. But, there is data transfer from called function to the calling
function. When no parameters are there, the function cannot receive any
values from the calling function. When the function returns a value, the
calling function receives one value from the called function.

Example to illustrate Function with no arguments and return value:

void main()

{
int gkadd();

printf(“Sum=%d”,gkadd());
}

int gkadd()

{
int a=10,b=5;

return(a+b);
}
Page 36 of 45

Output

Sum=15

Function with argument and return value:

In this category, there is data transfer between the calling function and called
function. When parameters are passed, the called function can receive values
from the calling function. When the function returns a value, the calling
function can receive a value from the called function.

Example to illustrate Function with arguments and return value:

void main()

{
int gkadd(int, int)

int a=10,b=5;

printf(“Sum=%d”,gkadd(a,b));
}

int gkadd(int a, int b)

{
return (a+b);
}

Output

Sum=15
Page 37 of 45

Write a program to compute the sum of even numbers and the sum
of odd numbers using a function.

int n,i,osum,esum;
void main()
{
int gkodd(int);
int gkeven(int);
clrscr();
printf("Enter the value for n \n");
scanf("%d",&n);
printf("\n Sum of ODD number= %d ",gkodd(n));
printf("\n Sum of EVEN number= %d ",gkeven(n));
getch();
}

int gkodd(int n)
{
int osum=0;
for(i=1;i<=n;i+=2)
osum=osum+i;
return(osum);
}

int gkeven(int n)
{
int esum=0;
for(i=2;i<=n;i+=2)
esum=esum+i;
return(esum);
}
Page 38 of 45

Passing arrays to functions

Passing entire one-dimensional array to a function

While passing arrays to the argument, the name of the array is passed as an
argument(,i.e, starting address of memory area is passed as argument).

Write a C program to pass an array to a function. This function should


find sum of the array elements and display the sum in main function.

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

int sumofarray(int a[]);

void main()
{
int sum, A[]={23, 55, 42, 15, 64, 18};
clrscr();
sum=sumofarray(A); /* Only name of array is passed as
argument.*/
printf("Sum=%d",sum);
getch();
}

int sumofarray(int A[])


{
int i,sum=0;
for(i=0;i<6;i++)
{
sum=sum+A[i];
}
return(sum);
}
Page 39 of 45

Recursions:

A function that calls itself is known as recursive function and this technique is
known as recursion in C programming.

Recursion is a process by which a function calls itself repeatedly, until some


specified condition has been satisfied. The process is used for repetitive
computations in which each action is stated in terms of previous result.

In order to solve a problem recursively, two conditions must be satisfied. First,


the problem must be written in recursive form, and second, the problem
statement must include a stopping condition.

Advantages and Disadvantages of Recursion


Recursion is more elegant and requires few variables which make program
clean. Recursion can be used to replace complex nesting code by dividing the
problem into same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also
difficult to debug the code containing recursion.
Page 40 of 45

Write a recursive program to find the sum of first N natural numbers.

void main()
{
int
gksum(int);
int n;
printf("Enter the
number\n");
scanf("%d",&n);
printf("Sum of the first %d natural numbers is %d\n",n,gksum(n));
getch();
}

int gksum(int n)
{
if(n==0)
return 0;
else
return (n+gksum(n-1));
}

Write a recursive program to find the factorial of a given number:

void main()
{
long int gkfact(int);
int n;
printf("Enter the number\n");
scanf("%d",&n);

printf("\n the Factorial of %d is %ld",n,gkfact(n));


}

long int gkfact(int n)


{
if(n<=1)
return 1;
else return(n*gkfact(n-1));
}
BCA105T- Programming Concepts using C Page 41 of
45

Write a C program to display Fibonacci series using recursive function.


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

int gkfib(int);

void main()
{
int n,i;
clrscr();
printf("Enter the value of n \n");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( i = 1 ; i <= n ; i++ )
{
printf("%d\n", gkfib(i));
}

getch();
}

int gkfib(int n)
{
if ( n == 0 || n == 1)
return 0;
else if ( n == 2 )
return 1;
else
return ( gkfib(n-1) + gkfib(n-2) );
}
Page 42 of 45

Write a C program to calculate NCR= N!/ R! * (N-R)! Using function.

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

long gkfact(int);
long gkncr(int, int);

void main()
{
int n, r;
long ncr;
clrscr();
printf("Enter the value of n and r\n");
scanf("%d%d",&n,&r);
printf("NCR = %ld", gkncr(n, r));
getch();
}

long gkncr(int n, int r)


{
long ncr;
ncr = gkfact(n)/(gkfact(r)*gkfact(n-r));
return(ncr);
}

long gkfact(int n)
{
int i;
long fact = 1;
for( i = 1 ; i <= n ; i++ )
{
fact = fact*i;
}
return (fact);
}
Page 43 of 45

Storage Class

Every variable in C programming has two properties: type and storage class.
Type refers to the data type of variable whether it is character or integer or
floating-point value etc. And storage class determines how long it stays in
existence.

There are 4 types of storage class:

auto
register
static
external

a) auto
auto is the default storage class for all local variables.
Variables declared inside the function body are automatic by default. These
variable are also known as local variables as they are local to the function and
doesn't have meaning outside that function.
Since, variable inside a function is automatic by default, keyword auto are
rarely used.
Example: auto int x;
Default value of auto variables is garbage value. auto variables are stored in
the memory.

b) register
register is used to define local variables that should be stored in
a register instead of RAM. This means that the variable has a maximum size
equal to the register size (usually one word) and can‟t have the unary '&'
operator applied to it (as it does not have a memory location).

Register should only be used for variables that require quick access - such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a
register - depending on hardware and implementation restrictions.
Example: register int p;
Page 44 of 45

c) static
A variable for which memory remains allocated throughout the execution
of the entire program is called static variable. ie, the value of the static
variables continue until the end of the program.
Example: static int b;
#include <stdio.h>
void Check();
void main()
{
checkgk();
checkgk();
checkgk();
}
void checkgk()
{
static int a=0;
printf("%d\t",a);
a=a+5;
}

The output is
0 5 10

d) external

External variable can be accessed by any function. They are also known
as global variables. Variables declared outside every function are external
variables.

By default, all the global variables are external variables. We may also
use the keyword extern to declare external variables explicitly.
Example: extern int a;
Default value of external storage class is zero. External variables are
stored in the memory.
Page 45 of 45

#include <stdio.h>
void extergk();
int a=5; /* a is global variable because it is outside every function */
void main( )
{
a+=4;
extergk ();
}

void extergk ( )
{
++a;
printf("a=%d",a);
}

The Output is
a=10

You might also like