50
Unit-C Programming in C Page 1 TOTAL:-39 Marks 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 elements are 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 The characteristic of subscript of an array subscript should be an integer. subscript should start from zero. subscript value cannot be negative.

Unit-C (1)

Embed Size (px)

Citation preview

Page 1: Unit-C (1)

Unit-C Programming in C Page 1

www.gkmvkalyan.blogspot.in

TOTAL:-39 Marks

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 elements are 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

The characteristic of subscript of an array

• subscript should be an integer. • subscript should start from zero. • subscript value cannot be negative.

Page 2: Unit-C (1)

Unit-C Programming in C Page 2

www.gkmvkalyan.blogspot.in

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 SORT N NUMBERS IN ASCENDING ORDER USING SELECTION SORT

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i,j,small,pos,a[50];

printf("enter the number of elements in a list\n");

scanf("%d",&n);

printf("enter the elements \n");

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

scanf("%d",&a[i]);

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

{

small=a[i];

pos=i;

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

{

if(small>a[j])

{

small=a[j];

pos=j;

} }

a[pos]=a[i];

a[i]=small;

}

printf("sorted list \n");

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

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

}

Page 3: Unit-C (1)

Unit-C Programming in C Page 3

www.gkmvkalyan.blogspot.in

WRITE A PROGRAM TO SORT N NUMBERS IN ASCENDING ORDER USING INSERTION SORT

#include<stdio.h>

#include<conio.h>

void main()

{

int A[50],n,i,j,temp;

printf("Enter the size of Array\n");

scanf("%d",&n);

printf("Enter the Element\n");

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

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

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

{

j=i;

while((j>=1) && (A[j]<A[j-1]))

{

temp=A[j];

A[j]=A[j-1];

A[j-1]=temp;

j=j-1;

}

}

printf("\n Sorted List is\n");

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

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

}

Page 4: Unit-C (1)

Unit-C Programming in C Page 4

www.gkmvkalyan.blogspot.in

WRITE A PROGRAM TO FIND THE MAXIMUM AND MINIMUM AND AVERAGE WEIGHTS OF THE BABIES IN A HOSPITAL

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i;

float a[10],max,min,sum,avg;

printf("enter the number of babies\n");

scanf("%d",&n);

printf("enter the weight of babies\n");

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

scanf("%f",&a[i]);

max=min=sum=a[0];

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

{

if(max<a[i])

max=a[i];

else if(min>a[i])

min=a[i];

sum=sum+a[i];

}

avg=sum/n;

printf("\n average weight of babies %.2f",avg);

printf("\n maximum weight of babies %.2f",max);

printf("\n minimum weight of babies %.2f",min);

}

Page 5: Unit-C (1)

Unit-C Programming in C Page 5

www.gkmvkalyan.blogspot.in

WRITE A PROGRAM TO FIND THE MAXIMUM AND MINIMUM ELEMENT IN AN ARRAY

#include<stdio.h>

#include<conio.h>

void main()

{

int a[50],i,n,max,min;

printf("Enter the size of the array\n");

scanf("%d",&n);

printf("Enter the array elements\n");

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

scanf("%d",&a[i]);

max=a[0];

min=a[0];

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

{

if(a[i]>max)

max=a[i];

else if(a[i]<min)

min=a[i];

}

printf("Maximum element=%d Minimum element=%d",max,min);

}

Page 6: Unit-C (1)

Unit-C Programming in C Page 6

www.gkmvkalyan.blogspot.in

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];

It contains 3 rows and 2 columns of integer values.

float name[2][2];

it contains 2 rows and 2 columns of float values.

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.

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]);

Page 7: Unit-C (1)

Unit-C Programming in C Page 7

www.gkmvkalyan.blogspot.in

a) Program to find the sum of two matrices of order mXn.

void main()

