Unit4- C
Unit4- C
INTRODUCTION:
We, humans, depend on many people, knowingly or unknowingly, for many different
[Link] being intelligent, we cannot complete all life's tasks independently. For example, A
personmay call a mechanic to repair his car, employ a gardener to prune his lawn, and depend on a
grocerystore to deliver foodstuff monthly. Similarly, A computer program (other than the simple
programsstudied in previous chapters) faces an analogous situation; it cannot complete every task by
[Link], it requires program-like entities known as functions to complete the task. This
sectiondiscusses the use of functions in a programming language.
A function can be defined as a set of statements that collectively performs some task. It
takesinputs, performs the tasks, and returns the results. A function must be declared first before
callingin the program. We can call the function several times. As we have already seen, using a
functionis similar to employing a person to carry out an assigned task. Getting along with the person
issometimes easy and challenging. For example, consider a routine operation you conduct, such
asrepairing your motorcycle every two months in the same manner as before. When the time
comes,you visit the service center and request its service. The individual does not need to
provideinstructions because the mechanic is experienced in his work. When the task is done, you do
TYPES OF FUNCTIONS:
The two kinds of functions provided in C programming are user-defined and library
functions(shown in Fig.4.14). Library functions are built-in functions that perform a specific task
and arepresent in standard libraries. The header files are used to include these standard
[Link] are not required to write library functions. A C program uses a variety of built-
infunctions that are present in the standard C library. For example, printf() and scanf()are defined in
the stdio.h library, while cbrt() for computing the cube of a number and pow() forthe computing
power of a number is defined in math.h library. User-defined functions arerequired to be written by
LIBRARY FUNCTION:
[Link]
If you try to use printf() without including the stdio.h header file, you will get an error.
To compute the square root of a number, you can use the sqrt() library function. The function is
defined in the math.h header file.
#include<stdio.h>
#include<math.h>
intmain()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
Enter a number: 12
Square root of 12.00 = 3.46
strlen ()
strcmp ()
strcpy ()
strncmp ()
strncpy ()
strrev ()
strcat ()
strstr ()
strncat ()
Syntax
int strlen (string name)
Example
#include <string.h>
main (){
char a[30] = “Hello”;
int l;
Output
length of the string = 5
stdio.h − It is a standard i/o header file in which Input/output functions are declared
conio.h − This is a console input/output header file.
string.h − All string related functions are in this header file.
stdlib.h − This file contains common functions which are used in the C programs.
math.h − All functions related to mathematics are in this header file.
time.h − This file contains time and clock related [Link] functions in stdio.h
SOLVED PROBLEMS 01
2) #include<string.h>
3) main (){
4) char a[50], b[50];
5) printf("enter a source string");
6) scanf("%s", a);
7) printf("enter destination string");
8) scanf("%s",b);
9) strcpy(b,a);
10) printf("copied string = %s",b);
11) getch();
12) }
OUTPUT:
OUTPUT:
#include<stdio.h>
#include<string.h>
int main (){
char a[50], b [50];
int d;
printf("Enter 2 strings:");
scanf("%s %s",a,b);
d =strcmp(a,b);
if(d==0){
printf("%s is (alphabetically) equal to %s",a,b);
}elseif(d>0){
printf("%s is (alphabetically) greater than %s",a,b);
}elseif(d<0){
printf("%s is (alphabetically) less than %s",a,b);
}
}
OUTPUT:
#include <stdio.h>
#include <math.h>
int main ()
{
return(0);
}
Output:
SELF-TEST 01
1) Input/output function prototypes and macros are defined in which header file?
a) conio.h
b) stdlib.h
c) stdio.h
d) dos.h
2) If the two strings are found to be unequal then strcmp returns difference between the
first non-matching pair of characters.
a) True
b) false
3) The prototypes of all standard library string functions are declared in the file string.h.
1) In C, when you use a command like getchar() or strcpy() you are actually executing
what?
2) How libraries are included in code
SUMMARY
Functions are sets of statements that take inputs, perform some operations, and
produce results. The operation of a function occurs only when it is called. Rather than
writing the same code for different inputs repeatedly, we can call the function instead of
writing the same code over and over again. Functions accept parameters, which are data. A
function performs a certain action, and it is important for reusing code. Within a function,
there are a number of programming statements enclosed by {}.
There are two types of functions user defined functions and library function.
Functions that are created by the programmer are known as User-Defined functions or
“tailor-made functions”. User-defined functions can be improved and modified according to
the need of the programmer. Whenever we write a function that is case-specific and is not
defined in any header file, we need to declare and define our own functions according to the
syntax.
Library functions are built-in functions that are grouped together and placed in a common
location called [Link] function here performs a specific operation. We can use this library
functions to get the pre-defined [Link] C standard library functions are declared by using many
header files. These library functions are created at the time of designing the [Link] include the
header files in our C program by using #include<filename.h>. Whenever the program is run and
executed, the related files are included in the C program.
KEY WORDS
C, functions, library function, user defined
[Link]
[Link]
[Link]
[Link]
[Link]
OER
[Link]
[Link]
BOOKS
[Link]
[Link]
MOOCS
[Link]
[Link]
A function is a block of code that can be used to perform a specific action. C allows
programmers to write their own functions, also known as user-defined functions. A user-
defined function has three main components that are function declarations, function
definition and function call. Further functions can be called by call by value or call by
reference. Functions need to be written once and can be called as many times as required
inside the program, which increases reusability in code and makes code more readable and
easy to test, debug, and maintain the code.
Output
Factorial(5) = 120
A function is a block of code that can be used to perform a specific action. C allows
users to create their own functions called user-defined functions. A user-defined function
can perform specific actions defined by users based on given inputs and deliver the required
output.
Function divides our program into several independent sub-tasks, making our code
easier to test and debug than one extensive program. The function also helps us avoid
duplication of efforts in our code as we don't have to write the same code again, reducing
the time to write code as explained in the above example.
Functions in the C language have three parts. Let us discuss each of them in detail.
FUNCTION DECLARATION
A function declaration has three main components: return type, function name,
and parameters. The function name is used to identify the function uniquely in code.
Function parameters are included in the declaration to identify the number and types of
inputs that the function accepts.
It is not compulsory to mention parameter name in declaration hence we can also use
1. Return type: The type of data returned from the function is called return type. A
function may not return any output, in that case, we use void as the return type. In
function declaration return type is mentioned before the name of the function.
2. Function name: Function name is a unique name that can be used to identify our
function in the program. Function names are used to create function calls, which is
why they are unique identifiers for compilers. A valid function name in C can
contain letters, underscore, and digits; the first letter must not be a digit.
For example,
thisIsAfunction(); // valid
_getMaximum(); // valid
!getMinimum(); // invalid, symbols except underscore are not allowed
getPowerOf2(); // valid
2Root(); // invalid function name, must not start with a number
3. Parameter list: Parameters required by the function are also defined inside the
declaration to tell the compiler number of arguments required by the function along
with their data types.
4. Semicolon: Semicolon indicates the termination of a function declaration.
Note: Function declaration is not required if the function is defined before it is called in the
code.
FUNCTION DEFINITION
1. Return type
2. Function name
3. Function parameters
4. Body of function
Function body contains a collection of instructions that define what a function does. If the
function returns any value, we use the keyword return to return the value from the function.
For example, return (5*10); returns value 50 of integer data type.
returnTypefunctionName(functionParameters...) {
// function body
}
We can also give default values to function parameters that are assigned to the parameter if
no argument is passed. For example,
The control can be passed to the called function in various ways (back to the place
from where the function was called). When the function returns nothing, the control is
transferred when the right curly brace of the function is encountered, or it can be
accomplished by executing the following statement.
When the function returns a value, the statement return expression; is used to return
the value to the point from which it has been invoked. Here, an expression could be a value
or an expression.
For example, a function finds the smallest number among two and returns the
smallest number.
int smallest(int var1 , int var2) //function definition
{
int small; if(var1 > var2) small = var2;
else
small = var1;
return small;
}
Here, in the above example, a function smallest is defined, which finds the
smallestnumber among the two numbers. This function takes two arguments of integer type
andreturns an integer value after executing the function’s body. The variable declared inside
the function’s body, that is, small is the local variable. It is identified within the function
smallest in which it is defined.
1)
2) #include <stdio.h>
3)
4) // Function declaration
6)
8) int main() {
11) return 0;
12) }
13)
16) return x + y;
2)
#include <stdio.h>
return x + y;
int main() {
return 0;
3)
return result;
}
SELF-TEST 01
a) Library Functions
b) User Defined Functions
c) Both Library and User Defined
d) None of the above
a) 16
b) 31
c) 32
SUMMARY
KEY WORDS
C, user defined,functions,declaration
REFERENCES
YOUTUBE VIDEOS
[Link]
[Link]
[Link]
[Link]
OER
[Link]
[Link]
[Link]
MOOCS
[Link]
[Link]
04-03: ARGUMENTS
INTRODUCTION:
The values that are declared within a function when the function is called are known as an
argument. Whereas, the variables that are defined when the function is declared are known
as a parameter. Let’s analyze the differences between arguments and parameters.
WHAT IS ARGUMENT?
The values that are declared within a function when the function is called are known as an
argument. These values are considered as the root of the function that needs the arguments
while execution, and it is also known as Actual arguments or Actual Parameters.
WHAT IS PARAMETER?
The variables that are defined when the function is declared are known as a parameter.
These are also known as formal parameters or formal arguments.
1 The values that are declared within a The variables that are defined when
function when the function is called are the function is declared are known as
known as an argument. parameters.
3 During the time of call each argument is Parameters are local variables which
always assigned to the parameter in the are assigned values of the arguments
function definition. when the function is called.
4 They are also known as Actual They are also known as Formal
Parameters. Parameters.
SOLVED PROBLEMS 01
NA
SELF-TEST 01
2) Select a program which get input data from datafile and also send output into
datafile ,it is called _____
a) files
b) file processing
c) data files
d) file handling
SUMMARY
A file is a collection of records. This is a loose definition of a file. The term file,
however, is usually reserved for large collections of information stored on devices outside the
computer's internal memory. It usually implies that the records are stored in secondary storage
in the computer's external memory, on tapes or disks. As a result, the ways in which the file
must be organized so that operations on it can be carried out efficiently are dependent on the
characteristics of the secondary storage devices used to implement the file. The basic
operations on a file are to insert and delete records, process or update records, and search for
or retrieve records. These operations are the same as the basic operations on arrays, lists,
trees, list-structures, and more complex lists, which are stored in the computer's internal
memory.
KEY WORDS
C, structure, record,file,field
REFERENCES
YOUTUBE VIDEOS
[Link]
[Link]
[Link]
OER
[Link]
[Link]
BOOKS
[Link]
[Link]
MOOCS
[Link]
[Link]
FOPEN(),FCLOSE(),FPRINTF(),FSCANF(),GETC(),PUTC(),CLOSING FILES.
INTRODUCTION:
In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be displayed
may be very large, and only a limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be
accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file system
through our C program. The following operations can be performed on a file.
There are many functions in the C library to open, read, write, search and close the file. A list of file
functions are given below:
We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.
o The file name (string). If the file is stored at some specific location, then we must mention the
path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
Mode Description
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
Output
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("[Link]", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Syntax:
Example:
Let's see a file handling example to store employee information as entered by user from console. We
are going to store id, name and salary of the employee.
1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("[Link]", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin directory, you will
see [Link] file. It will have following information.
[Link]
Id= 1
Name= sonoo
Salary= 120000
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
Example:
1. #include <stdio.h>
2. main(){
The fgetc() function returns a single character from the file. It gets a character from the stream. It
returns EOF at the end of file.
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("[Link]","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
SOLVED PROBLEMS 01
1) C program to read name and marks of n number of students and store them in a file.
#include <stdio.h>
int main()
CCCXXX: Book TitlePage 34
{
char name[50];
int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\[Link]", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fclose(fptr);
return 0;
}
2) C program to read name and marks of n number of students from and store them in a
file. If the file previously exits, add the information to the file.
FILE *fptr;
fptr = (fopen("C:\\[Link]", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fclose(fptr);
return 0;
}
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("[Link]","wb");
for(i = 0; i< 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
SELF-TEST 01
a) math.h
b) file.h
c) canio.h
d) stdio.h
SUMMARY
So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. But in the software industry, most programs are written to store the information fetched
from the program. One such way is to store the fetched information in a file. Different operations that
can be performed on a file are:
1. Creation of a new file (fopen() with attributes as “a” or “a+” or “w” or “w+”)
2. Opening an existing file (fopen())
3. Reading from file (fscanf() or fgets())
4. Writing to a file (fprintf() or fputs())
5. Moving to a specific location in a file (fseek(), rewind())
6. Closing a file (fclose())
The text in the brackets denotes the functions used for performing those operations.
The output of a C program is generally deleted when the program is closed. Sometimes, we need to
store that output for purposes like data analysis, result presentation, comparison of output for different
conditions, etc. The use of file handling is exactly what the situation calls for.
In order to understand why file handling makes programming easier, let us look at a few reasons:
Reusability: The file-handling process keeps track of the information created after the program
has been run.
Portability: Without losing any data files can be transferred to another in the computer system.
The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows you
to easily access a part of a code using individual commands which saves a lot of time and reduces
the chance of errors.
Storage Capacity: Files allow you to store data without having to worry about storing everything
simultaneously in a program.
KEY WORDS
C, structure, file, file handling
[Link]
[Link]
[Link]
OER
[Link]
[Link]
BOOKS
[Link]
[Link]
MOOCS
[Link]
[Link]