0% found this document useful (0 votes)
70 views62 pages

Character Arrays and Strings: Department of Computer Science and Engineering

Uploaded by

VINE TUBE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views62 pages

Character Arrays and Strings: Department of Computer Science and Engineering

Uploaded by

VINE TUBE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Department of Computer Science and Engineering

RV College of Engineering®, Bangalore


Programming in C

1. CHARACTER ARRAYS AND STRINGS

In C programming, array of characters are called strings. A string is terminated by null


character /0 . For example:

"c string tutorial"

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

1.1 Declaration and initializing Strings Variables

Strings are declared in C in similar manner as arrays. Only difference is that, strings are
of char type.

char s[5];

Strings can also be declared using pointer.

char *p

In C, string can be initialized in different number of ways.

char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};

DEPT. OF CSE 1
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

String can also be initialized using pointers

char *c="abcd";

1.2 Reading Strings from terminal


Reading words from user:
char c[20];
scanf("%s",c);

String variable c can only take a word. It is because when white space is encountered,
the scanf() function terminates.

Write a C program to illustrate how to read string from terminal.

#include<stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis.

Here, program will ignore Ritchie because, scanf() function takes only string before
the white space.

Reading String with spaces by using scanf


Note that –scanf with %s accepts only String which does not contain whitespaces
(blanks/space)

DEPT. OF CSE 2
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

It Reads wide verity of Characters including blank

Syntax :

scanf("%[\^n]", name );

Example :

void main()

char name[100];

printf("\nEnter the name : ");

scanf("%[\^n]s",name);

printf ("\nName of Student : %s ",name);

Output of this Block :

Enter the Name : RV CE

Name of Student : RV CE

Reading a line of text:

C program to read line of text manually.

#include<stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n')// terminates if user hit enter
{
ch=getchar();

DEPT. OF CSE 3
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

name[i]=ch;
i++;
}
name[i]='\0';// inserting null character at end
printf("Name: %s",name);
return0;
}

This process to take string is tedious. There are predefined functions gets() and puts() in
C language to read and display string respectively.

1.3 Writing Strings to screen

Using printf function:

Printf function can be used to print a string on to the terminal. For example:

printf("Name: %s",name);

We can also specify the precision with which the array is displayed. For example:

printf("Name: %10.4s",name);

The above line indicates that the first four characters are to be printed in a field width of
10 columns. So generalizing

printf("Name: %*.*s",w,d,name);

prints the first d characters of the string in the field width of w.

int main(){

char name[30];

printf("Enter name: ");

gets(name); //Function to read string from user.

printf("Name: ");

DEPT. OF CSE 4
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

puts(name); //Function to display string.

return 0;

Both, the above program has same output below:

Output

Enter name: Tom Hanks


Name: Tom Hanks

1.4 Arithmetic operations on characters


Characters in C can be used just like integers when used with arithmetic operators.
Whenever a character constant or character variable is used in an expression, it is
automatically converted into an integer value by the system. The integer value depends
on the local character set of the system.

Examples :

ASCII value of : ‘a’ is 97


ASCII value of : ‘z’ is 121

Possible Ways of Manipulation:

Way 1: Displays ASCII value[ Note that %d in Printf ]


char x = 'a';
printf("%d",x); // Display Result = 97
Way 2 : Displays Character value[ Note that %c in Printf ]
char x = 'a';
printf("%c",x); // Display Result = a
Way 3 : Displays Next ASCII value[ Note that %d in Printf ]
char x = 'a' + 1 ;

DEPT. OF CSE 5
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

printf("%d",x);
// Display Result = 98 ( ascii of 'b' )
Way 4 : Displays Next Character value[Note that %c in Printf ]
char x = 'a' + 1;
printf("%c",x); // Display Result = 'b'
Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ]
char x = 'z' - 'a';
printf("%d",x);
/* Display Result = 25
(difference between ASCII of z and a ) */
Way 6 : Displays Difference between 2 ASCII in Char [Note that %c in Printf ]
char x = 'z' - 'a';
printf("%c",x);
/* Display Result = ↓
( difference between ASCII of z and a ) */

Atoi Function :
 Atoi = A to I = Alphabet to Integer

 Convert String of number into Integer

Syntax:
num = atoi(String);
num - Integer Variable
String- String of Numbers

Example :
num = atoi("1947");
printf("%d",num);

DEPT. OF CSE 6
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Output :
1947

Significance :
1. Can Convert any String of Number into Integer Value that can Perform the
arithmetic Operations like integer

2. Header File : stdlib.h

Ways of Using Atoi Function :


Way 1 : Passing Variable in Atoi Function
// Variable marks is of Char Type

int num;
char marks[3] = "98";
num = atoi(marks);
printf("\nMarks : %d",num);

Way 2 : Passing Direct String in Atoi Function


int num;
num = atoi("98");
printf("\nMarks : %d",num);

Putting strings together

We cannot join two strings together by the simple arithmetic expression as follows:
string3=string1+string2
string2=string1+”hellow”
Are not valid in C programming.

DEPT. OF CSE 7
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

The process of combining two strings together is called as concatenation. This can be
done in two ways:

1. strcat() inbuilt function can be used


2. by manipulating character array indexes

Logic to concatenate two strings : Say str1[50] and str2[50] are two input string arrays
and str[100] will store concatenated string.