{

int A[10][10],B[10][10],C[10][10],i,j,m,n;

printf("Enter the order of the matrix\n");

scanf("%d%d",&m,&n);

printf("Enter the first matrix elements\n");

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

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

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

printf("Enter the second matrix elements\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("Sum of two matrices is\n");

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

{

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

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

printf("\n");

}

}

Page 8: Unit-C (1)

Unit-C Programming in C Page 8

www.gkmvkalyan.blogspot.in

b) Program to find the row sum and column sum for each row and column of a given matrix.

void main()

{

int A[10][10],m,n,i,j,rsum,csum;

printf("enter order of the matrix\n");

scanf("%d%d",&m,&n);

printf("enter matrix element\n");

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

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

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

printf("\n matrix is \n");

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

{

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

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

printf("\n");

}

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

{

rsum=0;

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

rsum=rsum+A[i][j];

printf("Sum of %d row=%d\n",i+1,rsum);

}

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

{

rsum=0;

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

rsum=rsum+A[j][i];

Page 9: Unit-C (1)

Unit-C Programming in C Page 9

www.gkmvkalyan.blogspot.in

printf("Sum of %d column=%d\n",i+1,rsum);

}

}

c) Program to find if the given matrix is square matrix then find sum of all elements in upper diagonal and lower diagonal.

void main()

{

int A[10][10],m,n,i,j,ude=0,lde=0;

printf("enter order of the matrix\n");

scanf("%d%d",&m,&n);

if(m==n)

{

printf("enter matrix element\n");

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

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

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

printf("\n matrix is \n");

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

{

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

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

printf("\n");

}

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

{

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

if(i<j)

ude=ude+A[i][j];

else if(i>j)

Page 10: Unit-C (1)

Unit-C Programming in C Page 10

www.gkmvkalyan.blogspot.in

lde=lde+A[i][j];

}

printf("\n Sum of all elements in upper diagonal =%d",ude);

printf("\n Sum of all elements in lower diagonal =%d",lde);

}

else

printf("Not a Square Matrix");

}

d) Program to check, if a given matrix is symmetric or not.

(Symmetric means if the original matrix is same as the transpose of the matrix, A= AT)

#include<stdio.h>

#include<conio.h>

void main()

{

int A[10][10],m,n,i,j,symetric=1;

clrscr();

printf("enter order of the matrix\n");

scanf("%d%d",&m,&n);

if(m==n)

{

printf("enter matrix element\n");

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

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

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

printf("\n matrix is \n");

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

{

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

Page 11: Unit-C (1)

Unit-C Programming in C Page 11

www.gkmvkalyan.blogspot.in

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

printf("\n");

}

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

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

{

if(A[i][j]!=A[j][i])

{

symetric=0;

break;

}

}

if(symetric==1)

printf("\n Symmetric matrix");

else

printf("\n Not a Symmetric Matrix");

}

else

printf("Not a Square Matrix");

}

e) Program to check whether matrix is square or rectangular. If it is square, check whether scalar or not.

(If all the diagonal elements are same, then the matrix is said to scalar matrix.)

#include<stdio.h>

#include<conio.h>

void main()

{

int a[5][5],n,m,i,j,scalar=1;

clrscr();

Page 12: Unit-C (1)

Unit-C Programming in C Page 12

www.gkmvkalyan.blogspot.in

printf("Enter the order of the matrix\n");

scanf("%d%d",&n,&m);

if(n==m)

{

printf("Given matrix is a square matrix\n");

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

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

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

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

/*To print the matrix*/

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

{

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

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

printf("\n");

}

/*To check for scalar matrix*/

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

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

if (i==j)

{

if((a[0][0]!=a[i][j])||(a[i][j]==0))

{

scalar=0;

break;

}

}

else

if(a[i][j]!=0)

{

Page 13: Unit-C (1)

Unit-C Programming in C Page 13

www.gkmvkalyan.blogspot.in

scalar=0;

break;

}

if(scalar==1)

printf("scalar matrix\n");

else

printf("Not a scalar matrix\n");

}

else

printf("Rectangular matrix\n");

getch();

}

