Character Arrays and Strings: Department of Computer Science and Engineering
Character Arrays and Strings: Department of Computer Science and Engineering
Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null
character at the end of string.
Strings are declared in C in similar manner as arrays. Only difference is that, strings are
of char type.
char s[5];
char *p
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
char *c="abcd";
String variable c can only take a word. It is because when white space is encountered,
the scanf() function terminates.
#include<stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return0;
}
Output
Here, program will ignore Ritchie because, scanf() function takes only string before
the white space.
DEPT. OF CSE 2
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
Syntax :
scanf("%[\^n]", name );
Example :
void main()
char name[100];
scanf("%[\^n]s",name);
Name of Student : RV CE
#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.
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);
int main(){
char name[30];
printf("Name: ");
DEPT. OF CSE 4
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
return 0;
Output
Examples :
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
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
int num;
char marks[3] = "98";
num = atoi(marks);
printf("\nMarks : %d",num);
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:
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);
}
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”);
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.
There are numerous functions defined in "string.h" header file. Few commonly used
string handling functions are discussed below:
DEPT. OF CSE 9
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
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>
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
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
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.
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’
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
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.
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
DEPT. OF CSE 18
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
#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);
}
DEPT. OF CSE 19
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
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.
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.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
/*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>
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);
}
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);
}
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”);
}
}
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”);
}
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.
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.
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"
C Header Files
<ctype.h>
<math.h>
<stdio.h>
<stdlib.h>
<string.h>
<time.h>
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
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.
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
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;
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.
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. )
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.
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.
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
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
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
DEPT. OF CSE 43
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
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;
}
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;
}
DEPT. OF CSE 46
Department of Computer Science and Engineering
RV College of Engineering®, Bangalore
Programming in C
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");
}
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
#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;
}
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
#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
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
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.
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
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
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
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
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=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
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