#include<stdio.h>
#include<string.h>
int main()
{
char str1[50] = {“VISWANATH”};
char str2[50]={“ANAND”};
char str[100];
int i=0,j=0;
/*copy str1 into str */
for(i=0;str1[i]!=’\0’;i++)
str[i]=str1[i];
/*end str1 with a space */
str[i]= ‘ ‘;
/*copy str2 into str */
for(j=0;str2[j]!=’\0’;j++)
str[i+j+1]=str2[j]; /*adding one to index because we have stored a space after
the first name */
str[i+j+1]='\0'; /*in the last location of character array store a null value to make it a string*/
printf("\n\nThe concatenated string is : ");
printf(“%s\n”,str);
}

Output of the program :


Enter first string : Lokesh is owner of
Enter second string : Ccodechamp
The concatenated string is : Lokesh is owner of Ccodechamp

Comparison of two strings:


C does not permit the comparison of two strings directly as follows:

DEPT. OF CSE 8
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

if(name1 == name2)
if(name == “ABC”)

It is necessary to compare two strings character by character. The comparison is done until there
is a mismatch or one of the strings terminates into a null character, whichever occurs first. The
following segment of the program illustrates this:
i=0;
while(str1[i] == str2[i] && str1[i] != ‘\0’ && str2[i] != ‘\0’)
i=i+1;
if(str1[i] != ‘\0’ && str2[i] != ‘\0’)
printf(“Strings are equal”);
else
printf(“Strings are not equal”);

1.5 String operations using String handling functions.

You can perform different type of string operations manually like: finding length of
string, concatenating (joining) two strings etc. But, for programmers ease, many library
functions are defined under header file <string.h> to handle these commonly used
tasks in C programming.

Strings are often needed to be manipulated by programmer according to the need of a


problem. All string manipulation can be done manually by the programmer but, this
makes programming complex and large. To solve this, the C supports a large number of
string handling functions.

There are numerous functions defined in "string.h" header file. Few commonly used
string handling functions are discussed below:

Function Work of Function

DEPT. OF CSE 9
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

Strings handling functions are defined under "string.h" header file, i.e, you have to
include the code below to run string handling functions.

#include <string.h>

gets() and puts()

Functions gets() and puts() are two string functions to take string input f rom user and
display string respectively as mentioned previously.

#include<stdio.h>
int main(){
char name[30];
printf("Enter name: ");
gets(name);//Function to read string from user.
printf("Name: ");
puts(name);//Function to display string.
return0;
}

Though, gets() and puts() function handle string, both these functions are defined in
"stdio.h" header file.

strlen():

DEPT. OF CSE 10
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

In C, strlen() function calculates the length of string. It takes only one argument, i.e, string name.

Syntax of strlen()
temp_variable = strlen(string_name);
Function strlen() returns the value of type integer.

Example of strlen()
#include <stdio.h>
#include <string.h>
int main(){
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
printf("Enter string: ");
gets(c);
printf("Length of string a=%d \n",strlen(a));
//calculates the length of string before null charcter.
printf("Length of string b=%d \n",strlen(b));
printf("Length of string c=%d \n",strlen(c));
return 0;
}

Output

DEPT. OF CSE 11
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Enter string: String


Length of string a=7
Length of string b=7
Length of string c=6

strcpy()
Function strcpy() copies the content of one character array to the content of another character
array. It takes two arguments as given in the syntax.
Syntax of strcpy()
strcpy(destination,source);
where destination and source are two character arrays.
Example of strcpy():
#include <stdio.h>
#include <string.h>
int main(){
char a[10],b[10];
printf("Enter string: ");
gets(a);
strcpy(b,a); //Content of string a is copied to string b.
printf("Copied string: ");
puts(b);
return 0;
}

Output
Enter string: Programming Tutorial
Copied string: Programming Tutorial

DEPT. OF CSE 12
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

strcmp()
In C programming, strcmp() compares two string and returns value 0, if the two strings are equal.
Function strcmp() takes two arguments, i.e, name of two string to compare.

Syntax of strcmp()
temp_varaible=strcmp(string1,string2);
string1 and string2 are character arrays
Example of strcmp()
#include <stdio.h>
#include <string.h>
int main(){
char str1[30],str2[30];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
return 0;
}

Output
Enter first string: Apple
Enter second string: Apple
Both strings are equal.

DEPT. OF CSE 13
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

If two strings are not equal, strcmp() returns positive value if ASCII value of first mismatching
element of first string is greater than that of second string and negative value if ASCII value of
first mismatching element of first string is less than that of second string. For example:
char str1[]="and",str2[]="cat";
temp=strcmp(str1,str2);
Since, ASCII value of 'a' is less than that of 'c', variable temp will be negative.

strcat()
In C programming, strcat() concatenates(joins) two strings. It takes two arguments, i.e, two
strings and resultant string is stored in the first string specified in the argument.

Syntax of strcat()
strcat(first_string,second_string);
first_string,second_string are character arrays.
Example of strcat()
#include <stdio.h>
#include <string.h>
int main(){
char str1[]="This is ", str2[]="programiz.com";
strcat(str1,str2); //concatenates str1 and str2 and resultant string is stored in str1.
puts(str1);
puts(str2);
return 0;
}

Output
This is programiz.com
programiz.com

Other String Functions:


The header file <string.h> contains many more string manipulation functions.

DEPT. OF CSE 14
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

strncpy:
strncpy copies only the left-most n characters of the source string to the target string variable.
This is a three variable function
strncpy(s1, s2, 5);

This statement copies the first 5 characters of the source string s2 to target string s1. Since the
first 5 characters may not include the null string at the end , we have to place it explicitly.
s1[6]=’\0’;