f) Program to find the product of two matrices.

void main()

{

int a[5][5],b[5][5],c[5][5], i,j,k,n;

printf("Enter the order of the first matrix\n");

scanf("%d",&n);

printf("Enter the first matrix elements\n");

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

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

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

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

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

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

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

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

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

{

c[i][j]=0;

Page 14: Unit-C (1)

Unit-C Programming in C Page 14

www.gkmvkalyan.blogspot.in

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

c[i][j]=c[i][j]+a[i][k]*b[k][j];

}

printf("Resultant matrix is\n");

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

{

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

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

printf("\n");

}

}

Page 15: Unit-C (1)

Unit-C Programming in C Page 15

www.gkmvkalyan.blogspot.in

STRING OPERATIONS

STRING

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

Syntax:-

char variable_name[size];

Example : char str[50];

Memory representation of String

char str[5];

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.

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 over come this drawback gets() is used.

Example-1

X=”Pre-University Education”

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

a) gets(X);

G K M V ‘ \0 ’

Page 16: Unit-C (1)

Unit-C Programming in C Page 16

www.gkmvkalyan.blogspot.in

b) scanf(“%s”,X)

Answer

gets( ) will have “Pre-University Education”

scanf( ) will have “Pre-University”

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”

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);

Page 17: Unit-C (1)

Unit-C Programming in C Page 17

www.gkmvkalyan.blogspot.in

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);

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 HANDLING 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 line

#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”);

Page 18: Unit-C (1)

Unit-C Programming in C Page 18

www.gkmvkalyan.blogspot.in

output:

Len=4

Example-2:

int Len;

Len=strlen(“MGK VGK”);

output:

Len=7

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);

Example-1:

strlwr(“GKMV”);

output:

gkmv

Page 19: Unit-C (1)

Unit-C Programming in C Page 19

www.gkmvkalyan.blogspot.in

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.

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

Page 20: Unit-C (1)

Unit-C Programming in C Page 20

www.gkmvkalyan.blogspot.in

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 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

Page 21: Unit-C (1)

Unit-C Programming in C Page 21

www.gkmvkalyan.blogspot.in

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

CHARACTER HANDLING FUNCTION

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)

Page 22: Unit-C (1)

Unit-C Programming in C Page 22

www.gkmvkalyan.blogspot.in

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)

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)

6. ispunct( )

ispunct( ) is used to check whether a character is a punctuation character or not.

Example:

ispunct(‘,’) Output: True(1) ispunct(‘X’) 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: Unit-C (1)

Unit-C Programming in C Page 23

www.gkmvkalyan.blogspot.in

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<stdio.h> #include<conio.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++; break; default : consnts++; } printf("\n Number of Vowels = %d",vowels); printf("\n Number of Consonants = %d",consnts); }

Page 24: Unit-C (1)

Unit-C Programming in C Page 24

www.gkmvkalyan.blogspot.in

WRITE A PROGRAM TO COUNT THE FREQUENCY OF OCCURRENCE OF A CHARACTER IN A STRING

#include<stdio.h> #include<conio.h> void main( ) { char str[100],ch; int i,count=0; printf("Enter the Text\n"); gets(str); printf("Enter the Character to count\n"); ch=getchar( ); for(i=0;str[i]!='\0';i++) { if(str[i]==ch) count++; } if (count>0) printf("\n %c Occurs %d times",ch,count); else printf("\n %c does not exist",ch); }

WRITE A PROGRAM TO INPUT A LINE OF TEXT AND REMOVE ALL BLANKS AND PUNCTUATIONS

#include<ctype.h> void main() { char str1[100],str2[100]; int i,j; printf("Enter the Text\n"); gets(str1); for(i=0,j=0;str1[i]!='\0';i++) { if(!(ispunct(str1[i]) || isspace(str1[i]))) str2[j++]=str1[i]; } str2[j]='\0'; printf("\n Text after removing all blanks and punctuations\n"); puts(str2); }

