Programming in C c is strong language in
Programming in C c is strong language in
POPE’S COLLEGE
SAWYERPURAM
STUDY MATERIAL
PROGRAMMING IN C
SEMESTER – I
1
Part – III / Information Technology / Semester – I
Unit Contents
I Studying Concepts of Programming Languages- Language Evaluation Criteria -
Language design - Language Categories - Implementation Methods – Programming
Environments - Overview of C: History of C- Importance of C- Basic Structure of C
Programs- Executing a C Program- Constants, Variables and Data types - Operators and
Expressions - Managing Input and Output Operations
II Decision Making and Branching: Decision Making and Looping -
Arrays - Character Arrays and Strings
III User Defined Functions: Elements of User Defined Functions- Definition of Functions-
Return Values and their Types- Function Call- Function Declaration- Categories of
Functions- Nesting of Functions- Recursion
IV Structures and Unions: Introduction- Defining a Structure- Declaring Structure Variables
Accessing Structure Members- Structure Initialization- Arrays of Structures- Arrays
within Structures- Unions- Size of Structures.
V Pointers: Understanding Pointers- Accessing the Address of a Variable- Declaring Pointer
Variables- Initializing of Pointer Variables- Accessing a Variable through its Pointer-
Chain of Pointers- Pointer Expressions- Pointer and Scale Factor- Pointer and Arrays-
Pointers and Character Strings- Array of Pointers- Pointer as Function Arguments-
Functions Returning Pointers- Pointers to Functions- File Management in C
Textbooks
Robert W. Sebesta, (2012), ―Concepts of Programming Languages‖, Fourth
Edition, Addison Wesley (Unit I : Chapter – 1)
E. Balaguruswamy, (2010), ―Programming in ANSI C‖, Fifth Edition, Tata McGraw
Hill Publications
2
UNIT – I
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
LANGUAGE DESIGN
The design of a programming language involves establishing rules for writing code,
choosing data types, and deciding how to move through the code. It also includes making sure the
code is easy to read, adding features to help with large projects, and creating tools for checking and
running code.
Steps to consider when designing a programming language:
● Define the problem: Clearly define the problem the language will solve.
● Identify features: Identify the features the language should include.
● Design syntax: Design the rules for constructing valid statements in the language.
Some criteria for good language design include:
● Simplicity: Clarity and simplicity are more important than in regular programming.
● Security: The language should be secure.
● Fast translation: The language should be efficient and easily converted into machine code.
● Efficient object code: The language should consume little space in memory when executed.
3
● Readability: The code should be easy to read.
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
LANGUAGE CATEGORIES
Programming languages can be categorized into several types, including:
● Machine language
● Assembly language
● High-level language
● Procedural languages
● Object-oriented languages
● Scripting languages
● Markup languages
● Query languages
Machine Language
Machine language is called as low level language. Low-level languages are closer to
machine language and don't require translators.
Assembly Language
An assembly language is a type of low-level programming language that is intended to
communicate directly with a computer's hardware. Unlike machine language, which consists of
binary and hexadecimal characters, assembly languages are designed to be readable by humans.
High-level languages
High level languages are closer to human language and require translators to be understood
by computers.
Procedural languages
Use step-by-step instructions, like C, Pascal, and BASIC
Object-oriented languages
Organize code into object classes and methods, like Java, C++, and Python. T
Scripting languages
Automate tasks and integrate applications, like JavaScript, PHP, and Ruby. It is easy to use
and develop for various applications, including web development and automation.
Markup Languages
Markup languages are designed to define and present text. They use tags to mark up
elements within a text file, explaining the purpose of that part of the content. Here are some
examples of markup languages:
Query Languages
Query languages, also known as data query languages or database query languages (DQLs),
are computer languages that let users access and manipulate data from databases. They act as an
interface between users and databases, allowing users to manage data from a database management
system (DBMS).
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
IMPLEMENTATION METHODS
Programs in a source language are implemented using
1. Compilation:
4
▪ Translate program from source language to target language
▪ Program in target language is then executed
▪ Compiler finished before program executed
▪ Diagram:
▪ source -> compiler -> target
▪ input -> target -> output
2. Interpretation:
▪ Directly execute source language program
▪ Fetch source program, decode it, execute it
▪ Interpreter executes while program executing
▪ Diagram:
▪ source + input -> interpreter -> output
● Or both:
o Compile source program to intermediate language version
o Interpret intermediate language version
o Diagram:
▪ source -> compiler -> intermediate
▪ intermediate + input -> interpreter -> output
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
PROGRAMMING ENVIRONMENTS
A Programming Environment is the collection of tools used in the development of software.
● In a general sense, a programming environment combines hardware and software that allows a
developer to build applications.
● Developers typically work in integrated development environments or IDEs. These connect users
with all the features necessary to write and test their code correctly. Different IDEs will offer other
capabilities and advantages.
An (IDE) Integrated Development Environment integrates common development tools in single
software environment.
An IDE normally consists of at least:-
● File system
● Text editor
● Linker
● Compiler
● Integrated tools
IDEs includes features/tools like:
● Debugging
● Syntax highlighting
● Code completion
● Language support
● Code search
● Refactoring
● Version control
5
● Visual programming
Some of the examples of programming environments or IDEs are-
1) Microsoft Visual Studio
2) NetBeans
3) Turbo C, C++
4) Dreamweaver
5) Arduino
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
OVERVIEW OF C
C is a general−purpose, high−level language that was originally developed by Dennis M.
Ritchie to develop the UNIX operating system at Bell Labs. C has now become a widely used
professional language for various reasons
● Easy to learn
● Structured language
● It produces efficient programs
● It can handle low−level activities
● It can be compiled on a variety of computer platforms
About C
● C was invented to write an operating system called UNIX.
● C is a successor of B language which was introduced around the early 1970s.
● The language was formalized in 1988 by the American National Standard Institute (ANSI).
● The UNIX OS was totally written in C.
● Today C is the most widely used and popular System Programming Language.
● Most of the state-of-the-art software have been implemented using C.
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
HISTORY OF C
● C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
● Dennis Ritchie is known as the founder of the c language.
● It was developed to overcome the problems of previous languages such as B, BCPL, etc.
● Initially, C language was developed to be used in UNIX operating system. It inherits many features
of previous languages such as B and BCPL.
● The programming languages that were developed before C language.
6
Traditional C 1972 Dennis Ritchie
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
IMPORTANCE OF C
C programming language offers several advantages over other programming languages, including:
o Efficiency: C allows for direct memory manipulation and low-level access to system resources.
This results in highly efficient code execution.
o Portability: C code can be easily ported to different platforms without major modifications, thanks
to its wide availability of compilers and libraries.
o Speed: C is known for its fast execution speed, making it suitable for developing performance-
critical applications.
o Control: C gives programmers fine-grained control over memory management and system
resources.
o Compatibility: C code can be easily integrated with code written in other languages like C++,
Java, and Python.
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
7
.C Programming - Practical
*/
Preprocessor Section
The preprocessor section contains all the header files used in a program. It informs the system to
link the header files to the system libraries. It is given by:
#include<stdio.h>
#include<conio.h>
Link Section
The link section provides instructions to the compiler to link functions from the system library.
Define Section
The define section comprises of different constants declared using the define keyword. It is given
by:
#define a = 2
Global Declaration
The global section comprises of all the global declarations in the program. It is given by:
float num = 2.54;
int a = 5;
Main Function
main() is the first function to be executed by the computer. It is necessary for a code to include the
main().
The main function is declared as:
main()
8
Local Declarations
The variable that is declared inside a given function or block refers to as local declarations.
main()
{
int i = 2;
i++;
}
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
EXECUTING A C PROGRAM
10
CONSTANTS
In C, constants are values that cannot be modified once they are defined. They are useful for
storing values that remain the same throughout the program,
Syntax to Define Constant
const data_type var_name = value;
11
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
VARIABLES
A variable in C is a memory location with some name that helps store some form of data and
retrieves it when required. We can store different types of data in the variable and reuse the same
variable for storing some other data any number of times.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
data_type: Type of data that a variable can store.
variable_name: Name of the variable given by the user.
value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables
C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the
variable.
Example
int var; // variable definition
var = 10; // initialization
Rules for Naming Variables in C
⮚ A variable name must only contain alphabets, digits, and underscore.
⮚ A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
⮚ No whitespace is allowed within the variable name.
⮚ A variable name must not be any reserved word or keyword.
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
DATA TYPES
ANSI C supports three classes of data types:
1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types
1. Basic Data Types
These are the fundamental data types in C that are directly supported by the programming
language.
include:
● int: Used to store whole numbers.
Example
int age = 25;
12
The "int" data type is used to store whole numbers. In this example, the variable "age" is
assigned the value of 25.
● char: Used to store a single character.
Example
char grade = 'A';
The "char" data type is used to store single characters. In this example, the variable "grade"
is assigned the value of 'A'.
● float: Used to store floating-point numbers.
Example
float price = 9.99;
The "float" data type is used to store floating-point numbers (numbers with a decimal point). In this
example, the variable "price" is assigned the value of 9.99.
● double: Used to store double-precision floating-point numbers.
Example
double salary = 45000.50;
The "double" data type is used to store double-precision floating-point numbers. In this
example, the variable "salary" is assigned the value of 45000.50.
● void: Used to indicate an empty data type.
13
3. User-defined Data Types
The user-defined data types in C are defined by the programmer and are created using the basic and
derived data types. include:
● Enums: A user-defined data type that represents a set of named constants.
● Typedefs: A way to create a new name for an existing data type to improve code readability
and maintainability.
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
OPTERATORS
C SUPPORTS A RICH SET OF BUILT-IN OPEPRATORS
An operator is symbol used to manipulate
C operators can be classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
ARITHMETIC OPERATORS
C provided all the basic arithmetic operates.
Arithmetic Operators
Operator Meaning
X Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division operation produces the
remainder of an integer division.
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the expression is
called an integer expression, and the operation is called integer arithmetic.
Integer arithmetic always yields an integer value. A and b are integers, a = 14 and b = 4 a – b = 10
a + b = 18 a X b = 56
a / b = 3 (decimal part truncated) a % b = 2 (remainder of division)
Relational Operators
C supports six relational operators in all. These operators and their meanings are shown in Table
14
Operator Meaning
== is equal to
!= is not equal to
A simple relation expression contains only one relational operator and takes the following
form:
ae-1 relational operator ae-2
23>3 a <b
Logical Operators
In addition to the relational operators, C has the following three logical operators. && meaning
logical AND
|| meaning logical OR
! meaning logical NOT
The logical operators && and || are used when we want to test more than one condition and
make decisions.
Assignment Operators
Assignment operators are used to assign the result of an expression to a variable. v op= exp;
a=10
Where V us a variable, exp is an expression and op is a C binary arithmetic operator.
The operator op= is known as the shorthand assignment operator. An example
x += y+1;
This is same as the statement
x = x + (y+1);
Increment And Decrement Operators
C allows two very useful operators increment and decrement operators:
++ and −−
The operator ++ adds 1 to the operand, while – subtracts 1. Both are unary operators and
takes the following form:
++m; or m++;
−−m; or m−−;
++m; is equivalent to m = m+1; (or m + = 1;)
−−m; is equivalent to m = m−1; (or m −= 1;)
Conditional Operator
A ternary operator pair “? :” is available in C to construct conditional expressions of the
form
ecp1 ? exp2 : exp3
Where exp1, exp2, and exo3 are expressions.
15
The operator? : works as follows: exp 1 is evaluated first. if it is nonzero (true), then the
expression exp2 is evaluated and becomes the value of the expression. If exp 1 is false, exp3 is
evaluated and its value becomes the value of the expression. For example
a = 10; b = 15;
x = (a > b) ? a : b;
Bitwise Operators
C has special operators known as bitwise operators for manipulation of data at bit level.
These operators are used for testing the bits,
Operator Meaning
^ bitwise exclusive OR
Special Operators
C supports some special operators of interest such as comma operator, size of operator,
pointer operators (& and *) and member selection operators (. and −> ).
The comma Operator
The comma operator can be used to link the related expressions together.
ARITHMETIC EXPRESSIONS
An arithmetic expression is a combination of variables, constants, and operators arranged
as per the syntax of the language.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form: variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression
is evaluated first and the result then replaces the previous value of the variable on the left-hand
side.
Examples:
x = a * b – c; z = a – b / c + d;
Precedence of Arithmetic Expressions
An arithmetic expression without parentheses will be evaluated from left to right using the
rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C:
High priority * / % Low priority + −
16
The basic evaluation procedure includes „two‟ left-to-right passes through the expression.
During the first pass, the high priority operators (if any) are applied as they are encountered.
During the second pass, the low priority operators (if any) are applied as they are encountered.
Example:
x = a-b/3 + c*2−1
When a = 9, b = 12, and c = 3, the statement becomes
x = 9−12/3 + 3*2−1 Answer is 10
However, the order of evaluation can be changed by introducing parentheses into an
expression. Consider the same expression with parentheses as shown below:
9−12/(3+3)*(2−1)
Whenever, parentheses are used, the expressions within parentheses assume highest
priority, if two or more sets of parentheses appear one after another as shown above, the expression
contained in the left-most set is evaluated first and the right-most in the last.
Answer is 7 .
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
17
printf function
This is the most commonly used function for outputting a data of any type.
The syntax is
printf(control string, list of arguments)
Here also control string consists of group of characters, each group having % symbol and
conversion characters.
Example:
#include<stdio.h>
` main()
{
int x; scanf(“%d”,&x); x=x*x;
printf(“The square of the number is %d”,x);
}
🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞🙞
UNIT -II
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main()
18
{
int x, y;
x =15;
y =13;
if(x > y )
{
printf("x is greater than y");
}
}
OUTPUT
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}
If the expression is true, the statement-block1 is executed, else statement-block1 is skipped
and statement-block2 is executed.
Example:
#include <stdio.h>
void main()
{
int x, y;
x =15;
y =18;
19
if(x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
OUTPUT
y is greater than x
else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
elseif(expression2)
{
statement block2;
}
elseif(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
20
Switch Statement
In C, the switch case statement is used for executing one condition from multiple conditions. It is
similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default case.
Syntax of switch Statement in C
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
Case value_n: statement_n;
break;
default:default_statement;
}
21
Example
#include <stdio.h>
void main()
{
int var = 1;
switch (var)
{
case 1:
printf("Case 1 is Matched.");
break;
case 2:
printf("Case 2 is Matched.");
break;
case 3:
printf("Case 3 is Matched.");
break;
default:
printf("Default case is Matched.");
break;
22
}
}
goto Statement
The C goto statement is a jump statement which is sometimes also referred to as an unconditional
jump statement. The goto statement can be used to jump from anywhere to anywhere within a
function.
Syntax:
goto label;
Example
#include<stdio.h>
void main()
{
printf(“\n Department of IT”);
goto line;
printf(“\n Welcome”);
line:
printf(“\n Pope’s College”);
}
OUTPUT
Department of IT
Pope’s College
LOOPING STATEMENTS
Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple times
without repetition of code.
There are mainly two types of loops in C Programming:
Entry Controlled loops:
In Entry controlled loops the test condition is checked before entering the main body of the
loop. For Loop and While Loop is Entry-controlled loops.
Exit Controlled loops:
In Exit controlled loops the test condition is evaluated at the end of the loop body. The loop
body will execute at least once, irrespective of whether the condition is true or false. do-while
Loop is Exit Controlled loop.
for Loop
for loop in C programming is a repetition control structure that allows programmers to write a loop
that will be executed a specific number of times. for loop enables programmers to perform n
number of steps together in a single line.
Syntax:
for (initialize expression; test expression; update expression)
23
{
//
// body of for loop
//
}
Example:
for(int i = 0; i<5; i++)
{
printf("Pope’s College");
}
OUTPUT
Pope’s College
Pope’s College
Pope’s College
Pope’s College
Pope’s College
While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was
previously known to us but in the While loop, the execution is terminated on the basis of the test
condition. If the test condition will become false then it will break from the while loop else body
will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
24
// body of the while loop
update_expression;
}
Flow Diagram for while loop:
Example
#include <stdio.h>
void main()
{
int i = 0;
while(i<5)
{
printf( "Pope’s College\n");
i++;
}
}
OUTPUT
Pope’s College
Pope’s College
Pope’s College
Pope’s College
Pope’s College
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test
condition which is tested at the end of the body. In the do-while loop, the loop body will execute at
least once irrespective of the test condition.
Syntax:
initialization_expression;
do
25
{
// body of do-while loop
update_expression;
} while (test_expression);
EXAMPLE
#include <stdio.h>
void main()
{
int i = 0;
do
{
printf( "Pope’s College\n");
i++;
} while (i<5);
}
OUTPUT
Pope’s College
Pope’s College
Pope’s College
Pope’s College
Pope’s College
ARRAYS:
An array is a collection of similar data type that are used to allocate memory in a sequential
manner.
Syntax :
<data type> <array name>[<size of an array>]
Subscript or indexing:
A subscript is property of an array that distinguishes all its stored elements because all the
26
elements in an array having the same name (i.e. the array name). so to distinguish these, we use
subscripting or indexing option.
e.g. int ar[20];
First element will be: int ar[0];
Second element will be: int ar[1];
Third element will be: int ar[2];
Fourth element will be: int ar[3];
Fifth element will be: int ar[4];
Sixth element will be: int ar[5]; So on……………………
Last element will be: int ar[19];
An array always starts from 0 indexing.
Example: int ar[20];
This above array will store 20 integer type values from 0 to 19.
Advantage of an array:
⮚ Multiple elements are stored under a single unit.
⮚ Searching is fast because all the elements are stored in a sequence.
Types of Arrays
⮚ One Dimensional Array
⮚ Two Dimensional Array.
⮚ One Dimensional Array
An Array of elements is called 1 dimensional, which stores data in column or row form.
Example: int ar[5];
This above array is called one dimensional array because it will store all the elements in column or
in row form
Two Dimensional Array.
An array of an array is said to be 2 dimensional array , which stores data in column and row
Example: int ar[4][5];
This above array is called two dimensional array because it will store all the elements in column
and in row form
In above example of two dimensional array, we have 4 rows and 5 columns. In above example of
two dimensional array, we have total of 20 elements.
Access the Elements of an Array
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
int myNumbers[] = {25, 50, 75, 100};
27
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Now outputs 33
Character Array in C
Char array in C is used for the string type data. Char array in c means character array in c
programing.
For example
Consider the array as shown in following figure. In the array C of size 8 below, if we try to store
the string “Rahul”,
we’ll have-
All the functions for string manipulation in c language, expect strings to be null terminated.
To store this extra null character, we need this extra space.
Strings
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.
char greetings[] = "Hello World!";
Example
char str[] = "Hello World!";
printf("%s", str);
28
UNIT - III
ELEMENTS OF USER DEFINED FUNCTIONS
Functions in the C language have three parts.
⮚ Function declaration
⮚ Function Definition
⮚ Calling the Function
Function declaration
A function declaration is simply a prototype of our function. For example, we have a function with
the name getRectangleArea to calculate the area of a rectangle that takes two integer inputs i.e
length and breadth and, returns an integer area as an output.
Declaration of such a function will be
int getRectangleArea(int , int);
1. Return Type: Specifies the type of data a function returns. Use void for functions without return
values. It precedes the function's name in its declaration.
2. Function Name: A unique identifier for the function, allowing it to be called.
3. Parameter List: Lists the function's parameters, informing the compiler about the number and
types of arguments it expects.
4. Semicolon: Marks the end of a function declaration.
Function Definition
Function definition contains the actual block of code that is executed once the function is called. A
function definition has four components:
1. Return type
2. Function name
3. Function parameters
4. Body of function
Function body contains a collection of instructions that define what function does. We can also
give default values to function parameters that are assigned to the parameter if no argument is
passed. For example,
int getRectangleArea(int length = 10, int breadth = 5)
29
{
return length * breadth;
}
If getRectangleArea() is called, default values will be assigned to function parameters and 50 will
be returned as function output. Here return is used to terminate the function call.
Calling the Function
To put your function to work, you need to call it by its name, followed by parentheses enclosing
any arguments it requires.
Syntax:
functionName(argument1, argument2, ..., argumentN);
DEFINITION OF FUNCTIONS
When we define a function, we provide the actual body of the function. A function definition
provides the following parts of the function.
● The return type is a data type of the value(return by the function).
● Within curly braces the function body is present.
● A function may have 0 or more parameters. When a function is invoked, you pass a value to the
parameter. You can have any type of parameter in C program such as int, float, char, etc.
Syntax:
datatype functionName(int a, int b)
{
statement;
}
Function definition contains the actual block of code that is executed once the function is called. A
function definition has four components:
1. Return type
2. Function name
3. Function parameters
4. Body of function
Example
int fact(int m)
{
---
---
}
30
Return with an Expression:
Syntax
return expression;
In this form, the expression represents the value that the C function returns to the calling code. This
value could be a constant, a variable, or the result of a computation.
2. Return with a Value
return;
When a function has no return value or is used to perform a task without providing any output, the
return statement can be used without an expression. This form simply indicates the end of the
function's execution.
3. No Return Statement
void myFunction()
{
// Function logic without a return statement
}
If a function does not require a return statement, it can be defined with a return type of void,
indicating that the function does not return any value.
Now that you know what the return statement in C entails and the various forms it can take, let's
look at an example showcasing its implementation. Below is an example where we are using a
return statement without an expression.
Function Call
A function call is an important part of the C programming language. It is called inside a program
whenever it is required to call a function. It is only called by its name in the main() function of a
program. We can pass the parameters to a function calling in the main() function.
Add(a, b) // a and b are the parameters
#include <stdio.h>
int add(int a, int b);
void main()
{
int sum;
int a, b;
printf(" Enter the first and second number \n");
scanf("%d %d", &a, &b);
sum = add(a, b); // call add() function
printf( "The sum of the two number is %d", sum);
}
int add(int n1, int n2) // pass n1 and n2 parameter
{
int c;
c = n1 + n2;
return c;
}
31
FUNCTION DECLARATION
Declaration of C Function, tells the compiler about a function’s name, it’s the return type and the
parameters. We can define the actual body of the function separately.
Important points for the Function Declaration:
● Function declaration in C always ends with a semicolon.
● In C Language, by default, the return type of a function is an integer(int) data type.
● A Function declaration is also known as a function prototype.
● In function declaration name of parameters are not compulsory, but we must define their datatype.
Hence the following declaration is also valid.
int getSum(int, int);
Syntax of Declaration of Function
return_type function_name(data_type parameter, data_type parameter)
{
// code to be executed
}
Example
int fact (int);
CATEGORIES OF FUNCTIONS
All the C functions can be called either with arguments or without arguments in a C program.
These functions may or may not return values to the calling function. Depending on the
arguments and return values functions are classified into 4 categories:
1. Function without arguments and without a return value.
2. Function with arguments and without a return value.
3. Function without arguments and with a return value.
4. Function with arguments and with a return value.
1. Functions without arguments and without return value:
In effect, there is no data transfer between the calling function and the called function in the
category function without arguments and without a return value.
Let’s consider an example of a function without arguments and without a return value:
#include <stdio.h>
void country_capital(void);
void main()
{
country_capital();
}
void country_capital()
{
printf("New Delhi is the capital of India\n");
}
2. Functions with arguments and without a return value:
When a function definition has arguments, it receives data from the calling function.
32
The actual arguments in the function call must correspond to the formal parameters in the function
definition, i.e. the number of actual arguments must be the same as the number of formal
parameters, and each actual argument must be of the same data type as its corresponding formal
parameter.
#include <stdio.h>
void largest(int, int);
void main()
{
int p, q;
printf("Enter two numbers : ");
scanf("%d%d" , &p, &q);
largest(p, q);
}
void largest(int x, int y)
{
if (x > y)
{
printf("Largest element = %d\n", x);
} else
{
printf("Largest element = %d\n", y);
}
}
3. Functions without arguments and with a return value:
When a function has no arguments, it does not receive any data from the calling function. When a
function returns a value, the calling function receives data from the called function.
#include <stdio.h>
int sum(void);
void main()
{
printf("\nSum of two given values = %d\n", sum());
}
int sum()
{
int a, b, total;
printf("Enter two numbers : ");
scanf("%d%d", &a, &b);
total = a + b;
return total;
}
4. Functions with arguments and with a return value:
When a function definition has arguments, it receives data from the calling function.
33
After taking some desired action, only one value will be returned from called function to the calling
a function through the return statement.
NESTED FUNCTIONS
Nested functions in C are functions that are defined inside another function. The inner function has
access to the variables of the outer function and can be used to perform specific tasks. However,
nested functions are not supported in standard C programming.
void outer_function()
{
int x = 10;
void inner_function()
{
printf("Value of x: %d\n", x);
}
inner_function();
}
In this example, inner_function is a nested function inside outer_function. The inner_function has
access to the variable x of the outer_function and prints its value.
Keep in mind that nested functions are not portable and may not work on all compilers. It's
always best to check the documentation of your compiler to see if it supports nested functions.
RECURSION
Recursion is the process of a function calling itself repeatedly till the given condition is satisfied. A
function that calls itself directly or indirectly is called a recursive function and such kind of
function calls are called recursive calls. In C, recursion is used to solve complex problems by
breaking them down into simpler sub-problems.
Syntax
This is how a general recursive function
void recursive_function()
{
recursion(); // function calls itself
}
int main()
{
recursive_function();
}
While using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Example: Recursive Factorial Function
Let us now write a recursive function for calculating the factorial of a given number.
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>
#include <math.h>
34
int factorial(int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int a = 5;
int f = factorial(a);
printf("a: %d \n", a);
printf("Factorial of a: %d", f);
return 0;
}
35
UNIT- IV
STRUCTURES
Arrays allow to define type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows to combine data items of
different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book −
● Title
● Author
● Subject
● Book ID
DEFINING A STRUCTURE
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows –
struct [structure tag] { member definition; member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition, before
the final semicolon, you can specify one or more structure variables but it is optional. Here is the
way you would declare the Book structure –
struct Books { char title[50]; char author[50];
char subject[100]; int book_id;
} book;
36
ACCESSING STRUCTURE MEMBER
We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1; strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to access
the members.
#include <stdio.h> #include <string.h> struct student
{
int rollno;
char name[60];
}s1;
void main( )
{
s1.rollno=1;
strcpy(s1.name, “POPESIT”); printf( "Rollno : %d\n", s1.rollno); printf( "Name : %s\n", s1.name);
}
37
Example: Array of Structure
If struture is declared like:
struct employee
{
int emp_id;
char name[20]; char dept[20];
float salary;
};
Then an array of structure can be created like:
struct employee emp[10]; /* This is array of structure */
In this example, the first structure employee is declared, then the array of structure created using a
new type i.e. struct employee. Using the above array of structure 10 set of employee records can
be stored and manipulated.
Acessing Elements from Array of Structure
To access any structure, index is used. For example, to read the emp_id of the first structure we use
scanf(“%d”, emp[0].emp_id); as we know in C array indexing starts from 0.
Similar array of structure can also be declared like:
struct employee
{
int emp_id;
float salary;
}emp[10];
EXAMPLE Program: Array of Structure
C program to read records of three different students in structure having member name, roll and
marks, and displaying it.
#include<stdio.h>
/* Declaration of structure */
struct student
{
char name[30];
int roll;
float marks;
};
void main()
{
/* Declaration of array of structure */
struct student s[3];
int i;
38
for(i=0;i< 3;i++)
{
printf("Enter name, roll and marks of student:\n"); scanf("%s%d%f",s[i].name, &s[i].roll,
&s[i].marks);
}
printf("Inputted details are:\n");
for(i=0;i< 3;i++)
{
printf("Name: %s\n",s[i].name);
printf("Roll: %d\n", s[i].roll); printf("Marks: %0.2f\n\n", s[i].marks);
}
ARRAYS WITHIN STRUCTURES
In C programming, we can have structure members of type arrays. Any structure having an array
as a structure member is known as an array within the structure. We can have as many members
of the type array as we want in C structure.
To access each element from an array within a structure, we write structure variables followed by
dot (.) and then array name along with index.
Example: Array Within Structure
struct student
{
char name[20];
int roll;
float marks[5]; /* This is array within structure */
};
In above example structure named student contains a member element marks which is of type
array. In this example marks is array of floating point numbers.
If we declare structure variable as:
struct student s;
To access individual marks from above structure s, we can write s.marks[0], s.marks[1],
s.marks[2], and so on.
UNION IN C
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many members,
but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Let's understand this through an example. struct abc
{
int a;
char b;
}
The above code is the user-defined structure that consists of two members, i.e., 'a' of type int and
'b' of type character
EXAMPLE
union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
40
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
}
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the size of
double is 8 bytes. Since the double variable occupies the largest memory among all the four
variables, so total 8 bytes will be allocated in the memory. Therefore, the output of the above
program would be 8 bytes.
SIZE OF STRUCTURES
The total size of a structure in the programming language C equals the sum of the sizes of each of
its constituent parts. A structure's overall size is equal to the sum of all of its individual members'
sizes, each of which takes up a specific amount of bytes in memory. In C, a structure's size is equal
to its component's total size. It is possible to figure out a structure type's size in C using the sizeof
operator.
The size of a structure can be evaluated at compilation time in C using the sizeof operator. To
apply the sizeof of a structure, enter sizeof(structure_name) in the syntax bar to get the size in
bytes.
You may estimate the size of a structure called Employee, for instance, by looking at the
members' name, experience, and salary.
Program:
#include <stdio.h> struct employee
{
char name[50];
int experience; float salary;
};
int main()
{
struct employee p;
41
int s;
s = sizeof(p);
printf("Size of Employee structure: %d bytes\n", s); return 0;
}
42
UNIT – V
Pointers
The pointer in C language is a variable which stores the address of another variable. This variable
can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.
Pointer to a function
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a function
Pointer to structure
struct st
{
int i;
float f;
}ref;
struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees,
etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.
43
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to display the
address of a variable.
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.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
Functions for file handling
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:
44
5 fgetc() reads a character from file
Mode Description
45
wb+ opens a binary file in read and write mode
46