0% found this document useful (0 votes)
63 views

Functions in UNIt 3C Language

The document discusses functions in C language. It defines a function as a block of code that performs a specific task. Functions allow programmers to divide a large program into smaller reusable parts. The summary includes: 1) A function declaration specifies the function name, return type, and parameters. A function definition provides the body of code. 2) Functions allow code to be reused by calling the function multiple times. Common functions include those for math operations and string manipulation. 3) Functions are called by their name and pass arguments. Arguments can be passed by value, where copies are used, or by reference, where the original variable is accessed.
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)
63 views

Functions in UNIt 3C Language

The document discusses functions in C language. It defines a function as a block of code that performs a specific task. Functions allow programmers to divide a large program into smaller reusable parts. The summary includes: 1) A function declaration specifies the function name, return type, and parameters. A function definition provides the body of code. 2) Functions allow code to be reused by calling the function multiple times. Common functions include those for math operations and string manipulation. 3) Functions are called by their name and pass arguments. Arguments can be passed by value, where copies are used, or by reference, where the original variable is accessed.
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/ 17

Unit 3

Functions in C Language
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.
We can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually 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, function strcat() to concatenate two strings, function memcpy() to copy one memory
location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
Defining a Function

return_type function_name( parameter list )


{
body of the function
}
A C++ function definition 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.
• 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.
Example:

#include<iostream.h>
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}

int main()
{
int a = 10;
int b = 20;
// calling the function with name 'sum'
sum (a, b);
}
Here, a and b are two variables which are sent as arguments to the function sum, and x and y
are parameters which will hold values of a and b to perform the required operation inside the
function.
Function body: is the part where the code statements are written.

Declaring, Defining and Calling a Function


Function declaration, is done to tell the compiler about the existence of the function. Function's
return type, its name & parameter list is mentioned. Function body is written in its definition. Lets
understand this with help of an example.
#include < iostream.h>
int sum (int x, int y);
void main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling the function
cout << c;
}
//defining the function
int sum (int x, int y)
{
return (x + y);
}
Here, initially the function is declared, without body. Then inside main() function it is called, as
the function returns sumation of two values, and variable c is there to store the result. Then, at last,
function is defined, where the body of function is specified. We can also, declare & define the
function together, but then it should be done before it is called.

Calling a Function
Functions are called by their names. If the function is without argument, it can be called directly
using its name. But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
Call by Value

In this calling technique we pass the values of arguments which are stored or copied into
the formal parameters of functions. Hence, the original values are unchanged only the parameters
inside function changes.
#include<iostream.h>
void calc(int x);
void main()
{
int x = 10;
calc(x);
printf("%d", x);
}

void calc(int x)
{
x = x + 10 ;
}
10
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.
#include<iostream.h>
void calc(int *p);
void main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
20
C++ Programs
1. Following is the program to check whether a number is prime or not.
#include<iostream.h>
void main()
{
int no, i;
cout<<"Enter a number to be checked (greater than 2) : ";
cin>>no;
for(i=2;i<no;i++)
{
if(no%i==0)
{
break;
}
}
if(no==i)
{
cout<<"\n"<<no<<" is a prime number";
}
else
{
cout<<"\n"<<no<<" is not a prime number";
}
}
2. Following is the program to check whether a number is armstrong or not.
#include<iostream.h>
void main()
{
int no, ld, nn=0, cn;
cout<<"Enter a number to be checked : "
cin>>no;
cn==no;
while(no > 0)
{
ld=no%10;
nn=nn+ld*ld*ld;
no=n/10;
}
if(nn==cn)
{
cout<<"\n"<<cn<<" is an armstrong number";
}
else
{
cout<<"\n"<<cn<<" is not an armstrong number";
}
}

3. Following is the program to find factorial of a given number.


#include<iostream.h>
#include<conio.h>
void main()
{
int i, n1, factorial=1;
clrscr() ;
cout<<"Enter the number to find it's factorial : " ;
cin>>n1 ;
for(a=1;a<=n1;a++)
{
factorial*=a;
}
if(n1==0)
{
cout<<"\nThe factorial is : 1";
}
else
{
cout<<"\nThe factorial is : "<<factorial;
}
getch() ;
}
4. Following is the program to find greatest of three numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2 && n1 >= n3)
{
cout << "Largest number: " << n1;
}
if(n2 >= n1 && n2 >= n3)
{
cout << "Largest number: " << n2;
}
if(n3 >= n1 && n3 >= n2)
{
cout << "Largest number: " << n3;
}
getch();
}

5. Following is the program to swap two numbers with the help of a temporary variable.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,x;
cout<<"Enter a and b:\n";
cin>>a>>b;
cout<<"Before swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b=
"<<b<<endl;
{
x=a;
a=b;
b=x;
cout<<"After swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b=
"<<b<<endl;
}
PROGRAMMING IN C... 2nd Unit

