Unit3 Pps

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 90

Unit-III

String Basics - String Declaration and Initialization - String Functions: gets(), puts(),
getchar(),putchar(), printf() - Built-inString Functions: atoi, strlen, strcat, strcmp -
String Functions: sprint, sscanf, strrev, strcpy, strstr, strtok - Operations on Strings -
Function prototype declaration, function definition - Actual and formal parameters -
Function with and without Arguments - Function with and without return values -
Call by Value, Call by Reference - Passing Array to Function - Passing Array
elements to Function - Function Pointers.
STRING BASICS

Strings in C are represented by arrays of characters.

String is nothing but the collection of the individual array


elements or characters stored at contiguous memory
locations

i) Character array – 'P','P','S'

i) Double quotes – “PPS” is a example of String.

−If string contains the double quote as part of string


then we can use escape character to keep double quote
as a part of string.
− “PP\S” is a example of String
iii) Null Character
− The end of the string is marked with a special
character, the null character, which is a character all of whose
bits are zero i.e., a NULL.
− String always Terminated with NULL Character (‘/0′)
char name[10] = {'P','P','S','\0'}

NULL Character is having ASCII value 0

ASCII Value of '\0' = 0

As String is nothing but an array , so it is Possible
to Access Individual Character
name[10] = "PPS";
− It is possible to access individual character
name[0] = 'P';
name[1] = 'P';
name[2] = 'S';
7
iv) MEMORY:

Each Character Occupy 1 byte of Memory

Size of "PPS" = Size of 'P' +


= Size of 'P' +
= Size of 'S’ ;
Size of "PPS” is 3
BYTES

Address
Eachof 'P' = 2000
Character is storedofin 'P' = 2001
Address
consecutive memory
Address of 'S' = 2002
location.

9
STRING DECLARATION AND INITIALIZATION


String Declaration:

−String data type is not supported in C Programming. String


means Collection of Characters to form particular word. String
is useful whenever we accept name of the person, Address of
the person, some descriptive information. We cannot declare
string using String Data Type, instead of we use array of type
character to create String.
− Character Array is Called as ‘String’.
− Character Array is Declared Before Using it in Program.
char String_Variable_name [ SIZE ] ;
Eg: char city[30];
11
Point Explanation

Significance - We have declared array of character[i.e String]

Size of string - 30 Bytes

Bound - C Does not Support Bound Checking i.e if we store City


checking with size greater than 30 then C will not give you any
error
Data type - char

Maximum size - 30

13
#include Outpu
<stdio.h> int t
main() H

{
char greetings[] = "Hello
World!"; printf("%c",
greetings[0]);
return 0;
}
#include Outpu
t
<stdio.h> Jello
int main() { World!
char greetings[] = "Hello
World!"; greetings[0] = 'J';
printf("%s",
greetings); return
0;
} 15
Precautions to be taken while declaring Character Variable :


String / Character Array Variable name should be legal C
Identifier.

String Variable must have Size specified.
− char city[];

Above Statement will cause compile time error.
− Do not use String as data type because String data type
is included in later languages such as C++ / Java. C
does not support String data type
− String city;

When you are using string for other purpose than accepting and
printing data then you must include following header file in
your
code –
− #include<string.h>
17
2. INITIALIZING STRING [CHARACTER ARRAY] :


Whenever we declare a String then it will contain garbage
values inside it. We have to initialize String or Character
array before using it. Process of Assigning some legal
default data to String is Called Initialization of String.


There are different ways of initializing String in C
Programming –
❑ Initializing Unsized Array of character
❑ InitializingString Directly
❑ InitializingString Using Character Pointer

19
WAY 1 : UNSIZED ARRAY AND CHARACTER


Unsized Array :Array Length is not specified while
initializing character array using this approach

Array length is automatically calculated by Compiler

Individual characters are written inside single quotes ,
separated by comma to form a list of characters.
complete list is wrapped inside Pair of Curly braces