strncmp:
This is a three variable function
strncmp(s1, s2, n);
strncmp compares only the left-most n characters of s1 to s2 and returns.

1. 0 if they are equal


2. negative number if s1 is less than s2
3. positive number, otherwise

strncat:
This is a three variable function
strncat(s1, s2, n);
This call will concatenate the left most n characters of s2 to the end of s1.
example:
s1:
B A L A ‘\0’

s2:
G U R U ‘\0’

After strncat(s1,s2,4) execution:


s1:

DEPT. OF CSE 15
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

B A L A G U R U ‘\0’

strstr:
It is a two-parameter function that can be used to locate a sub-string in a string.
strstr(s1,s2); or
strstr(s1.”abc”);

The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes the
function returns the position of the first occurrence of the sub string.
We also have functions to determine the existence of a character in a string.
strchr(s1,’m’); locates the first occurrence of character ‘m’ in s1.
strrchr(s1,’m’); locates the last occurrence of character ‘m’ in s1.

EXAMPLE QUESTIONS
1. Write a C program to calculate Average Using Arrays.

Solution:
#include <stdio.h>
int main(){
int n, i;
float num[100], sum=0.0, average;
printf("Enter the numbers of data: ");
scanf("%d",&n);
while (n>100 || n<=0)
{
printf("Error! number should in range of (1 to 100).\n");
printf("Enter the number again: ");
scanf("%d",&n);

DEPT. OF CSE 16
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

}
for(i=0; i<n; ++i)
{
printf("%d. Enter number: ",i+1);
scanf("%f",&num[i]);
sum+=num[i];
}
average=sum/n;
printf("Average = %.2f",average);
return 0;
}

Output

Enter the numbers of data: 6


1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69

This program calculates the average if the number of data is from 1 to 100. If user enters value of
n above 100 or below 100 then, while loop is executed which asks user to enter value of n until it
is between 1 and 100.

2. Write a C program to Display Largest Element of an array

DEPT. OF CSE 17
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

#include <stdio.h>
int main(){
int i,n;
float arr[100];
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;++i) /* Stores number entered by user. */
{
printf("Enter Number %d: ",i+1);
scanf("%f",&arr[i]);
}
for(i=1;i<n;++i) /* Loop to store largest number to arr[0] */
{
if(arr[0]<arr[i]) /* Change < to > if you want to find smallest element*/
arr[0]=arr[i];
}
printf("Largest element = %.2f",arr[0]);
return 0;
}
Output

Enter total number of elements(1 to 100): 8

Enter Number 1: 23.4


Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5
This program takes n number of elements from user and stores it in array arr[]. To find the
largest element, the first two elements of array are checked and largest of these two element
is placed in arr[0]. Then, the first and third elements are checked and largest of these two
element is placed in arr[0]. This process continues until and first and last elements are
checked. After this process, the largest element of an array will be in arr[0] position.

DEPT. OF CSE 18
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

3. Write a C program to multiply to matrix in C programming

#include <stdio.h>
int main()
{
int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d",&r2, &c2);

/* If colum of first matrix in not equal to row of second matrix, asking user to enter the size
of matrix again. */
while (c1!=r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d",&r2, &c2);
}

/* Storing elements of first matrix. */


printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}

/* Storing elements of second matrix. */

DEPT. OF CSE 19
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

printf("\nEnter elements of matrix 2:\n");


for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1,j+1);
scanf("%d",&b[i][j]);
}

/* Initializing elements of matrix mult to 0.*/


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
mult[i][j]=0;
}

/* Multiplying matrix a and b and storing in array mult. */


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
mult[i][j]+=a[i][k]*b[k][j];
}

/* Displaying the multiplication of two matrix. */


printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ",mult[i][j]);
if(j==c2-1)
printf("\n\n");
}
return 0;
}
Output
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3

DEPT. OF CSE 20
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29

6 25
In this program, user is asked to enter the size of two matrix at first. The column of first
matrix should be equal to row of second matrix for multiplication. If this condition is not
satisfied then, the size of matrix is again asked using while loop. Then, user is asked to enter
two matrix and finally the output of two matrix is calculated and displayed.
This program is little bit larger and it is better to solve this program by passing it to a
function.

4. What will be the output when you execute the below statements:
#include<stdio.h>
void main()

DEPT. OF CSE 21
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

{
char arr[7]=”Network”;
printf(“%s”,arr);
}

Explanation:
Size of a character array should one greater than total number of characters in any string
which it stores. Inc every string has one terminating null character. This represents end of the
string.
So in the string “Network” , there are 8 characters and they are ‘N’,’e’,’t’,’w’,’o’,’r’,’k’ and
‘\0’. Size of array arr is seven. So array arr will store only first seven characters and it will
note store null character.
As we know %s in prinf statement prints stream of characters until it doesn’t get first null
character. Since array arr has not stored any null character so it will print garbage value.

5. What will be the output when you execute the below statements:
#include<stdio.h>
void main()
{
char arr[11]=”The African Queeen”;
printf(“%s”,arr);
}

Explanation:
Size of any character array cannot be less than the number of characters in any string which it
has assigned. Size of an array can be equal (excluding null character) or greater than but
never less than. So compilation error.

1.6 String operations without using String handling functions

A variety of operations can be performed on Strings. Therefore different modules are


created(with and without pointers) to perform the following different functions:

1.Substring:This function tells whether user entered string is a part of the original String.
Eg: The original string is:Codearea
The user entered string is:Code
Then above function will display the result as “String is a substring”

DEPT. OF CSE 22
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

2.Palindrome:If the user entered string and its reverse is same,then string is a palindrome.
Eg: LIRIL (‘This word is a palindrome because the word and its reverse is same).

3.Compare:This function allows the user to know whether the two entered strings are equal
or not
Eg: The first string is:Codearea
The second string is:Codearea
The above function will display the result as “Strings are same” ,as the two entered
string are equal

4.Copy:This function copies the second string over first string.


Eg:String 1:Code
String 2:Area
After performing above function String 1: becomes Area

5.Reverse:This function displays particular string in reverse order.


Eg:The original string:codearea
The result of above function will be:aeraedoc

/*Perform following operations with and without pointers to arrays(without using library
functions):a.substring, b.pallindrome, c.compare, d.copy, e.reverse.*/

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

void reverse(char str[20])


{
int i,j;
char temp;
j=0;
while(str[j]!=’\0')
{
j=j+1;
}
j=j-1;
i=0;
while(i<j)

DEPT. OF CSE 23
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j–;
}
printf(“\nReverse of string:%s”,str);
}

void palindrome(char str[20])


{
int i,j;
j=0;
while(str[j]!=’\0')
{
j=j+1;
}
j=j-1;
i=0;
while(i<j)
{
if(str[i]!=str[j])
{
printf(“\n\n%s is not a palindrome”,str);
return;
}
i++;
j–;
}
printf(“\n\n%s is palindrome”,str);
}

void copy(char str[20],char str1[20])


{
int i;
i=0;
while(str[i]!=’\0')

DEPT. OF CSE 24
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

{
str1[i]=str[i];
i++;
}
str1[i]=’\0';
printf(“\n\nCopied string is:%s”,str1);
}

int compare(char str1[20],char str2[20])


{
int i=0;
while(str1[i]!=’\0' && str2[i]!=’\0')
{
if(str1[i]!=str2[i])
{
break;
}
i=i+1;
}
return(str1[i]-str2[i]);
}
void substring(char str1[20],char str2[20])
{
int i,j,k;
k=0;
j=0;
while(str1[k]!=’\0' && str2[j]!=’\0')
{
i=k;
j=0;
while(str1[i]!=’\0' && str2[j]!=’\0')
{
if(str1[i]!=str2[j])
{
break;
}
i++;
j++;

DEPT. OF CSE 25
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

}
k=k+1;
}
if(str2[j]==’\0')
{
printf(“\n\nString is substring”);
}
else
{
printf(“\n\nString is not a substring”);
}
}

void reversept(char *fptr)


{
char temp,*lptr;
lptr=fptr;
while(*lptr!=’\0')
{
lptr++;
}
lptr–;
while(fptr<lptr)
{
temp=*fptr;
*fptr=*lptr;
*lptr=temp;
fptr++;
lptr–;
}

void palindromept(char *fptr)


{
char *lptr;
lptr=fptr;
while(*lptr!=’\0')

DEPT. OF CSE 26
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

{
lptr++;
}
lptr–;
while(fptr<lptr)
{
if(*fptr!=*lptr)
{
printf(“\n\nString is not a palindrome”);
return;
}
fptr++;
lptr–;
}
printf(“\n\nString is palindrome”);
}

void copypt(char *sptr,char *dptr)


{
while(*sptr!=’\0')
{
*dptr=*sptr;
sptr++;
dptr++;
}
*dptr=’\0';

int comparept(char *p1,char *p2)


{
while(*p1!=’\0' && *p2!=’\0')
{
if(*p1!=*p2)
{
break;
}
p1++;

DEPT. OF CSE 27
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

p2++;
}
return(*p1-*p2);
}
void substringpt(char *pstr1,char *pstr2)
{
char *p1,*p2;
p2=pstr2;
while(*pstr1!=’\0' && *p2!=’\0')
{
p1=pstr1;
p2=pstr2;
while(*p1!=’\0' && *p2!=’\0')
{
if(*p1!=*p2)
{
break;
}
p1++;
p2++;
}
pstr1++;
}
if(*p2==’\0')
{
printf(“\n\nString is substring.”);
}
else
{
printf(“\n\nString is not a substring.”);
}
}
void main()
{
int ch;
char string1[20],string2[20],string3[20];
clrscr();
printf(“\nenter string 1:”);

DEPT. OF CSE 28
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

flushall();
gets(string1);
printf(“\nenter string 2:”);
flushall();
gets(string2);
while(1)
{
printf(“\n1]substring without pointers\n2]palindrome without pointers\n3]compare without
pointers\n4]copy without pointers\n5]reverse without pointers”);
printf(“\n6]substring with pointers\n7]palindrome with pointers\n8]compare with
pointers\n9]copy with pointers\n10]reverse with pointers\n11]exit”);
printf(“\nenter your choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:substring(string1,string2);
break;
case 2:palindrome(string1);
break;
case 3:if(compare(string1,string2)==0)
{
printf(“\nstrings are same”);
}
else
{
printf(“\nstrings are not same”);
}

break;
case 4:copy(string1,string3);
break;
case 5:reverse(string1);
break;
case 6:substringpt(string1,string2);
break;
case 7:palindromept(string1);
break;
case 8:if(comparept(string1,string2)==0)

DEPT. OF CSE 29
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

{
printf(“\nstrings are same”);
}
else
{
printf(“\nstrings are not same”);
}

break;
case 9:copypt(string1,string3);
printf(“copied string is:%s”,string3);
break;
case 10:reversept(string1);
printf(“reverse of string:%s”,string1);
break;
case 11:exit(0);
}
}
}

DEPT. OF CSE 30
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

2. FUNCTIONS
2.1 Need for user defined functions
 Very often in computer programs there is some code that must be executed multiple times
in different places in the program.
 It is also common to need the same code in multiple different programs.

 Encapsulating frequently-used code into functions makes it easy to re-use the code in
different places and/or different programs.

 Separating code out into functions also allows the programmer to concentrate on different
parts of the overall problem independently of the others.

o In "top-down" programming a programmer first works on the overall algorithm of


the problem, and just assumes that functions will be available to handle individual
details.

o Functions can then be concentrated on independently of the greater context in


which they will be used.
 Well-written functions should be general enough to be used in a wide range of contexts,
not specific to a particular problem.

 Functions can be stored in libraries for later re-use. Examples of functions we have used
include log( ), sqrt( ), abs( ), cos( ), etc.

Introduction
A function is a block of code that performs a particular task. There are times when we need to
write a particular block of code for more than once in our program. This may lead to bugs and
irritation for the programmer. C language provides an approach in which you need to declare and

DEPT. OF CSE 31
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

define a group of statements once and that can be called and used whenever required. This saves
both time and space.
C functions can be classified into two categories,

 Library functions
 User-defined functions
Library functions are those functions which are defined by C library, example printf(),
scanf(), strcat() etc. You just need to include appropriate header files to use these functions.
These are already declared and defined in C libraries.

User-defined functions are those functions which are defined by the user at the time of writing
program. Functions are made for code reusability and for saving time and space.

C Standard Library Functions


C Standard library functions or simply C Library functions are inbuilt functions in C
programming. Function prototype and data definitions of these functions are written in their
respective header file. For example: If you want to use printf() function, the header
file <stdio.h> should be included.
#include <stdio.h>
int main()
{
/* If you write printf() statement without including header file, this program will show error. */
printf("Hello.");
}

There is at least one function in any C program, i.e., the main() function (which is also a library
function). This program is called at program starts.

There are many library functions available in C programming to help the programmer to write a
good efficient program.

Suppose, you want to find the square root of a number. You can write your own piece of code to
find square root but, this process is time consuming and the code you have written may not be

DEPT. OF CSE 32
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

the most efficient process to find square root. But, in C programming you can find the square
root by just using sqrt() function which is defined under header file "math.h"

Use Of Library Function To Find Square root


#include <stdio.h>
#include <math.h>
int main(){
float num,root;
printf("Enter a number to find square root.");
scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in root. */
printf("Square root of %.2f=%.2f",num,root);
return 0;
}
List of Standard Library Functions Under Different Header Files in C Programming

C Header Files

<ctype.h>

<math.h>

<stdio.h>

<stdlib.h>

<string.h>

<time.h>

User defined function

DEPT. OF CSE 33
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

C allows programmer to define their own function according to their requirement. These types of
functions are known as user-defined functions. Suppose, a programmer wants to find factorial of
a number and check whether it is prime or not in same program. Then, he/she can create two
separate user-defined functions in that program: one for finding factorial and other for checking
whether it is prime or not.
#include <stdio.h>
void function_name(){
................
................
}

int main(){
...........
...........
function_name();
...........
...........
}

As mentioned earlier, every C program begins from main() and program starts executing the
codes inside main() function. When the control of program reaches
to function_name() inside main()function. The control of program jumps to void
function_name() and executes the codes inside it. When all the codes inside that user-defined
function are executed, control of the program jumps to the statement just
after function_name() from where it is called. Analyze the figure below for understanding the
concept of function in C programming. The function name is an identifier and should be unique.

DEPT. OF CSE 34
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Advantages of user defined functions


1. User defined functions helps to decompose the large program into small segments which
makes programmer easy to understand, maintain and debug.

2. If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.

3. Programmer working on large project can divide the workload by making different
functions.

A multi-function program:
A function is self-contained block of code that performs a particular task. Once a function has
been designed and packed, it can be treated as a ‘black box’ that takes some data from the main
program and returns a value. Thus a program, which has been written using a number of
functions, is treated as a multi-function program.

Example of user-defined function

Write a C program to add two integers. Make a function add to add integers and display
sum in main() function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;

DEPT. OF CSE 35
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

printf("Enters two number to add\n");


scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}

1.3 Elements of user defined functions


The three elements that are related to functions are:
1. Function definition
2. Function call
3. Function declaration

Definition of functions:
A function definition, also known as function implementation shall include the following
elements:
1. Function name
2. Function type

DEPT. OF CSE 36
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

3. List of parameters
4. Local variable declarations
5. Function statements and
6. A return statement
All the six elements are grouped into two parts, namely;

 Function header ( First three elements) and

 Function body (Second three elements).

Syntax and Components


The general syntax of a function is as follows:

function_type function_name( parameter list )


{
Local variable declaration;
executable statement1;
executable statement2;
.
.
.
return statement;
}
 Example:
int add( int a, int b ) {
int sum;
sum = a + b;
return sum;

DEPT. OF CSE 37
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Function Type
 The "funtion type" indicates what kind of data this function will return. In the example
above,the function returns an int.

 Some languages differentiate between "subroutines", which do not return a value,


and "functions", which do. In C there are no subroutines, only functions, but functions
are not required to return a value. The correct way to indicate that a function does not
return a value is to use the return type "void". ( This is a way of explicitly saying that the
function returns nothing. )

 If no return type is given, the compiler will normally assume the function returns an int.
This can cause problems if the function does not in fact return an int.

Function Name
 The function name is an identifier by which this function will be known, and obeys the
same naming rules as applied to variable names ( Alphanumeric characters, beginning
with alpha, maximum 31 significant characters, etc. )

Formal Parameter List


 Following the function name are a pair of parentheses containing a list of the formal
parameters, (arguments) which receive the data passed to the function.

 The ANSI standard requires that the type of each formal parameter to be listed
individually within the parentheses as shown in the above example. Even if several
parameters are of the same type, each must have its type given explicitly.
 If a function takes no parameters, the parameters may be left empty. The compiler will
not perform any type checking on function calls in this case. A better approach is to
include the keyword "void" within the parentheses, to explicitly state that the function
takes no parameters.

Function Body
 The body of the function is enclosed within curly {} braces, just as the "main" function
with which we have been dealing so far, and contains the instructions that will be
executed when this function is called.

 The function body starts by declaring all local variables, prior to any executable
statements.

DEPT. OF CSE 38
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

o In C99 variables can be declared any time before they are used, but in general it is
still best to declare all variables that will be used at the beginning of the function,
or at the beginning of the block in which they are used for very local variables. (
See scope below. )
o There are actually two schools of thought on this issue:

o Declaring all variables at the top of the function puts them all together, in one
comprehensive list. If you print out the program, then all the variables will print
on the same page, making a sort of "checklist" of variables to be taken care of.

o If you only work on the computer, and never from printouts, it can be difficult to
continuously scroll back and forth between the variable declarations at the
beginning of the function and the part of the program you are working on.
Declaring the variables just before you use them keeps the declaration and use on
the same screen without scrolling.

o ( As a compromise, you can declare the variables just before use while working
on the program, and then move them all up to the top of the function after the
program is running.

1.4 Return values and their types


The Return Statement
 The return statement exits the called function and returns control back to the calling
function.

o Once a return statement is executed, no further instructions within the function are
executed.
 A single return value ( of the appropriate type ) may be returned.
o Parentheses are allowed but not required around the return value.

o A function with a void return type will not have a return value after the return
statement.
 More than one return statement may appear in a function, but only one will ever be
executed by any given function call.
o ( All returns other than the last need to be controlled by logic such as "if" blocks. )

DEPT. OF CSE 39
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

 If a function does not contain a return statement, most compilers will add one
automatically at the end of the routine, and may generate a warning message. The return
value, if any, is undefined in this case.

 "main( )" is technically a function, and should return 0 upon successful completion, or a
non-zero value otherwise. This is ignored by many programmers, but some compilers
will issue warning messages if main() does not contain a return statement.

1.5 Function calls


 A function is called by using the function name, followed by a set of parentheses
containing the data to be passed to the function.

 The data passed to the function are referred to as the "actual" parameters. The variables
within the function which receive the passed data are referred to as the "formal"
parameters.
 The formal parameters are local variables, which exist during the execution of the
function only, and are only known by the called function. They are initialized when the
function starts by copies of the data passed as actual parameters. This mechanism,
known as "pass by value", ensures that the called function can not directly change the
values of the calling functions variables. ( Exceptions to this will be discussed later. )
 To call a function which takes no arguments, use an empty pair of parentheses.
 Example: total = add( 5, 3 );

 VERY IMPORTANT: It is crucial that the number and types of actual parameters
passed match with the number and types of parameters expected by the functions formal
parameter list. ( If the number of arguments matches but the data types do not, then the
compiler MAY insert some type conversion code if the correct data types are known, but
it is safer not to rely on this. )

 NOTE CAREFULLY: The actual parameters passed by the calling program and the
formal parameters used to receive the values in the called function will often have the
same variable names. However it is very important to recognize that they are totally
different independent variables ( because they exist in different scopes, see below ),
whether they happen to have the same name or not.

o Example: In the code below, the variables x, y, z, and x again in main are used to
initialize the variables x, z, b, and c in the function. The fact that x and z appear in
both main and the function is irrelevant - They are independent variables with
independent values.

DEPT. OF CSE 40
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

void func( double x, double z, double b, double c );

int main( void ) {

double x( 1.0 ), y( 2.0 ), z( 3.0 );

func( x, y, z, x );

o The call to the function above initializes the function parameters equivalently to
the following assignment statements:
 x in func = x in main
 z in func = y in main
 b in func = z in main
 c in func = x in main

1.6 Function declaration, Category of functions


Function declaration
 When the compiler processes a call to a function, it will check to see that the correct
number and types of data items are being passed to the function, and will automatically
generate type conversions as necessary. This is known as type checking.

 Type checking is only possible if the compiler already knows about the function,
including what kind of data the function is expecting to receive. Otherwise, the compiler
has to make assumptions, which can lead to incorrect and erratic behavior if those
assumptions are not correct.

 One way of dealing with this situation is to make certain that all functions appear earlier
in a file than any calls to them. This works for simple cases, but can make large complex
programs hard to follow, and does not work in the cases of ( mutually ) recursive
functions and functions located in separate files or libraries.
 A better approach is to use function prototypes. This is a way of declaring to the
compiler what data a function will require, without actually providing the function itself.

DEPT. OF CSE 41
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

 Examples:
int add( int a, int b );
int add( int, int );
 Note that the function prototypes end with semicolons, indicating that this is not a
function, but merely a prototype of a function to be provided elsewhere.

 Note also that the variable names are not required in the function prototype. They may
be included for clarity if you wish, but the compiler will ignore them. This also means
that the variable names used in the function prototype do not need to match those used in
the actual function itself.

 For clarity it is generally good style to list all functions that will be used by prototypes at
the beginning of the file. Then provide main( ) as the first full function definition,
followed by each of the other functions in the order in which the prototypes are listed. (
I.e. the prototype list acts as a kind of table of contents for the actual function which
appear after main. )

 Function prototypes are often placed in separate header files, which are then included in
the routines which need them. For example, "math.h" includes the function prototypes
for the C math functions sqrt( ) and cos( ).
 Exercise: Write function prototypes for:
1. A function which takes an int and a float, and returns a double.
 Answer: double myfunction( int, float );
2. A function which takes no arguments and returns no value.
 Answer: void

Category of functions:
No arguments and no return values
/*C program to check whether a number entered by user is prime or not using function with no
arguments and no return value*/
#include <stdio.h>
void prime();
int main(){

DEPT. OF CSE 42
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

prime(); //No argument is passed to prime().


return 0;
}
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is void */
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}

Arguments but no return values


/*Program to check whether a number entered by user is prime or not using function with
arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main(){
int num;

DEPT. OF CSE 43
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

printf("Enter positive enter to check:\n");


scanf("%d",&num);
check_display(num); /* Argument num is passed to function. */
return 0;
}
void check_display(int n){
/* There is no return value to calling function. Hence, return type of function is void. */
int i, flag = 0;
for(i=2; i<=n/2; ++i){
if(n%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",n);
else
printf("%d is prime", n);
}

Arguments with return values


/* Program to check whether a number entered by user is prime or not using function with
argument and return value */
#include <stdio.h>
int check(int n);
int main(){

DEPT. OF CSE 44
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

int num,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num); /* Argument num is passed to check() function. */
if(num_check==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
return 0;
}
int check(int n){
/* Integer value is returned from function check() */
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return 1;
}
return 0;
}

No argument but returns a value


/*C program to check whether a number entered by user is prime or not using function with no
arguments but having return value */
#include <stdio.h>
int input();
int main(){

DEPT. OF CSE 45
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

int num,i,flag = 0;
num=input(); /* No argument is passed to input() */
for(i=2; i<=num/2; ++i){
if(num%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",num);
else
printf("%d is prime", num);
return 0;
}
int input(){ /* Integer value is returned from input() to calling function */
int n;
printf("Enter positive integer to check:\n");
scanf("%d",&n);
return n;
}

Function that return multiple values


Call by Reference
In this we pass the address of the variable as arguments. In this case the formal parameter can be
taken as a reference or a pointer, in both the case they will change the values of the original
variable.

DEPT. OF CSE 46
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

void calc(int *p);


int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}

void calc(int *p)


{
*p = *p + 10;
}
Output : 20

1.7 Nesting of functions


Function calling one or more functions is called nesting of function.
#include <stdio.h>
void italy();
void brazil();
void argentina();

int main()
{
printf("I am in main\n");
italy();
printf("I am finally back in main\n");

DEPT. OF CSE 47
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

return 0;
}

void italy(){
printf("I am in italy\n");
brazil();
printf("I am back in italy\n");
}

void brazil(){
printf("I am in brazil\n");
argentina();
}
void argentina(){
printf("I am in argentina\n");
}

1.8 Functions with arrays


Passing One-dimensional Array In Function
Single element of an array can be passed in similar manner as passing variable to a function.
C program to pass a single element of an array to function
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()

DEPT. OF CSE 48
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2] only.
return 0;
}
Output
4

Passing an entire one-dimensional array to a function


While passing arrays as arguments to the function, only the name of the array is passed (,i.e,
starting address of memory area is passed as argument).
C program to pass an array containing age of person to a function. This function should find
average age and display the average age in main function.

#include <stdio.h>
float average(float age[]);

int main()?
{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}

float average(float age[])


{

DEPT. OF CSE 49
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i) {
sum += age[i];
}
avg = (sum / 6);
return avg;
}

Output
Average age=27.08

Passing Multi-dimensional Arrays to Function


To pass two-dimensional array to a function as an argument, starting address of memory area
reserved is passed as in one dimensional array
#Example: Pass two-dimensional arrays to a function

#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
// passing multi-dimensional array to displayNumbers function

DEPT. OF CSE 50
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2])
{
// Instead of the above line,
// void displayNumbers(int num[][2]) is also valid
int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

1.9 Storage Class

DEPT. OF CSE 51
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

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:
1. automatic
2. external
3. static
4. register

Automatic storage class


Keyword for automatic variable

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

External storage class


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

In case of large program, containing more than one file, if the global variable is declared in file 1
and that variable is used in file 2 then, compiler will show error. To solve this problem,
keyword extern is used in file 2 to indicate that, the variable specified is global variable and
declared in another file.
Example to demonstrate working of external variable

#include
void Check();
int a=5;

DEPT. OF CSE 52
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

/* a is global variable because it is outside every function */


int main(){
a+=4;
Check();
return 0;
}

void Check(){
++a;

/* ----- Variable a is not declared in this function but, works in any function as they are global
variable ------- */
printf("a=%d\n",a);
}

Output
a=10

Register Storage Class


Keyword to declare register variable

register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.

If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory. Value stored in register are much faster than that of memory.

In case of larger program, variables that are used in loops and function parameters are declared
register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in
register, it will automatically store it in memory.

DEPT. OF CSE 53
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Static Storage Class


The value of static variable persists until the end of the program. A variable can be declared
static using keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=5;
}