getch();
}
6. Following is a program to check whether a string is palindrome or not.
#includ
e<iostr
eam.h>
#includ
e<strin
g.h>
void
main()
{
char string[50];
int len, i, x, flag=0;
cout<<"Enter a String(max 49
characters): ";
cin.getline(string,50);
len = strlen(string);
for(i=0, x=len-1;i<=len/2;i++, x--)
{
if(string[i]!=string[x])
{
flag=1; break;
}
}
if(flag==0)
{
cout<<"\n\nString is palindrome";
}
else
{
cout<<"\n\nString is not a palindrome";
}
}

Page 9 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

Unit -3
Non-formatted and Formatted input/output Functions

Non-formatted I/O Functions:-


➢ Non-formatted Input/output functions are the simple and basic i/0 functions of C.
➢ They are the means of the data transfer between the memory and the file in binary
form.
➢ They can operate only on the data of type ‘char”. Various Non-formatted
Input/Output Functions
The various non-formatted I/O functions are as follows

1) getchar()
2) putchar()
3) gets()
4) puts()
5) getch()
6) putch()

1) getchar()

This function returns a single character entered from keyboard.


It does not requires any arguments.
It is used to read a string.
Syntax
var = getchar();

Here, var is an identifier of char týpe.


2) putchar(var)
This function displays a single character on an output device.
Syntax

putchar(var);
3) gets()
This function reads an input string.
Syntax
Page 10 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

gets(var);
Here, var is a character string
4) puts(var)

This function displays string stored in var on keyboard.


Syntax
puts(var);
5) getch()

getch() is an unformatted I/O function defined in conio.h header file.


It is an input function that takes single character as input and does not display (echo) it on
screen,
Syntax

int getch(void)
or
variableName = getch();
6) putch()
putch() is an unformatied I/O function defined in conio.h headerfile.

This function is used for displaying a single alphanumeric character on the screen.
Syntax
putch(variable);
Programs Example

Programs Example on getchar() and putchar() #include<stdio.h>


#include<conio.h>
void main()
{

char ch:
clrscr;
printf("Enter a character:");
ch = getchar();

printf("You entered:");

Page 11 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

putchar(ch);
getch();
return 0;

}
Output
Enter a character: s
You entered: s

Example on gets() and puts()


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

void main()
{
char a[25];
clrscr();
printf("Enter the string :");

gets(a);
puts(a);
getch();
return;

Output
Enter the string : Hello

Hello
Example on getch() and putch()
#include<stdio.h>
#include<conio.h>

int main()

Page 12 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

{
char ch;
printf("Press any key\n");

ch = getch();
printf("The key pressed is:");
putch(ch),
return 0;

}
Output
Press any key The key
The key pressed is: s

Page 13 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

Formatted input/output functions.

The input and output data which is ordered in specific format is called format input and
output data.
There are two formatted input/output functions.

1) scanf():
It is used for formatted input

2) printf()
1) It is used to obtain formatted output

1) scanf():
This function is used to read values for variables from keyboard.

Sýntax:-
scanf(“control string”, address_list);
Control String
➢ Control string is enclosed within double quotes.
➢ It specifies the type of values that have to be read from keyboard.
➢ It consists of field specification written in the form "%field specification”.

Field formats for different data types are given below,


Format. Type of Value
%d Integer
%f Floating numbers
%c Character

%ld Long integer


%u Unsigned integer
%lf Double
%s String type

Page 14 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

%ox Hexadecimal
%o Octal
%i Decimal or hexadecimal or octal

%e Floating point number in exponential form


%og Floating point number with trailing zeros truncated,
Address_list
➢ It contains addresses of input/output variables.
➢ The addresses are specified by preceding a variable by '&' operator,
Example

scanf("%d %f %d",&i, &a, &b);


When user enters 10,5.5, *' from keyboard, 10 is assigned to i, 5.5 is assigned to a and 'z' is
assigned to b.
User can also specify field widths in field formats as "% width field specifier".

2) printf()
This function is used to print result on monitor.

Syntax
printf("control string", argl, arg2...., argn);
Control String
Control string can have,
➢ Format specifier given in the form "% specifier"
➢ Escape sequence characters such as t (tab), \n (new line), \b (blank) etc.
➢ It can have a string that must be printed on console i.e., monitor.
➢ argl, arg2...., argn are the variables whose values must be printed on the monitor in
the format specified in control string
Examples

1. printf("%d %c", num, ch);


2. printf(“hello world”);
3. printf("%d\n%c" num, ch);

Page 15 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

Programme
#include<stdio.h>
#include<conio.b>
int main()
int s id;

char s_name[20];
float s percentage:
clrscr;
printf("Enter Student ID:");
scanf("%d",&s_id);
printf("Enter Student Name:");
scanf("%s",&s_name);
printf("Enter Student Percentage:”);

scanf("%f",&s_percentage);
printf("\nThe Student Details are:");
printf(" nStudent Id:%d\nStudent Name:%s\nStudent Percentage:%f",s_id,s_name,s
percentage);
getch();

return 0;
}

Output
Enter Student Id : 1
Enter Student Name: Sai
Enter Student Percentage:75
The student details are :-
Student Id : 1

Student Name: Sai

Page 16 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali
PROGRAMMING IN C... 2nd Unit

Student Percentage:75

Page 17 of 17
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Laxman Anukali

You might also like