NULL Character should be written in the list because it
is ending or terminating character in the String/Character
Array

char name [] = {'P','P','S','\0'};
21
WAY 2 : DIRECTLY INITIALIZE STRING VARIABLE


In this method we are directly assigning String to variable
by writing text in double quotes.


In this type of initialization , we don’t need to put NULL
or Ending / Terminating character at the end of string. It
is appended automatically by the compiler.


char name [ ] = "PPS";

23
WAY 3 : CHARACTER POINTER VARIABLE


Declare Character variable of pointer type so that it
can hold the base address of “String”


Base address means address of first array element
i.e (address of name[0] )


NULL Character is appended
Automatically char *name = "PPS";

25
STRING FUNCTIONS
− puts( ) − strcmp( )
− gets( ) − sprintf( )
− getchar( ) − sscanf( )
− − strrev( )
putchar( )
− printf( ) − strcpy( )
− atoi( ) − strstr()
− strlen( ) − strtok()
− strcat ( )

27
GETS():
SYNTAX FOR ACCEPTING STRING :
char * gets ( char * str ); OR
gets( <variable-name> )

Example :
#include<stdio.h>
void main()
{
char name[20]; printf("\
nEnter the Name : ");
gets(name);
}

29
❑ Whenever gets() statement encounters then characters entered by user
(the string with spaces) will be copied into the variable.
❑ If user start accepting characters , and if new line character appears
then the newline character will not be copied into the
string variable(i.e name).
❑ A terminating null character is automatically appended after the
characters copied to string variable (i.e name)
❑ gets() uses stdin (Standard Input Output) as source, but it does not
include the ending newline character in the resulting string and does
not allow to specify a maximum size for string variable (which can
lead to buffer overflows).

31
Some Rules and Facts :
A. %s is not Required :

Like scanf statement %s is not necessary


while accepting string.
scanf("%s",name);

gets() syntax which is simpler than scanf() –


gets(name);
Sample Input Accepted by Above Statement :


Value Accepted : Problem solving\n

Value Stored : Problem (\n Neglected)
solving

33
B. Spaces are allowed in gets() :
gets(name);
Whenever the above line encounters then interrupt will wait
for user to enter some text on the screen. When user starts
typing the characters then all characters will be copied to
string and when user enters newline character then process of
accepting string will be stopped.

35
2. PUTS():
Way 1 :Messaging

puts(" Type your Message / Instruction ");

Like Printf Statement puts() can be used to display message.
Way 2 : Display String

puts(string_Variable_name) ;
Notes or Facts :

puts is included in header file “stdio.h”

As name suggest it used for Printing or Displaying Messages
or Instructions.
37
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
char string[] =
"This is an
example string\
n";
puts(string); //
String is variable
Here
puts("String"; //
String is in
Double Quotes
getch(); 39
}
GETCHAR():

Getchar() function is also one of the function which is
used to accept the single character from the user.


The characters accepted by getchar() are buffered until
RETURN is hit means getchar() does not see the
characters until the user presses return. (i.e Enter Key)

Syntax for Accepting String and Working :


/* getchar accepts character & stores in ch */
char ch = getchar();

41

When control is on above line then getchar() function will accept
the single character.

After accepting character control remains on the same line.

When user presses the enter key then getchar() function will read
the character and that character is assigned to the variable ‘ch’.

Parameter Explanation

Header File - stdio.h


Return Type - int (ASCII Value of the character)
Parameter - Void
Use - Accepting the Character

43
EXAMPLE 1 :
IN THE FOLLOWING EXAMPLE WE ARE JUST ACCEPTING THE
SINGLE CHARACTER AND PRINTING IT ON THE CONSOLE –
main()
Output :
{ rukcdnhjmjcghkcg
char ch; Accepted Character : r
ch = getchar();
printf("Accepted Character : %c",ch);
}