Page 25: Unit-C (1)

Unit-C Programming in C Page 25

www.gkmvkalyan.blogspot.in

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

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()

Page 26: Unit-C (1)

Unit-C Programming in C Page 26

www.gkmvkalyan.blogspot.in

User-Defined functions:

A function defined by the user.

Arguments/Parameters: The variables which are inside the function call are called arguments or parameters.

Function Definition:

Syntax

• Here Return_type indicates the type of value a function is returning (like int, char,

float,void) If there is no return expression in the function, then the return_type is

void.

• Function_name indicates the name of the function. It is any valid variable name

allowed in C language.

• The argument list contains valid variable names separated by commas. The list must

be enclosed by parenthesis. All argument variables must be declared with their

types after the function header and before the opening brace of the function body.

• Statement 1, statement 2, ……….. statement n are executable statements

• A function may or may not send back any value to the calling function. If it sends, it

is done through the return statement.

Return statement:

The return statement takes one of the following forms:

return; Or return (expression);

Page 27: Unit-C (1)

Unit-C Programming in C Page 27

www.gkmvkalyan.blogspot.in

• the first return statement does not return any value. When return is encountered,

the control is immediately passed back to the calling function.

• The second form of return with an expression returns the value of the expression.

• The default return type is int. if you don’t want to return any value from a function,

use the data_type void. It means nothing.

Function Prototype(declaration):

The declaration of function header, before calling a function is called function prototype.

Function declaration describes the function interface to the compiler by giving details such as the number and the type of arguments and type of return values.

When the function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly.

Syntax of function prototype:

return_type function_name(argument_list);

the argument_list contains the type and name of arguments that must be passed to the 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 28: Unit-C (1)

Unit-C Programming in C Page 28

www.gkmvkalyan.blogspot.in

Example:

Page 29: Unit-C (1)

Unit-C Programming in C Page 29

www.gkmvkalyan.blogspot.in

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

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.

Page 30: Unit-C (1)

Unit-C Programming in C Page 30

www.gkmvkalyan.blogspot.in

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");

}

Output:

Hello How are you? I am Fine

Page 31: Unit-C (1)

Unit-C Programming in C Page 31

www.gkmvkalyan.blogspot.in

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);

}

Output

Sum=15

Page 32: Unit-C (1)

Unit-C Programming in C Page 32

www.gkmvkalyan.blogspot.in

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);

}

Output

Sum=15

Page 33: Unit-C (1)

Unit-C Programming in C Page 33

www.gkmvkalyan.blogspot.in

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 34: Unit-C (1)

Unit-C Programming in C Page 34

www.gkmvkalyan.blogspot.in

Recursions:

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.

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));

}

int gksum(int n)

{

if(n==0)

return 0;

else

return (n+gksum(n-1));

}

Page 35: Unit-C (1)

Unit-C Programming in C Page 35

www.gkmvkalyan.blogspot.in

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));

}

Write a recursive program to find the Nth term of a Fibonacci series.

void main()

{

int gkfibo(int);

int n;

printf("Enter the N th term\n");

scanf("%d",&n);

printf("The %d term of Fibonacci series is %d\n",n,gkfibo(n));

}

int gkfibo(int n)

{

Page 36: Unit-C (1)

Unit-C Programming in C Page 36

www.gkmvkalyan.blogspot.in

if(n==1)

return 0;

else if(n==2)

return 1;

else

return(gkfibo(n-1)+gkfibo(n-2));

}

Write a program to find Xn where n<0, n=0, n>0 using recursion.

void main()

{

float gkpower(float x, int n);

int n;

float x;

clrscr();

printf("Enter the value for base and power\n");

scanf("%f%d",&x,&n);

printf("%.2f power %d= %.3f\n",x,n,gkpower(x,n));

getch();

}

float gkpower(float x, int n)

{

if(x==0)

return 0;

else if(n==0)

return 1;

else if(n>0)

Page 37: Unit-C (1)

Unit-C Programming in C Page 37

www.gkmvkalyan.blogspot.in

return(x*gkpower(x,n-1));

else

return(1/x*gkpower(x,n+1));

}

Storage Classes:

The storage classes tell about scope and lifespan of the variable.

Moreover, a variable’s storage class tells us:

• Where the variable would be stored.

• What will be the initial value of the variable, if the initial value is not specifically assigned.(ie, the default initial value).

• What is the scope of the variable, ie in which functions the value of the variable would be available.

• What is the life of the variable; ie, how long would be the variable exist.

There are four storage classes in C:

• auto • register • static • external

auto variables:

All variables declared within a function are auto by default. Variables declared auto can only be accessed only within the function or the nested block within which they are declared. They are created when the function is called and destroyed automatically when the function is exited, hence the name auto.

Example: auto int a;

• Default value of auto variables is garbage value. • auto variables are stored in the memory.

register variables:

register variables are stored in the registers of the microprocessor. The number of variables which can be declared register are limited. A program that uses register variables executes faster as compared to a similar program without register variables. Loop indices, accessed more frequently, can be declared as register variables. The default value of register variable is zero. Only integer and character variables are declared as register variables.

Example: register int a;

Page 38: Unit-C (1)

Unit-C Programming in C Page 38

www.gkmvkalyan.blogspot.in

static variables:

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.

static variable are of two types:

• static variables that are declared within a function (function static variables). These variables retain their values from the previous call.

• file static variables. These variables are declared outside any function using the keyword static. file static variables are accessible only in the file in which they are declared. This case arises when multiple files are used to generate one executable code.

Example: static int a=1; Default value of static variable is zero. static variables are stored in the memory.

extern variables:

Variables that are both alive and active throughout the entire program are known as extern variables. External variables are declared outside a function. External variables can be accessed by any function in the program and change its value. Then, subsequent functions can reference only that new value.

• 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 39: Unit-C (1)

Unit-C Programming in C Page 39

www.gkmvkalyan.blogspot.in

POINTER

Pointer is a variable which contains the address of another variable. or

A variable which holds address of another variable is called a pointer variable.

Example:

If x is a variable and address of x is stored in a variable p (i.e. p=&x), then the variable p is called a pointer variable.

(Note: A pointer variable should contain only the addresses)

Syntax of declaring pointer variable:

datatype *identifier;

Here datatype indicates any data type like int, char, float etc. It can be derived or user defined data type also.

Identifier is the name given to the pointer variable. It should be a valid user-defined variable name.

The asterisk(*) in between type and identifier indicates that the identifier is a pointer variable.

Example: int *p; char *x; float *z,*a,*b;

Pointer operators or Operators used in Pointers:

a) Address operator(&): It is used to get the address of the variable where it is stored in the memory.

b) Indirection operator or Dereferencing operator or Asterisk(*): It used to get the value stored in the particular address.

Accessing variables through pointers:

We use indirection operator(*) to access the values of the variables through pointers.

Example: int x=10, *p;

p=&x;

printf(“%d”,*p);

Here *p prints the value of the variable x.(i.e. 10).

Page 40: Unit-C (1)

Unit-C Programming in C Page 40

www.gkmvkalyan.blogspot.in

Write a program to define three pointer variables for character, integer and float variables. Display the values and address of all the variables.

void main()

{ char c,*cptr; int i,*iptr;

float f,*fptr;

printf("Enter the character value\n");

scanf("%c",&c);

printf("Enter the integer value\n");

scanf("%d",&i);

printf("Enter the float value\n");

scanf("%f",&f);

cptr=&c;

iptr=&i;

fptr=&f;

printf("character value=%c and its address=%u\n",*cptr,cptr);

printf("integer value=%d and its address=%u\n",*iptr,iptr);

printf("float value=%f and its address=%u\n",*fptr,fptr);

}

Arithmetic operators & Expressions using operators

int a=10,b=20,*p1,*p2;

int sum,diff,prod,quo,rem;

p1=&a; p2=&b;

Page 41: Unit-C (1)

Unit-C Programming in C Page 41

www.gkmvkalyan.blogspot.in

Compatibility:

Compatibility means the type of data variable and type of the pointer variable should be same or compatible.

Example: int a,*p; p=&a is compatible

int x; char *y; y=&x; it is incompatible, since type of the data variable and the type of the pointer variables are different.

Pointers and Functions:

There are two ways of passing parameters to the functions:

a) Pass by value (also called call by value).

b) Pass by reference (also called call by reference).

a)Pass by value: Whatever the changes done inside the function is not reflected outside the function.

If the values of the formal parameters changes in the function, the values of the actual parameters are not changed. This way of passing parameters is called pass by value or call by value.

Example:

sum=*p1+*p2;

=10 + 20

=30

diff=*p1-*p2;

=10 - 20

=-10

prod=(*p1)*(*p2);

=10 * 20

=200

quo=*p1/*p2;

=10/ 20

=10.5

rem=*p1%*p2;

=10 % 20

=10(numerator is less than denominator )

Page 42: Unit-C (1)

Unit-C Programming in C Page 42

www.gkmvkalyan.blogspot.in

After execution of this program, the first printf() function prints the value x=10,y=20, then it calls the function gkswap(x,y), In the function gkswap(x,y), the values of x and y are interchanged. So in the gkswap(x,y), the printf() function prints x=20 and y=10, then the control will transferred to main() function and the printf function prints the value x=10 and y=20. This indicates that, in call by value, whatever modifications done to the formal parameters, it will be reflected in that particular functions, outside the functions the value will be remain same as actual parameter.

b) Pass by reference: Whatever the changes done inside the function is reflected inside the function as well as outside the function.

If the values of the formal parameters changes in the function, the values of the actual parameters are also changed.

Example:

After execution of this program, the first printf() function prints the value x=10,y=20, then it calls the function gkswap(&x,&y), In the function gkswap(&x,&y), the values of x and y are interchanged. So in the gkswap(&x,&y), the printf() function prints x=20 and y=10, then the control will transferred to main() function and the printf function prints the value x=20 and y=10. This indicates that, in call by reference, whatever modifications done to the formal parameters, it will be reflected in that functions and also outside the functions the value will be changed.

Page 43: Unit-C (1)

Unit-C Programming in C Page 43

www.gkmvkalyan.blogspot.in

Note: Using pointers, a function can return more than one value.

Memory allocation functions:

There are two types of memory allocation techniques. They are

1) Static memory allocation: Allocation of memory during the compile time is called static memory allocation.

Example: arrays

2) Dynamic memory allocation: Allocation of memory during run time is called dynamic memory allocation. Example: pointers, linked lists, trees etc

Advantages and Disadvantages of pointers:

Advantages:

i. More than one value can be returned using pointer concept. ii. Very compact code can be written using pointers. iii. Data accessing is much faster when compared to arrays. iv. The pointers in C language are mainly useful in non-primitive data structures

such as arrays, linked list and trees. Disadvantages:

1) Un-initialized pointers or pointers containing invalid addresses can cause system crash. 2) It is very easy to use pointers incorrectly, causing bugs that are very difficult to identify

and correct. 3) They are confusing and difficult to understand in the beginning and if they are misused,

the result is not predictable.

Page 44: Unit-C (1)

Unit-C Programming in C Page 44

www.gkmvkalyan.blogspot.in

FILES

A file is a place on the disk were data is stored permanently.

Declaration of file:

Syntax: FILE *variable;

• The keyword FILE tells the system that we are pointing to the file structure. The definition for the file structure is present in the header file stdio.h.

• Variable indicates any user defined variable name preceeded with star(*) operator.

Example : FILE *fp;

Opening a file:

To open a file, we use fopen() function.

Syntax of fopen():

variable=fopen(“filename”,”mode”);

o fopen() function opens the file named filename and assigns an identifier(variable) to

the FILE type pointer variable. This pointer variable which contains all the information

about the file is subsequently used as a communication link between the system and

the program.

o The mode specifies the purpose of opening this file. The mode can be one of the

following: r,w,a,r+,w+,a+.

Different modes of accessing a file:

MODE MEANING

r Read only

w Write only

a Append only

r+ Read + Write

w+ Read + Write

a+ Read+Write+Append

Page 45: Unit-C (1)

Unit-C Programming in C Page 45

www.gkmvkalyan.blogspot.in

Different modes of opening a file:

r mode (read mode):

Syntax:

FILE *fp;

fp=fopen(“sample”, ”r”);

This mode is used for opening an existing file to perform read operation. The various features of this mode are as follows:

* Used only for the text file.

* If the file does not exist, fopen() returns “NULL”.

* The contents of the file are not lost.

* The file pointer points to the beginning of the file.

w mode:( write mode):

Syntax:

FILE *fp;

fp=fopen(“sample”, ”w”);

This mode is used to create a file. The various features of this mode are as follows:

* Used only for the text file.

* If the file does not exist, a file is created.

* If the file already exists, the original contents of the file are lost.

* The file pointer points to the beginning of the file.

a mode(append mode):

Syntax:

FILE *fp;

fp=fopen(“sample”, ”a”);

This mode is used to insert the data at the end of the existing file. The various features of this mode are as follows:

Page 46: Unit-C (1)

Unit-C Programming in C Page 46

www.gkmvkalyan.blogspot.in

* Used only for the text file.

* If the file does not exist, a file is created.

* If the file already exists, the file pointer points to the end.

* The new data is inserted at the end.

* Existing data cannot be modified.

Note: If we have + as the suffix for the above modes, then in all the above three cases the file is opened for read/write operation with the same features as specified earlier.

i.e.

* r+: Existing file is opened for reading and writing.

* w+: Newly created file is opened for writing and reading. It destroys the old data.

* a+: Existing file is opened for writing and reading. It writes at the end of the file.

The file can be opened in the binary mode by suffixing ‘b’ at the end of these modes. i.e.

rb, wb, ab, rb+, wb+, ab+

Closing a file:

A file must be closed as soon as all operations on it have been completed. This ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental misuse of the file. Another instance where we want to close a file is when we want to reopen a file in different mode. We use fclose() function to close a file.

Syntax of fclose() function:

fclose(file_pointer);

This would close the file associated with the FILE pointer file_pointer.

Example:

FILE *fp1, *fp2;

fp1=fopen(“input”,”w”);

fp2=fopen((“output”,”r”);

………….. ………….. fclose(fp1);

fclose(fp2);

Page 47: Unit-C (1)

Unit-C Programming in C Page 47

www.gkmvkalyan.blogspot.in

Input output functions on FILE:

I. Character handling file functions:-

The getc() and putc() functions are used to handle with characters on files.

A) putc(): It is used to write a character to the file.

Syntax: char ch;

FILE *fp;

putc(ch,fp);

Assumes that a file is opened with mode w and file pointer fp. The above statement writes the character contained in the character variable ch to the file associated with File pointer fp.

B) getc(): It is used to read a character from the file.

Syntax: char ch;

FILE *fp;

ch=getc(fp);

Assumes that a file is opened with mode r and file pointer fp. The above statement read the character from the file and stored in the character variable ch.

Note: Difference between getchar() and getc().

• getchar() is used to read a character from the keyboard.

• getc() is used to read a character from the file.

Difference between putchar() and putc().

• putchar() is used to write a character or display a character on the monitor.

• putc() is used to write a character on the file

II. Integer handling file functions:-

The getw() and putw() functions are used to handle with Integers on files.

Page 48: Unit-C (1)

Unit-C Programming in C Page 48

www.gkmvkalyan.blogspot.in

a) putw():It is used to write a integer value to the file.

Syntax: int n;

FILE *fp;

putw(n,fp);

Assumes that a file is opened with mode w and file pointer fp. The above statement writes the integer value contained in the integer variable n to the file associated with File pointer fp.

b) getw(): It is used to read a integer value from the file.

Syntax: int n;

FILE *fp;

n=getw(fp);

Assumes that a file is opened with mode r and file pointer fp. The above statement read the integer value from the file and stored in the integer variable n.

III. Formated input-output functions of a file:-

a) fprintf(): This function is used to write a formatted data to the file.

Syntax: fprintf(filevariable,”formatspecifier”,variable(s));

Example:- int a,b;

FILE *fp;

fprintf(fp,”%d%d”,a,b);

Where fp is a file pointer associated with a file that has been opened for writing. The control string contains the output specifications for the items in the list. The list may include variables, constants and strings.

b) fscanf(): This function is used to read formatted data from the file.

Syntax: fscanf(filevariable,”formatspecifier”,&variable(s));

Example:- int a,b;

FILE *fp;

fscanf(fp,”%d%d”,&a,&b);

Page 49: Unit-C (1)

Unit-C Programming in C Page 49

www.gkmvkalyan.blogspot.in

Where fp is a file pointer associated with a file that has been opened for reading. The control string contains the input specifications for the items in the list. This statement reads the items in the list from the file specified by fp, according to the specifications in the control string.

Note:

1) The difference between printf() and fprintf() is, printf() function is used to display the output on the output screen whereas fprintf() function is used to write the data to the file.

2) The difference between scanf() and fscanf() is, scanf() function is used to read the data from the input device whereas fscanf() function is used to read the data from the file.

III. Files and Strings:-

fgets() and fputs() fgets(): It is used to read a line of text from a file.

Syntax: fgets(string_variable,size,file_pointer);

Example: FILE *fp;

Char str[100];

fgets (str, size, fp);

fputs(): It is used to write a line of text to the file.

Syntax: fputs(string_variable,size,file_pointer);

Example: FILE *fp;

Char str[100];

fputs (str, size, fp);

Other functions of FILE(random access to files):

1) ftell(): the function ftell() is used to find the current file pointer position in a given file from the beginning of the file. Syntax:

variable=ftell(fp);

where fp is the file pointer variable and variable is any integer variable.

2) rewind():This function rewin() is used to set the file pointer to the beginning of the file. Syntax: rewind(fp); where fp is file pointer variable.

Page 50: Unit-C (1)

Unit-C Programming in C Page 50

www.gkmvkalyan.blogspot.in

3) fseek(): It is used to make the file pointer in forward or backward directions based on the number of characters.

Syntax:

fseek(fp,pffset,origin);

Where

• fp is a file pointer. • Offset can take positive, negative or zero value and specifies the number of bytes to

be moved from the location specified by origin. • Origin can take one of the values as shown below:

SEEK_SET 0 Beginning of the file

SEEK_CURRENT 1 Current position

SEEK_END 2 End of the file

If the offset is positive, the file pointer fp moves forwards. If it is negative, the file pointer fp moves backwards.

Example(s):

• fseek(fp,0,0):file pointer fp moves to the beginning of the file. • fseek(fp,0,1):file pointer fp stays in the current position. • fseek(fp,0,2):file pointer fp moves to the end of the file. • fseek(fp,n,1):file pointer fp moves n bytes from the current position of the file

pointer. • fseek(fp,-n,1): file pointer fp moves n bytes backwards from the current pointer.

File status functions:

feof(): This function is used to detect whether end of file is reached or not.

Syntax: feof(fp);

It returns true, if end of file is detected, otherwise it returns false.

ferror():This function is used to detect an error that occurred during read or write operations on a file.

Syntax: ferror(fp); It returns true if an error is detected otherwise it returns false.