Output
0 5 10

During first function call, it will display 0. Then, during second function call, variable c will not
be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10
in third call.
If variable c had been automatic variable, the output would have been:
 0 0

Scope, Lifetime and Visibility in C

DEPT. OF CSE 54
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

Whenever you declare a variable, you determine its scope, lifetime and visibility. These three are
important concepts associated with any variable declared in C. Understanding the difference
between them, and how they are related to each other, will help avoid mistakes in writing code.

Scope
Scope is defined as the area in which the declared variable is ‘available’. There are five scopes in
C: program, file, function, block, and prototype. Let us examine a dummy program to understand
the difference (the comments indicate the scope of the specific variable):
void foo() {}
// "foo" has program scope
static void bar() {
// "bar" has file scope
printf("hello world");
int i;
// "i" has block scope
}
void baz(int j);
// "j" has prototype scope
print:
// "print" has function scope

The foo function has program scope. All non-static functions have program scope, and they can
be called from anywhere in the program. Of course, to make such a call, the function needs to be
first declared using extern, before being called, but the point is that it is available throughout the
program.

The function bar has file scope — it can be called from only within the file in which it is
declared. It cannot be called from other files, unlike foo, which could be called after providing
the external declaration of foo.

The label print has function scope. Remember that labels are used as a target for jumps using
goto in C. There can be only one print label inside a function, and you can write a goto

DEPT. OF CSE 55
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

printstatement anywhere in the function, even before the label appears in the function. Only
labels can have function scope in C.

The variable i has block scope, though declared at the same level/block as print. Why is that so?
The answer is, we can define another variable with the same name i inside another block within
the bar function, whereas it is not possible for print, since it is a label.

The variable j has prototype scope: you cannot declare any other parameter with the same
name j in the function baz. Note that the scope of j ends with the prototype declaration: you can
define the function baz with the first argument with any name other than j.

Lifetime
The lifetime of a variable is the period of time in which the variable is allocated a space (i.e., the
period of time for which it “lives”). There are three lifetimes in C: static, automatic and dynamic.
Let us look at an example:
int foo() {
static int count = 0;
// "count" has static lifetime
int * counter = malloc(sizeof(int));
// "counter" has automatic lifetime
free(counter);
// malloc’ed memory has dynamic lifetime
}

In this code, the variable count has a static lifetime, i.e., its lifetime is that of the program. The
variable counter has an automatic lifetime — its life is till the function returns; it points to a
heap-allocated memory block — its life remains till it is explicitly deleted by the program, which
is not predictable, and hence it has a dynamic lifetime.

Visibility
Visibility is the “accessibility” of the variable declared. It is the result of hiding a variable in
outer scopes. Here is a dummy example:
int i;
// the "i" variable is accessible/visible here

DEPT. OF CSE 56
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

void foo() {
int i;
// the outer "i" variable
// is not accessible/visible here
{
int i;
// two "i" variables at outer scopes
// are not accessible/visible here
}
// the "i" in this block is accessible/visible
// here and it still hides the outer "i"
}
// the outermost "i" variable
//is accessible/visible here

Summary of differences
As you can see, scope, lifetime and visibility are related to each other, but are distinct. Scope is
about the ‘availability’ of the declared variable: within the same scope, it is not possible to
declare/define two variables of the same type with the same name. Lifetime is about the duration
in which the variable is ‘alive': it determines how long the named or unnamed variable has
memory allocated to it.

Visibility is about the ‘accessibility’ of the declared variables: it arises because of the possibility
of variables in outer scope having the same name as the ones in inner scopes, resulting in
‘hiding’.

Example Questions
1. /* C programming source code to convert either binary to decimal or decimal to binary
according to data entered by user. */

DEPT. OF CSE 57
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

#include <stdio.h>
#include <math.h>
int binary_decimal(int n);
int decimal_binary(int n);
int main()
{
int n;
char c;
printf("Instructions:\n");
printf("1. Enter alphabet 'd' to convert binary to decimal.\n");
printf("2. Enter alphabet 'b' to convert decimal to binary.\n");
scanf("%c",&c);
if (c =='d' || c == 'D')
{
printf("Enter a binary number: ");
scanf("%d", &n);
printf("%d in binary = %d in decimal", n, binary_decimal(n));
}
if (c =='b' || c == 'B')
{
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("%d in decimal = %d in binary", n, decimal_binary(n));
}
return 0;

DEPT. OF CSE 58
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

int decimal_binary(int n) /* Function to convert decimal to binary.*/


{
int rem, i=1, binary=0;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}

int binary_decimal(int n) /* Function to convert binary to decimal.*/

{
int decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(2,i);
++i;

DEPT. OF CSE 59
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

}
return decimal;
}

Output

Instructions:
1. Enter alphabet 'd' to convert binary to decimal.
2. Enter alphabet 'b' to convert decimal to binary.
d
Enter a binary number: 110111
110111 in binary = 55 in decimal

2. With using User-defined Function Write a Program to Find Length of String


#include<stdio.h>
// Prototype Declaration
int FindLength(char str[]);
int main() {
char str[100];
int length;
printf("\nEnter the String : ");
gets(str);
length = FindLength(str);
printf("\nLength of the String is : %d", length);
return(0);
}
int FindLength(char str[]) {

DEPT. OF CSE 60
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

int len = 0;
while (str[len] != '\0')
len++;
return (len);
}

DEPT. OF CSE 61
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C

DEPT. OF CSE 62

You might also like