45
EXAMPLE 2 : ACCEPTING STRING (USE ONE OF THE
LOOP)
#include<stdio.h>
void main()
{
int i = 0;
char name[20]; printf("\
nEnter the Name : ");
while((name[i]=getchar())!='\n’)
i++ ;/*while loop will accept
the
one character at a time and
check it with newline character.
Whenever user enters newline
character then control comes
out of the loop.*/
} 47
PUTCHAR():

Displaying String in C Programming


Syntax : int putchar(char c);

Way 1 : Taking Character as Parameter


putchar('a') ; // Displays a


Individual Character is Given as
parameter to this function.

We have to explicitly mention
Character.

49
Way 2 : Taking Variable as Parameter
putchar(a);
// Display Character Stored in ‘a’

Input Parameter is Variable of Type “Character”.

This type of putchar() displays character stored in variable.

Way3:Displaying Particular Character from Array


putchar(a[0]) ;
// Display a[0]th element from array

Character Array or String consists of collection of characters.

Like accessing individual array element , characters can be
displayed one by one using putchar().

51
Example: Output:
#include<stdio.h> C programming
int main()
{
char string[] = "C programming\n";
int i=0;
while(string[i]!='\0')
{
putchar(string[i]);
i++;
}
return 0;
}

53
PRINTF():
Syntax :

Way 1 : Messaging printf (" Type your Message / Instruction " ) ;


Way 2 : Display String printf ("Name of Person is %s ", name ) ;

Notes or Facts :
printf is included in header file “stdio.h”
As name suggest it used for Printing or Displaying Messages or

Instructions Uses :

Printing Message

Ask user for entering the data ( Labels . Instructions )

Printing Results

55
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
Output :
Example : Value : 100
char a[10] = "100";
int value = atoi(a);
printf("Value = %d\n", value);
return 0;

57
SIGNIFICANCE :

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

Header File : stdlib.h

Ways of Using Atoi Function :

Way 1 : Passing Variable in Atoi Function


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

59
OTHER INBUILT TYPECAST FUNCTIONS IN C PROGRAMMING
LANGUAGE:

Typecasting functions in C language performs data type
conversion from one type to another.


Some other functions are given below

atof() Converts string to float

atoi() Converts string to int

atol() Converts string to long

itoa() Converts int to string

ltoa() Converts long to string

61
STRLEN FUNCTION: Finding length of string

Point Explanation
No of Parameters - 1
Parameter Taken - Character Array Or String
Return Type - Integer
Description - Compute the Length of the String
Header file - string.h

63
Different Ways of Using strlen() :

There are different ways of using strlen function. We can pass
different parameters to strlen() function.

Way 1 : Taking String Variable as Parameter


char str[20];
int length ;
printf("\nEnter the String : ");
gets(str);
length = strlen(str);
printf("\nLength of String : %d ", length);
Output:
Enter the String : hello
Length of String : 5

65
67
Way 2 : Taking String Variable which is Already Initialized using Pointer
char *str = "priteshtaral";
int length ;
length = strlen(str);
printf("\nLength of String : %d ", length);

Way 3 : Taking Direct String


int length ;
length = strlen("pritesh"); printf("\
nLength of String : %d",length);

Way 4 : Writing Function in printf Statement


char *str = "pritesh";
printf("\nLength of String : %d", strlen(str));

69
STRCAT FUNCTION:
Function takes 2 Strings / Character Array as Parameter

Appends second string at the end of First String.
Parameter Taken - 2 Character Arrays / Strings
Return Type - Character Array /
String


Syntax :

char* strcat ( char * s1, char *


s2);

71
Ways of Using Strcat Function :
Way 1 : Taking String Variable as Parameter
char str1[20] = “Don” ;str2[20] = “Bosqo”;
strcat(str1,str2);
puts(str1);

Way 2 : Taking String Variable which is Already Initialized using Pointer


char *str1 = “Ind”,*str2 = “ia”;
strcat(str1,str2); Result :
puts(str1); India

Way 3 : Writing Function in printf Statement


printf(“String:%s“, strcat(“Ind”,”ia”));

73
STRCMP FUNCTION:


Function takes two Strings as parameter.

It returns integer .

Syntax : int strcmp ( char *s1, char *s2 ) ;

Return Type Condition


-ve Value - String1 < String2
+ve Value - String1 > String2
0 Value - String1 = String2

75
1.It starts with comparing the ASCII values of the first
characters of both strings.
2.If the first characters in both strings are equal, then this
function will check the second character, if they are also equal,
then it will check the third, and so on till the first unmatched
character is found or the NULL character is found.
If a NULL character is found, the function returns zero as
both strings will be the same.

77
Output

Strings are equal


Value returned by strcmp()
is: 0

79
4. If a non- matching character is found,
•If the ASCII value of the character of the first string is
greater than
that of the second string, then the positive difference ( > 0)
between their ASCII values is returned.

81
Output

Strings are
unequal Value of
result: 19

83
•If the ASCII value of the character of the first string is less
than that of the second string, then the negative difference (
< 0) between their ASCII values is returned.

85
Output
Strings are unequal
Value returned by strcmp()
is: -5

87
SPRINTF FUNCTION: sends formatted output to String


Output is written into string instead of displaying it on the
output devices.

Return value is integer ( i.e Number of characters actually placed
in array / length of string ).

String is terminated by ‘\0’.

Main purpose : Sending Formatted output to String.


Header File : Stdio.h

Syntax :
int sprintf(char
*buf,char
format,arg_list
);
89
Example : Output:
My age is 23
int age = 23 ;
char str[100];
sprintf( str , "My age is %d",age);
puts(str);
Analysis of Source Code: Just keep in mind that

Assume that we are using printf then we get output “My age is 23”

What printf will do ? —– Just Print the Result on the Screen

Similarly Sprintf stores result “My age is 23” into string str instead of

printing it.

91
int main() {
float num = 9.34;
printf("I'm a float, look: %f\n", num);
char output[50]; //for storing the converted
string
sprintf(output, "%f", num);
printf("Look, I'm now a string: %s", output);
}

Output
I'm a float, look: 9.340000
Look, I'm now a string: 9.340000

93
int main() {
char output[50];
int num1 = 3, num2 = 5,
ans; ans = num1 * num2;
sprintf(output,"%d multiplied by %d is
%d",num1,num2,ans); printf("%s", output);
return 0;
}
Output

3 multiplied by 5 is 15

95
SSCANF FUNCTION:
Syntax :
int sscanf(const char *str, const char *format, ...);

Common Use Cases for the sscanf() Function

1.Parsing Strings
2.Reading Formatted Data
3.Converting String to Number
4.Reading Data from Buffer

97
#include
<stdio.h> int
main() {
char date[11] = "12-10-
2023"; int day, month,
year;
sscanf(date, "%d-%d-
%d", &day, &month,
&year);
printf("Day: %d, Month: %d, Year: %d\n",
day, month, year);
return 0;
}

99
Example
#include <stdio.h>
int main ()
{
char buffer[30]="Fresh2refresh 5 ";
char name [20];
int age;
sscanf (buffer,"%s
%d",name,&age);
printf ("Name : %s \n Age : %d \n",name,age);
return 0;
}

101
Syntax :
STRSTR FUNCTION:
char *strstr(const char *s1, const char *s2);

Finds first occurrence of sub-string in other string
Features :

Finds the first occurrence of a sub string in another string
Main Purpose : Finding Substring
Header File : String.h

Checks whether s2 is present in s1 or not


On success, strstr returns a pointer to the element in s1 where

s2 begins (points to s2 in s1).



On error (if s2 does not occur in s1), strstr returns null.
103
#include Output:
<stdio.h> String found
#include First occurrence of string 'are' in 'How are you' is
int main()
<string.h> 'are you'
{
// Take any two strings
char s1[ ] = "How are
you"; char s2[ ] =
"are";
char* p;
// Find first occurrence of s2
in s1 p = strstr(s1, s2);
// Prints the result
if (p) {
printf("String found\n");
printf("First occurrence of
string '%s' in '%s' is "‘%s’
"", s2, s1, p);
}
else
105
printf("String not
Example 2
Parameters as String initialized using Pointers
#include<stdio.h>
Output :
#include<string.h>
The substring is:
int main(void) google.com
{
char *str1 = “www.google.com", *str2 = “google", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s", ptr);
return 0;
}

107
Example 3 Output :
Passing Direct Strings The substring is:
google.com
#include<stdio.h>
#include<string.h> void main()
{
char *ptr; ptr=strstr(“www.google.com
",“google"); printf("The substring is:
%s", ptr);
}

109
STRREV(): reverses a given string in C language.

Syntax
char *strrev(char *string);

strrev() function is nonstandard function which may not available in
standard library in C.

Algorithm to Reverse String in C :


Start

Take 2 Subscript Variables ‘i’,’j’

‘j’ is Positioned on Last Character

‘i’ is positioned on first character

str[i] is interchanged with str[j]

Increment ‘i’

Decrement ‘j’

If ‘i’ > ‘j’ then goto step 3
Stop
111
Example
Output:
String before strrev() :
#include<stdio.h> Hello String after
#include<string.h> strrev() :
int main() olleH
{
char name[30] =
"Hello";
printf("String before strrev() :%s\n",name);
printf("String after strrev(%s", strrev(name));
return 0;
}

113
STRCPY FUNCTION: Syntax :
char * strcpy ( char *string1, char *string2 ) ;

Copy second string into First



Function takes two Strings as parameter.

Header File : String.h



It returns string.

Purpose : Copies String2 into String1.



Original contents of String1 will be lost.

Original contents of String2 will remains as it is.

115

strcpy ( str1, str2) – It copies contents of str2 into str1.

strcpy ( str2, str1) – It copies contents of str1 into str2.

If destination string length is less than source entire
string,
source string value won’t be copied into destination string.

For example, consider destination string length is 20 and source

string length is 30.



Then, only 20 characters from source string will be copied into

destination string and remaining 10 characters won’t be copied

and will be truncated.


117
Example 1
Outpu
t:
char s1[10] = "SAM" ; MIKE MIKE
char s2[10] = "MIKE" ;
strcpy (s1,s2);
puts (s1) ; // Prints :
MIKE

puts (s2) ; // Prints :


MIKE

119
Example 2 Output
#include <stdio.h> source string = hihello
#include <string.h> target string =
target string after
int main( ) strcpy( ) = hihello
{
char source[ ] = "hihello" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf("target string after strcpy()=%s",target) ;
return 0; }

121
STRTOK FUNCTION

tokenizes/parses the given string using delimiter.
Syntax
char * strtok ( char * str, const char * delimiters );
For example, we have a comma separated list of items from a file
and we want individual items in an array.

Splits str[] according to given delimiters and returns next token.

It needs to be called in a loop to get all tokens.

It returns NULL when there are no more tokens.

123
EXAMPLE
#include <stdio.h>
#include <string.h>
int main()
{
char str[] =
"Problem_Solving_
in_c";//Returns
first token
char* token = token);
printf("%s\n",
Output:
strtok(str,
token "_");
= strtok(NULL, "_");
}//Keep printing tokens Problem
return
while one0;of the
}delimiters present in Solving
str[].
while (token != in
NULL)
{ C

125
ARITHMETIC CHARACTERS ON STRING

C Programming Allows you to Manipulate on String

Whenever the Character is variable is used in the expression
then it is automatically Converted into Integer Value called
ASCII value.

All Characters can be Manipulated with that Integer
Value.(Addition,Subtraction)
Examples :
ASCII value of : ‘a’ is 97
ASCII value of : ‘z’ is 121

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

printf("%d",x); //Display Result = 98 (ascii of 'b' )

129
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 ) */

131
FUNCTION DECLARATION AND DEFINITION:

❑ A function is a group of statements that together perform a task. Every C


program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
❑ You can divide up your code into separate functions--- logically the division is
such that each function performs a specific task.
❑ A function declaration tells the compiler about a function's name, return type,
and parameters.
❑ A function definition provides the actual body of the function.
❑ The C standard library provides numerous built-in functions that your program
can call. For example, strcat() to concatenate two strings, memcpy() to copy
one memory location to another location, and many more functions.
❑ A function can also be referred as a method or a sub-routine or a procedure, etc.

133
Defining a function
The general form of a function definition in C programming
language is as follows −
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and a
function body. Here are all the parts of a function −

Return Type − A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.

135
Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the function
signature.

Parameters − A parameter is like a placeholder. When a function is


invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.

Function Body − The function body contains a collection of


statements that define what the function does

137
main()
{
display();
}
void mumbai() We have written functions in the above
{ specified sequence , however functions
printf("In mumbai"); are called in which order we call them.
}
void pune()
Here functions are called this sequence –
{
india();
main() ->display() -
}
>
void display()
pune() -> india() ->
{
mumbai().
pune();
}
void india()
{
mumbai();
}

139
Why Funtion is used???

Advantages of Writing Function in C Programming

1. Modular and Structural Programming can be done


❑ We can divide c program in smaller modules.
❑We can call module whenever require. e.g suppose we have written calculator
program then we can write 4 modules (i.e add,sub,multiply,divide)
❑ Modular programming makes C program more readable.
❑ Modules once created , can be re-used in other programs.

2. It follows Top-Down Execution approach , So main can be kept very small.


❑ Every C program starts from main function.
❑ Every function is called directly or indirectly through main
❑ Example : Top down approach. (functions are executed from top to
bottom)

141
3. Individual functions can be easily built,tested
❑ As we have developed C application in modules we can test each and
every module.
❑ Unit testing is possible.
❑ Writing code in function will enhance application development
process.
4. Program development become easy
5. Frequently used functions can be put together in the customized library
❑ We can put frequently used functions in our custom header file.
❑After creating header file we can re use header file. We can include header file
in other program.
6. A function can call other functions & also itself
❑ Function can call other function.
❑ Function can call itself , which is called as “recursive” function.
❑ Recursive functions are also useful in order to write system functions.
7. It is easier to understand the Program topic
❑ We can get overall idea of the project just by reviewing function names.
143
How Function works in C Programming?

• C programming is modular programming language.


• We must divide C program in the different modules in order to create more
readable, eye catching ,effective, optimized code.

145
Explanation : How function works in C Programming ?

❑ First Operating System will call our main function.


❑ When control comes inside main function , execution
of main starts execution of C program starts)
Consider line 4 :
num = square(4);
❑ We have called a function square(4). [ See : How to call
a function ? ].
❑ We have passed “4” as parameter to function.

147
Note : Calling a function halts execution of the current function ,
it will execute called function

• After execution control returned back to the calling function.


• Function will return 16 to the calling function.(i.e. main)
• Returned value will be copied into variable.
• printf will get executed.
• main function ends.
• C program terminates.

149
Function Prototype Declaration

• A function is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
Predefined Function
For example,
int main()
• main() is a function, which is used to
{ printf("Hello
execute code, and
World!"); return 0;
• printf() is a function; used
} to
output/print text to the screen

151
Function Prototype Declaration
return_type function_name(parameter list)
{ How to Declare a Function in C
// function body return_type function_name(parameter_list);

} Example: int add(int num1, int num2);

The return_type specifies the type of value that the function will
return. If the function does not return anything, the return_type will be
void.
The function_name is the name of the function, and the
parameter list specifies the parameters that the function will take in.

153
Function Prototype Declaration: Example:
#include <stdio.h>
//Function declaration
/* function definition */
int add(int a, int b)
{
return a + b;
}
int main() { // Starting point of execution
int result = add(2,3); // Calling Function
printf("The result is %d\n", result);
return 0;
}
Function definition:
It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is
called. Here, we must notice that only one value can be returned from the
function.

155
FUNCTION PROTOTYPE DECLARATION
FUNCTION DECLARATION:

A FUNCTION MUST BE DECLARED GLOBALLY IN A C PROGRAM TO TELL THE COMPILER ABOUT THE

FUNCTION NAME, FUNCTION PARAMETERS, AND RETURN TYPE.

Function Call:
Function can be called from anywhere in the program. The parameter
list must not differ in function calling and function declaration. We must pass
the same number of functions as it is declared in the function declaration.
Actual Parameters
Actual parameters are values that are passed to a function when it is invoked.
Formal Parameters
Formal parameters are the variables defined by the function that receives
values when the function is called.
157
FUNCTION PROTOTYPE DECLARATION IN C PROGRAMMING
FUNCTION PROTOTYPE DECLARATION IS NECESSARY IN ORDER TO PROVIDE

information the compiler about function, about return type, parameter


list and function name etc.
Important Points :

• Our program starts from main function.


• Each and every function is called directly or
indirectly through main function
• Like variable we also need to declare function before
using it in program.
• In C, declaration of function is called as

• prototype declaration
• function prototype

159
Points to remember

Below are some of the important notable things related


to prototype declaration

• It tells name of function, return type of function


and argument list related information to the
compiler
• Prototype declaration always ends with semicolon.
• Parameter list is optional.
• Default return type is integer.

161
Actual and Formal Parameters

Difference between Actual and Formal Parameters

163
Actual and Formal Parameters

Example
#include <stdio.h>
void addition (int x, int y) { // Formal parameters
int addition;
addition = x+y;
printf(“%d”,ad
dition);
}
void main () {
addition
(2,3); //actual
parameters
addition 165
(4,5); //actual
Different aspects of function calling: Type 1
Output:
Example
#include<stdio.h>
void
printName();
void main ()
{
printName(); // function without arguments and without return value
printf("Hello
} ");
void printName()
{
printf("Students");
}

167
Different aspects of function calling: Type 2
Output:
Example
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing
to calculate the
sum of two
numbers:");
result = sum();
//Function
without
arguments
and with
return value
printf("%d",res
ult);
169
}
Different aspects of function calling : Type 3 Output:

Example
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\n sum
of two
numbers:");
result =
sum(2,3);
//Function
with
arguments
and with
return value
printf("%d",res
ult); 171
}
Different aspects of function calling: Type 4 Output:
Example
#include<stdio.h>
void sum();
void main()
{
int result;
sum(2,3);
//Function
with
arguments
and no return
value
}
void sum(int a,int
b)
{
printf("Additio
n of two
numbers %d", 173
Call by Value & Call by Reference
CALL BY VALUE
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
Example: Output:
#include <stdio.h>
void swap(int x, int y);
int main () {
int a = 100;
int b =
200;
printf("Bef
ore swap,
value of a :
%d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int x, int y) {
int temp;
CALL BY REFERENCE
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. It means the changes made to the parameter affect the
Output:

•passed argument.
•Example:
•#include <stdio.h> int main ()
{
• int a = 100;
• int b = 200;
• printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
• swap(&a, &b);
• printf("After swap, value of a : %d\n", a );
• printf("After swap, value of b : %d\n", b ); return
0;
•}
• void swap(int *x, int *y) { int temp;
Why do we need functions in C programming?

❖ Enables reusability and reduces redundancy

❖ Makes a code modular

❖ Provides abstraction functionality

❖ The program becomes easy to understand and manage

❖ Breaks an extensive program into smaller and simpler pieces

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy