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

Programming in c Unit - 1 & 2 Material

The document provides an introduction to algorithms, programming languages, and specifically the C programming language. It covers key features of algorithms, flowcharts, the generations of programming languages, and the design and implementation of software. Additionally, it discusses the advantages and disadvantages of C, its features, and its applications in system programming.

Uploaded by

harshithavennu
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)
6 views

Programming in c Unit - 1 & 2 Material

The document provides an introduction to algorithms, programming languages, and specifically the C programming language. It covers key features of algorithms, flowcharts, the generations of programming languages, and the design and implementation of software. Additionally, it discusses the advantages and disadvantages of C, its features, and its applications in system programming.

Uploaded by

harshithavennu
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/ 60

UNIT - I

Introduction to Algorithms and Programming Languages: Algorithm - Key features


of Algorithms - examples of Algorithms, Flow Charts– Pseudo code, Programming
Languages – Generation of Programming Languages – Structured Programming
Language.
Introduction to C: Introduction – Structure of C Program, Writing the first C Program,
File used in C Program – Compiling and Executing C Programs, Using Comments –
Keywords – Identifiers, Basic Data Types in C, Variables – Constants, I/O Statements in
C, Operators in C, Programming Examples, Type Conversion and Type Casting.
************************************************************************

Algorithm – Key features of Algorithms:


According to the dictionary, algorithm can be represented by “A process or set of rules to
befollowed in calculation or other problem solving operations, especially a computer”.
Definition:
An algorithm is a finite set of instructions to accomplish a particular task in given problem.
Before writing a program for solving a problem it is better to write step by step process
forsolving it. This step by step process is called an algorithm.
Knuth (1968-1973) has given a list of five programming rules that are widely accepted
asrequirements for an algorithm.
Finiteness: an algorithm must always terminate a finite number of steps.
Definiteness: Each step of an algorithm must be preciously defined the action to be carried
out must be clear.
Input: Quantities which are given to it initially before the algorithm begins these inputs
aretaken from specified steps of objects.
Output: Quantities which have a specified relation to input.
Effectiveness: All of the operations to be performed in the algorithm must be sufficiently
basic that they can in principle, by alone exactly and in a finite length of time by a man
using paper and pencil.
Key features / various steps in algorithm development:
An algorithm has a finite number of steps may involve decision making and repetition.
Broadly speaking an algorithm uses three control structures namely sequence, decision, and
repetition.
Sequence:
Sequence means that each step of the algorithm is executed in the specified order.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Example: Algorithm to add two numbers.
Step1: start
Step2: read two numbers as a, b

Step3: set c=a+b;


Step4: print c
Step5: end

Decision:
Decision statements are used when the execution of a process depends on the outcome of some
conditions.A condition is any statement that may evaluate either to a true value or false value.
A decision statement canbe stated using if..else construct in the following manner.
If condition
Then statement
1Else
The statement 2
Example: algorithm to check the equality of twonumbers.

Step1: read two numbers as a, b Step2: if a=b


Then print “two numbers are equal

”Else
Print “two numbers are not equal”
Step3: end
Repetition:
Repetition which involves executing one or more steps for a number of time, can be
implemented using construction such as while, do-while, for loops.

1. Flow Chart

A flowchart is a type of diagram that represents a workflow or process. A flowchart can also
be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving
a task.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
The flowchart shows the steps as boxes of various kinds, and their order by connecting the
boxes with arrows. This diagrammatic representation illustrates a solution model to a given
problem. Flowcharts are used in analyzing, designing, documenting or managing a process or
program in various fields.
Symbols Used In Flowchart
Different symbols are used for different states in flowchart, for example: Input / Output and
decision makinghas different symbols. The table below describes all the symbols that are used
in making flowchart

Symbol Purpose Description


Flow line Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Processing Used for arithmetic operations and data-manipulations.

Decision Used to represent the operation in which there are two


alternatives,true and false.

On-page Connector Used to join different flow line

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing one


Process/Function processingtask.

Significance of flow chart:


A follow chart is a diagrammatic representation that illustrates the sequence of steps that must
be performed to solve a problem. It is usually drawn in the early stages formulating computer
solutions. It facilitates communication between programmers and users. Once a flowchart is
drawn, it becomes easy for the programmers to write the program in any high level language.
Flow charts are very important in the programming of a problem as they help the programmers
to understand the logic of complicated and lengthy problems.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Advantages / Benefits of Flowchart-
Better explanation of program: Flowchart is a pictorial description of any program. The program
created byit can easily be understood.
Effective analysis: Through the flowcharts, the program is divided into smaller parts, making
effective analysis of the program.
Designing of program: Using a flowchart, your program can be designed correctly.
Systematic debugging: When any program is created, it is always tried to make it right, but still
the mistake remains somewhere. These mistakes can only be known when we start the
execution of the program on the computer. The mistake of this type of program, is called
Bugs and the method of removing this mistake, is called Debugging. A flow chart is very
helpful indetecting, locating and removing the mistake in a program.
Disadvantages / Limitations of Flowchart
Time consuming: Creating a flow chart takes more time. The flow chart is made especially for
big complex problems. Which take more time and very hard work.
Difficult to make changes: If there is any modification in the flow chart, then the entire
flowchart has to be recreated.
No standard: Program flowcharts, although easy to understand, but cannot be written as a
standard, like others language. Nor with the help of flowcharts, it can be converted into the
language of the program. Each programmer resolves the problem in its own way and creates
aflow chart accordingly.
Examples:

1. Draw a flowchart to add two numbers entered by user.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
2. Draw flowchart to find the largest among three different numbers entered by user.

Though, flowcharts are useful in efficient coding, debugging and analysis of a program,
drawing flowchart in very complicated in case of complex programs and often ignored.

3. Generations of programming language


Programming languages have been developed over the year in a phased manner. Each phase
of developed has made the programming language more user-friendly, easier to use and more
powerful. Each phase of improved made in the development of the programming languages
can be referred to as a generation. The programming language in terms of their performance
reliability and robustness can be grouped into five different generations,

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
1. First generation languages (1GL)
2. Second generation languages (2GL)
3. Third generation languages (3GL)
4. Fourth generation languages (4GL)
5. Fifth generation languages (5GL)

1. First Generation Language (Machine language)

The first generation programming language is also called low-level programming language
because they were used to program the computer system at a very low level of abstraction. i.e.
at the machine level. The machine language also referred to as the native language of the
computer system is the first generation programming language. In the machine language, a
programmer only deals with a binary number.

Advantages:

 They are translation free and can be directly executed by the computers.
 The programs written in these languages are executed very speedily and efficiently by
the CPU of the computer system.
 The programs written in these languages utilize the memory in an efficient manner
because it is possible to keep track of each bit of data.

2. Second Generation language (Assembly Language)


The second generation programming language also belongs to the category of low-level-
programming language. The second generation language comprises assembly languages that use
the concept of mnemonics for the writing program. In the assembly language, symbolic names
are used to represent the opcode and the operand part of the instruction.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Advantages:

 It is easy to develop understand and modify the program developed in these languages
are compared to those developed in the first generation programming language.
 The programs written in these languages are less prone to errors and therefore can be
maintained with a great case.

3. Third Generation languages (High-Level Languages)

The third generation programming languages were designed to overcome the various
limitations of the first and second generation programming languages. The languages of the
third and later generation are considered as a high-level language because they enable the
programmer to concentrate only on the logic of the programs without considering the internal
architecture of the computer system.
Advantages:

 It is easy to develop, learn and understand the program.


 As the programs written in these languages are less prone to errors they are easy to maintain.
 The program written in these languages can be developed in very less time as
compared to the first and second generation language.

Examples: FORTRAN, ALGOL, COBOL, C++, C

4. Fourth generation language (Very High-level Languages)


The languages of this generation were considered as very high-level programming languages
required a lot of time and effort that affected the productivity of a programmer. The fourth
generation programming languages were designed and developed to reduce the time, cost and
effort needed to develop different types of software applications.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Advantages:

 These programming languages allow the efficient use of data by implementing the various
databases.
 They require less time, cost and effort to develop different types of software applications.
 The program developed in these languages is highly portable as compared to
the programs developed in the languages of other generation.

Examples: SOL, CSS

5. Fifth generation language (Artificial Intelligence Language)


The programming languages of this generation mainly focus on constraint programming. The
major fields in which the fifth generation programming language are employed are Artificial
Intelligence and Artificial Neural Networks

Advantages:

 These languages can be used to query the database in a fast and efficient manner.
 In this generation of language, the user can communicate with the computer system in
a simple and an easy manner.

Examples: mercury, prolog, OPS5


4. Design and Implementation of Correct, Efficient and Maintainable Programs.
The entire program or software (collection of programs) development process is divided in to
a number of phases, where each phase performs a well- defined task.
Requirements analysis:
In this phase, the user’s expectations are gathered to
understand why the program or software has to be
developed. Then, all the gathered requirements are analyzed
and the scope or objective of the overall software product is
penned down. The last activity in this phase involves
documenting every identified requirement of the user in
order to avoid any doubts or uncertainty regarding the
functionality of the program. The functionality, capability,
performance, and availability of hardware and software
components are all analyzed in this phase.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Design:
The requirement documented in the previous phase act as the input to the design phase. In
this phase, a plan of actions is made before the actual development process starts. This plan
will be followed throughout the development process. Moreover, in the design phase, the
core structure of the software or program is broken down in to modules. The solution of the
program is then specified for each module in the form of algorithms or flow charts. The design
phase, therefore specifies how the program or software will be developed.
Implementation:
In this phase, the designed algorithms are converted in to program code using any of the high
level languages. The particular choice of language will depend on the type of program such
as whether it is a system or an application program. C is preferred for writing system
programs, whereas Visual basic might be preferred for an application program. The program
codes are tested by the programmer to ensure their correctness.

Testing:
In this phase, all the modules are tested together to ensure that the overall system works well
as a whole product. In this phase, the software is tested using a large number of varied inputs,
also known as test data, to ensure that the software is working as expected by the user’s
requirements identified in the requirements analysis phase.
Software deployment, training, and support:
After the code is tested and the software or the program is approved by the user’s it is then
installed or deployed in the production environment.
Software training and support is a crucial phase. Program designers and developers spend a lot
of time creating the software, but if nobody in the organization knows how to use it or to fix
certain problems , then no one will want to use it.
Maintenance:
Maintenance and enhancements are ongoing activities that are done to cope with newly
discovered problems or new requirements. Such activities may take a long time to complete.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
CHAPTER- II
C Language Introduction
C is a procedural programming language. It was initially developed by Dennis Ritchie
between 1969 and1973. It was mainly developed as a system programming language to write
operating system.

Some Facts about C Programming Language

 In 1988, the American National Standards Institute (ANSI) had formalized the C language.
 C was invented to write UNIX operating system.
 C is a successor of 'Basic Combined Programming Language' (BCPL) called B language.
 Linux OS, PHP, and MySQL are written in C.
 C has been written in assembly language.

Uses of C Programming Language

In the beginning, C was used for developing system applications, e.g. :

1. Database Systems
2. Language Interpreters
3. Compilers and Assemblers
4. Operating Systems
5. Network Drivers
6. Word Processors

C Has Become Very Popular for Various Reasons


 One of the early programming languages.
 Still, the best programming language to learn quickly.
 C language is reliable, simple and easy to use.
 C language is a structured language.
 Modern programming concepts are based on C.
 It can be compiled on a variety of computer platforms.
 Universities preferred to add C programming in their courseware.
Features of C Programming Language
 C is a robust language with a rich set of built-in functions and operators.
 Programs written in C are efficient and fast.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED

 C is highly portable; programs once written in C can be run on other machines with
minor or no modification.
 C is a collection of C library functions; we can also create our function and add it to the C
library.
 C is easily extensible.

Advantages of C
* C is the building block for many other programming languages.
* Programs written in C are highly portable.
* Several standard functions are there (like in-built) that can be used to develop programs.

* C programs are collections of C library functions, and it's also easy to add own functions
to the C library.
* The modular structure makes code debugging, maintenance and testing easier.

* Disadvantages of C
 C does not provide Object Oriented Programming (OOP) concepts.
 There are no concepts of Namespace in C.
 C does not provide binding or wrapping up of data in a single unit.
 C does not provide Constructor and Destructor.

The limitations of C programming languages are as follows:


 Difficult to debug.
 C allows a lot of freedom in writing code, and that is why you can put an empty line or
white space anywhere in the program. And because there is no fixed place to start or end the
line, so it is difficult to read and understand the program.
 C compilers can only identify errors and are incapable of handling exceptions (run-time
errors).
 C provides no data protection.
 It also doesn't feature reusability of source code extensively.

 It does not provide strict data type checking (for example an integer value can be passed
for floating data type)

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Q) Structure of C Program
A c program is collection of different modules / Functions. Each module performs their own
individual task.The output of all modules are put together to generate final output. The basic
structure of C program ANSI C follow is given below

Documentation section:-
 This is the section where the programmer gives the details of the program.
 Comments are used to provide details.
 Generally it includes the name of the program, the author of the program and other
details like date when the program wrote.
 C supports two type of comments 1. Single line comments
2. Multiple line Comments
Example:
1. Single line comments:
// this program calculates the sum of two matrices

2. Document / multiple line comments


/**
* File Name: first.c
* Author: siri

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
* Date: 09/08/2020
* Description: a program to display sum of tow matrix
* give proper input.
*/
Link section
 The link section provides instructions to the compiler to link functions from system
library.
 This can be done by including header files like #include<stdio.h>

Defination section

Here one can define all symbolic constants used in C program using define keyword, like#define
PI 3.148

Main function section

The main() is the starting point of nay C program.

The main is an independent module which performs some operations on data to accomplish a
task with in aC program. The main section contains two parts.

1. Declaration part: It is the place where all variable declarations are done.

2. Execution part:

 It contain instructions to the computer that cause it do some operations on data. Every
C program executable statement is terminated with semicolon.
 The execution part begins with the curly brackets and ends with the curly close
bracket. Both the declaration and execution part are inside the curly braces.

int main (void)


{
int a=10;
printf (" %d", a);
return 0;
}

Sub-Program Section

All user define functions are defined here.

Syntax : function function_name()


{

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Statement 1;
Statement 2;
………….
Statement n;
}

Q) Writing the first C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the
first c program.To write the first c program, open the C console and write the following code:

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello C Language");
5. return 0;
6. }

Line-1: #include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .

Line-2: int main() The main() function is the entry point of every program in c language.

Line-4: printf() The printf() function is used to print data on the console.

Line-5: return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.

Line-3&6: In C language, a pair of curly brackets define a scope and mainly used in functions
and control statements like if, else, loops. All functions must start and end with curly brackets.

Q) Compiling and Executing C Programs

What is a compilation?

The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source codeis error-free, then it generates the object code.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
The following are the phases through which our program passes before being transformed into
an executable form:

o Pre-processor
o Compiler
o Assembler
o Linker

1. Pre-processor:

The source code is the code


which is written in a text editor
and the source code file is given
an extension ".c". This source
code is first passed to the
preprocessor, and then the
preprocessor expands this code.
After expanding the code, the
expanded code is passed to the
compiler.

2. Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the
pre- processed code into assembly code.

3. Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file
in DOS is '.obj,' If the name of the source file is 'hello.c', then the name of the object file
wouldbe 'hello.obj'.
4. Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code
of our program.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Q) Files used in C program
A C program uses four types of files as follows:

Source Code File


 This file includes the source code of the program.
 The extension for these kind of files is '.c'. It defines the main and many more functions
written in C.
 main() is the starting point of the program. It may also contain other source code files.

Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions that
are shared between various source files. C provides us with some standard header files which
areavailable easily.
Common standard header files are:
i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more
than one function of the same file.
Object files
 They are the files that are generated by the compiler as the source code file is processed.
 These files generally contain the binary code of the function definitions.
 The object file is used by the linker for producing an executable file for combining
the object files together. It has a '.o' extension.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Executable file
 This file is generated by the linker.
 Various object files are linked by the linker for producing a binary file which will be
executed directly.
 They have an '.exe' extension.

Q) Using Comments in C
Comments in C language are used to provide information about lines of code. It is widely
used for documenting code. There are 2 types of comments in the C language.
1. Single Line Comments
2. Multi-Line Comments

Single LineComments
Single line comments are represented by double slash //.
Let's see an example of a single linecomment in C.

#include<stdio.h>
int main()
{
//printing information

printf("Hello C");
return 0;
}
Even you can place the comment after the statement. For example:
Ex: printf("Hello C");//printing information

Multi Line Comments


Multi-Line comments are represented by slash asterisk /* ... */. It can occupy many lines of
code, but it can't be nested.
Syntax:
/* code to be commented

*/

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Let's see an example of a multi-Line comment in C.
#include<stdio.h>
int main(){
/*printing
information Multi-
Line Comment*/
printf("Hello C");
return 0;
}

Q) Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There
are only 32 reserved words (keywords) in the C language. A list of 32 keywords in the c
language is given below:

Q) C Identifiers
C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc.
Rules for constructing C identifiers
 The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short, and easy to read.
Example of valid identifiers
total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers


 2sum (starts with a numerical digit)
 int (reserved word)
 char (reserved word)
 m+n (special character, i.e., '+')

Q) Basic Data Types:


Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it.

A data type defines a set of values and the operations on that can be performed on them.
Moreover a datatype tells to the compiler
1. What type of data the program can handle
2. How much memory is needed for that data?
3. What type of operations that can be performed on those data?

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
1. Basic Data Types
i) Void Data type
1. Designated by 'void' keyword.
2. Used in front of a function which does not return any value.
3. Used to create generic pointers.
ii) Integral Data type
The C language has three integral data types.
a) Boolean data type
 Used to represent two values 'true' or 'false'
 Designated by the keyword 'bool'
b) Character Data type
The characters are used to form words, numbers and expressions depending upon the
computer on which the program runs. There are two types of character types.
 Signed characters which occupies one byte in memory and range from -128 to 127
 Unsigned characters which occupies one byte in memory and range from 0 to 255
 The format specifier used is %c
c) Integer Data type:
An integer is a number without fractional part. C supports 4 different types of integer types.

Type Size in bytes Range Format specifier


Short int 1 -27 to 27-1 %hd
Int 2 -215 to 215-1 %d
Long int 4 -231 to 231-1 %ld
Long long 8 -261 to 261-1 %ud
int
d) Floating point type:
i) Real data type
real data type represents the real numbers; A number with decimal part.
ii) Imaginary data type
An imaginary number is used extensively in mathematics and engineering. An imaginary
number is a real number which is multiple of square root of -1

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
iii) Complex numbers type
A complex number is a combination of real and imaginary number.
2. Derived Data Types
Derived Data types are derived from the basic datatypes.
Examples: Arrays, functions, pointers
3. User Defined Data types:

C allows us to define our own data types such as structures and unions. These are called user
defined datatypes because the programmer or user creates them according to their needs.

Q) Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.

Declaring (or) Creating Variable


Each and every variable must be created before using in your c program. The
basic syntax is
Syntax: Data type variable_list;
Example: int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type


float f=20.8; char c='A';
The declaration tells to the compiler three things
The name of the variable
The type of the variable
The value of the variable.
Rules for defining variables
 A variable can have alphabets, digits, and underscore.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
 A variable name can start with the alphabet, and underscore only. It can't start with a digit.
 No whitespace is allowed within the variable name.
 A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Assigning Value (OR) Initialization of variable


A variable must be initialized before it can be used in your C program. Initialization is
nothing but storing values in variable. A variable can be initialized in two ways:
i) Static initialization:

We can initialize the variable at the time same time of declaration using assignment
operator (=).

int a=10,b=20;//declaring 2 variable of integer type


float f=20.8;
ii) Dynamic initialization:
In some programs the value of a variable is known when the program in execution or after
execution. This type of initialization is known as dynamic initialization.
Ex: C=a+b;
Types of Variables in C
There are many types of variables in c:
a) Local variable
A variable that is declared inside the function or block is called a
local variable. It must be declared at the start of the block.
b) Global variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
It must be declared above the block.
c) Static variable
d) Automatic variable
e) External variable

Q) Constant in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4,
"c programming" etc.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.


Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa

etc.Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", etc.

2 ways to define constant in C


There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor

1) C const keyword
The const keyword is used to define constant in C programming.
1. Ex: const float PI=3.14;
Now, the value of PI variable can't be changed.

Example:
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directivelater.
Syntax: #define token value

Example:
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}

Q) Operators in C
An operator is a symbol that tells the compiler to perform certain mathematical or logical
operations.
C is a rich set of operators it include all high level language operators as well as low level
language operators such as bitwise operators.
There are following types of operators to perform different types of operations in C language.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment and decrement operators
5. Ternary or Conditional Operators
6. Bitwise Operators
7. Assignment Operator
8. Special Operator

1. Arithmetic Operators
C provides all the basic arithmetic operators. They are shown in below table. The operators
+, -,* and /all work the same way as they do in other languages. These can operate on any
built- in data type allowed in C.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Operator Meaning
+ Addition
- Subtraction
* Multiplicat
ion
/ Division
% Modulus

i) 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.
In the below examples, if a and b are integers, then for a=14 and b= 4
we have the following results:A-b =10 A+b= 14
A*b= 56
a/b= 3 (decimal part truncated a%b = 2( remainder of division)
Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic; a real operand may assume values either in decimal (or) exponential notation
If x, y and z are floats, then we will have:
X= 6.0/ 7.0 = 0.8572

Y= 1.0/3.0 = 0.333
Z = -2.0 /3.0 = -0.6667
The operator % cannot be used with real operands.
Mixed – Mode Arithmetic: when one of the operands is real and the other is integer, the
expression is called a mixed mode arithmetic expression.
If either operand is of the real type, then only the real operation is performed and the
results are always a real number. Thus 15/10.0 = 1.5 where as 15/10 = 1.

2. Relational Operators:
The operators which are used to distinguish two values depending on their relationships. This
operator provides the relationship between two expressions. If the relationship is true it
returns1 otherwise 0.

Operator Meaning Example


< Less than 3<5 gives 1

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
> Greater than 7>9 gives 0
>= Less than or equal to 100>=100 gives 1
<= Greater than equal to 50>= 100 gives 0
3. Logical operators
Logical operators are used to combine expressions containing relational operators. The logical
operators are
Logical AND (&&): The logical and operator produces true value when both expressions aretrue.

A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1

Logical OR: The logical operator produces TRUE value when one the of expression is
trueotherwise zero.

A B A||B
0 0 0
0 1 1
1 0 1
1 1 1

Logical NOT: The logical not operator takes a single expression and produces opposite value.

A !A
0 1
1 0
4. Assignment Operator
Assignment operators are used to assign the result of an expression to a variable, the general format
of assignment statement is:
Variable = name expression;
a=10;
In addition ’C’ has a set of ‘shorthand’ assignment operators of the form.

V OP = exp;

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Where V is a variable, exp is an expression and OP is a C binary arithmetic operator. The
operator
OP = is known as the shorthand assignment operator.
Some of the commonly used shorthand assignment operators are shown below.

Statement with simple Statement with shorthand


Assignment operator Operator
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b

The use of shorthand assignment operators has three advantages:


1. What appears on the left hand side need not be repeated and therefore it becomes easier to
write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.
5. Increment and decrement operators / Unary operators
C allows two very useful operators not generally found in other languages. These are the
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;)
While ++m and m++ mean the same thing when they form statements independently, they
behave differently when they are used in expressions on the right hand side of an assignment
statement. Consider the following:
m = 5;
y = ++m;
In the case, the value of y and m would be 6. Suppose, if we rewrite the above statement as
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
m = 5;
y = m++;
then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the
operand and then the result is assigned to the variable on left. On the hand, a postfix operator
first assigns the value to the variable on left and then increments the operand.
6. Conditional operator
A ternary operator pair “?:” is available in C to construct conditional expressions of the form.
Exp1? exp2: exp 3 Where exp1, exp2, and exp3 are expressions.
The operator (? : )works as follows:
exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and
becomes the value of the expression.
If exp1 is false, exp 3 is evaluated and its value becomes the value of the expression.
Note that only one of the expressions (either exp2 or exp3) isevaluated.
For example, consider the following statements.
a = 10;
b = 15;
x = (a>b)? a : b;
In this example, x will be assigned the value of b.
7. Bitwise operators
C has a distinction of supporting special operators known as bitwise operators for manipulation
of data at bitlevel. These operators are used for testing the bits, or Lists the bitwise operators and
their meanings.

Operator Meaning
~ One’s complement 9 Bitwise AND)
>> Right shit
<< left shit
& Bitwise AND
! Bitwise OR
^ Bitwise XOR ( Exclusive OR)

8. Special Operators:
These are used for special purpose in C language these operators are used in pointers, structures
and unions etc. Some types special operators as
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
I ) unary operator
II) Comma operator
III) Size of operator
IV) Member selection operator
I) Unary Operator: Those that operators on a single operand. The unary operators
are ++, - -,(underscore), & (address operand),* (indirection operator), size of
operator and so on.
II) Comma Operator: When a no. of statement occurred in a C program having a
relationship betweenexpressions. Then we can write all expression are statements in
a single expression using comma (,) operator. The comma operator are also used in
variable declaration statement.
III) Size Operator: It is to display no. of bytes covered by a variable or an expression.

Ex: int a, b ;

B=size of (a); b contains 2


Iv) Member selection Operator: These operators are used in structures, unions and pointers.
These are ‘.’ And ‘->’.

Q) I/O Statements in C
Reading the data from the input devices and displaying the result on the screen are two major
task of program. To perform these operations user-friendly, C has a number of input-output
functions.
Formatted I/O functions:
1. Printf(): The printf() function prints all type of data values on output console.
The general form is Syntax: printf("format string", argument_list);
2. Scanf(): The scanf() function is used for input. It reads the input data from the console.
Syntax: scanf("format string", argument_list);
#include<stdio.h>
int main()
{
int number;
printf("enter a number:");
scanf("%d",&number);

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
printf("cube of number is:%d ",number*number*number);

return 0;
}
Unformatted I/O functions:
The unformatted I/O functions can be classified into three types: 1) String I/O 2) Character
I/O
3) File I/O
1) String I/O: These functions are used to read and print strings.
a) gets(): This function is used to read a string from the input console.
b) puts(): This is used to print a string on the output console.
2) Character I/O: These functions are used to read and print characters.
a)getchar(): This function reads character type data from the standard input device. It
reads onecharacter at a time.
b) putchar(): This function print one character at a time on the output console.
c) getch() getche(): These functions read any alpha numeric characters from the standard
inputdevices.
d) putchar(): This function prints any alpha numeric value on output console.

Q) Type conversion and Type casting.

1. Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
destination data type may be smaller than the source data type when converting the data
type to another data type, that’s why it is also called narrowing conversion.
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
(): is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
Type Casting example –
float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source) data type into byte(target)
data type.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
2. Type conversion : In type conversion, a data type is automatically converted into another data
type by a compiler at the compiler time. In type conversion, the destination data type cannot be
smaller than the source data type, that’s why it is also called widening conversion. One more
important thing is that it can only be applied to compatible data types.
Type Conversion example –
int x=30;
float y;
y=x; // y==30.000000.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
UNIT – II
Decision Control and Looping Statements
Introduction to Decision Control Statements– Conditional Branching Statements – Iterative
Statements –Nested Loops – Break and Continue Statement – Goto Statement
Functions: Introduction, Using functions – Function declaration/ prototype – Function
definition, Function call – Return statement – Passing parameters, Scope of variables, Storage
Classes, Recursive functions
………………………………………………………………………………

Q) Conditional Branching Statements


The conditional branching statements help to jump from one part of the program to another
depending on whether a particular condition is true or false. C provides three types of conditional
branching statements.
1. If statement
2. Switch statement
3. Conditional operator.

1)If statements: The if statement many be implemented on different forms depending upon
the complexity of condition tested.
a) Simple if statement
b) If-else statement
c) Nested-if statement
d) else-if ladder statement.

a)Simple if statement: If Statement in C language is a programming conditional statement


that executes a code segment over a condition, provided if it is true and valid. Below is
thesyntax and flowchart for if condition.

Syntax:
If(test condition)
{
Statement block;
}
Statement-x

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
The statement block is executed only if the condition is true and them followed by rest
of the program(statement-x) will be executed.
If the condition is false, the statement block is skipped and rest of the program is executed.

Example: Write a C program to check whether the given number is even or not.
#include<stdio.h>

int main()
{
int number=0; printf("Enter a number:");

scanf("%d",&number);

if(number%2==0)

{
printf("your number is %d and it is an even number", number);
}
return 0;
}
b) If-else statement
The If-else statement is an extension of simple if statement. The general form is

Syntax:
If(test-condition)
{
True block statements;
}
else
{
else block statements;
}
Statement-x
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
The if-else statement works as follow
 If test condition is true both true block statements and statement-x are executed.
 If test condition is false both the else block statements and statement-x are executed.
 In any case both true block and else block are not executed at a time. Example:

Write a C program to find biggest of two numbers using if-else statement.


#include<stdio.h>
void main()
{
int a, b, c;
printf(“ enter a,b, c values”);
scanf(“%d %d”, &a, &b);
if(a>b)
{
printf(“a is big”);
}
else
{
printf(“ b is big”);
}
getch();
}

c) Nested-if statement:
C language supports if-else-if statement to test additional conditions a part from the initial
condition. The general form is

if(test condition-1)
{
if(test condition-2)
{
statement-2
}
else
{
statement-3
}
}
else
{
statement-1
}
statement-x
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
The if-else-if works as follows
 Statement-1 is executed when condition isfalse.
 Statement-2 is executed when bothconditions are true.
 Statement-3 is executed when condition-1 is true and condition-2 is false.
 At a time one statement block will be executed followed by statement-x

Example: write a c program to find biggest of three numbers using nested-if statement.
#include<stdio.h>
void main()
{
int a,b,c;
printf (“ enter a, b, c values”);
scanf(“ %d %d %d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“ a is big”);
}
else
{
printf(“ c is big”);
}
}
else
{
if(c>b)
{
printf(“ c is big”);
}
else
{

}
}
printf(“ b is big”);
getch();
}

d) else-if ladder:
There is another way of putting ifs together when multipath decisions are involved. A
multipath decision is chain of ifs in which the statement associated with each else is an if. It
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
takes the following general form:

if(condition-1)

Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
…………….
. else
if(condition-n)
Statement-n;
else
default statement;
Statement-x

 This construct is known as the else if ladder.


 The conditions are evaluated from the top (of the ladder), downwards.
 As soon as a true condition is found, the statement associated with it is executed and
the control is transferred to the statement-x (skipping the rest of the ladder).
 When all the n conditions become false, then the final else contain the default-
statement will be executed.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Example: program on to display the examination result.
#include <stdio.h>
#include<conio.h>
void main ()
{
int marks;
printf(“%/n Enter the marks obtained: “);
scanf (“%d” , &marks);
if (marks>=75)

printf( “\n DISTINCTION”);


else if (marks>=60 && marks <75)
printf(“\n FIRST DIVISION”) ;
else if (marks >=50 && marks >60)
printf(“\n SECOND DIVISION”);
else if (marks >=40 && marks >50)
printf(“\n THIRD DIVISION);
else
printf (“/n FAIL”);

Switch Statement
C has a built in multi way decision statement known as a switch. The switch statement tests the
value of a given variable (or expression) against a list of case values and when a match is
found, a block of statements associated with that case is executed.
The general of the switch statement is as shown below

switch (variable)
{
case value1:
Statement block 1;

Break;
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
case Value 2:
Statement block2;
Break;
……………
……..

case value N :
Statement block N;
Break;
Default:
}
Statement X ;

In the syntax of the switch case statement, the break statement must be used at the end of each
case because if it were not used, then all the cases from the one met will be executed.
To summarize the switch case construct, let us go through the following rules:
 The control expression that follows the keyword switch must be of integral type
( i.e., either be an integer or any value that can be converted to an integer).
 Each case label should be followed with a constant or a constant expression.
 Case labels must end with a colon.
 The default label is optional and is executed only when the value of the
expression does not match with any labeled constant expression.

Example : program on to determine whether an entered character is vowel or not.


#include<stdio.h>
#include<conio.h>
void man ( )
{
char ch;
printf(“/n Enter any character:”);
Scanf (“%c”, &ch);
switch (ch)
{
case ‘ a ‘ :
printf (“/n %%c is a VOWEL”, ch);
break;
case ‘e’:
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
printf(“/n %c is a VOWEL”, ch);
break;
case ‘ I ‘:
Printf (“/n % c is a VOWEL “,ch);
Break;
case ‘o’ :
printf( “/n %c is a VOWEL”, ch);
break;
case ‘ u ‘:
printf (“/n%c is a VOWEL”,ch);
break;
default : printf (“%c is not a VOWEL”, ch);
}
getch( );
}
2. Conditional operator
The operator pair (?, :) is called ternary operator and it takes the following form

Expression1 is evaluated first if it is true expression2 is evaluated and becomes the value of the
value. Otherwise expression3 is evaluated and becomes the value of the expression.

#include<stdio.h>
void main()
{
int a,b,results;
printf(“ enter a, b values”);
scanf(“ %d %d”. &a, &b);
results=a>b?a:b;
printf(“ results=%d”, results);
getch();
}

Looping / Iterative statements in C


. When a single statement or a group of statements will be executed again and again in a program
then such type processing is called Loop (or iteration). The C programming language
contains 3 different programming statements for program looping.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
1. for Loop
2. While Loop
3. Do while Loop

1. for Loop
The for loop in C language is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like the array and linked list.
Syntax:
for(intitilization;condition;update statements)
{
body of the loop
}
 The initialization statement is executed only
once at the beginning of the for loop.
 Then the condition is checked by the
program. If the condition is false, for loop is
terminated.
 But if condition is true then the code/s inside
body of for loop is executed and then
update expression is updated. This process
repeats until test expression is false

Example:
#include<stdio.h>
void main ()
{
int i; for(i=0;i<10;i++)
{
int i = 20;
printf("%d ",i);
}
}
The braces {} are used to define the scope of the loop. However, if the loop contains only one
statement, then we don't need to use braces. A loop without a body is possible. The braces
work as a block separator,i.e., the value variable declared inside for loop is valid only for that
block and not outside.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Infinitive for loop in C

To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we
need to provide two semicolons to validate the syntax of the for loop. This will work as an
infinite for loop.

#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome to infinite loop");
}
}

2. While loop:

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the
code to be executed multiple times depending upon a given boolean condition. It can be viewed
as a repeating if statement. The while loop is mostly used in the case where the number of
iterations is not known in advance.

Syntax:

while(test expression)
{
body of the loop
}

 The test condition is evaluated and if the condition is


true, then body of the loop is executed.
 After execution of and if the condition of the body, the test condition is once again
evaluated and if it is true, the body is executed once again.
 This process continues until the test-condition finally becomes
false the control is transferred out of the loop and the body of the loop may have one or
more statements.
 If the test condition evaluate to false at the first time the statements are never executed
Example:
#include<stdio.h>
int main()
{
int i=1;
while(i<=10)
{
printf("%d \n",i);
i++;
}
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
3. do-while

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution
of several parts of the statements. The do-while loop is mainly used in the case where we need
to execute the loop atleast once. The do-while loop is mostly used in menu-driven programs
where the termination condition depends upon the end user.

Syntax:

do
{
body of the loop
}while(test condition);

 In this first body of the loop is executed and then the


condition is checked.
 If condition is true then body of the loop is
executed when condition becomes false then it
will exit from the loop.
 Note that semicolon must be at the end of the while.
Example:

#include<stdio.h>
int main()
{
int i=1;
do
{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
}

What are the differences between while and do-while loops?


A) There are many differences between while loop and do-while loop. Some important and
basic differences between them is as follows:

While loop:

1. In while loop the condition is tested first and then the statement are executed, if the
condition turns out to be true.
2. It is entry-controlled loop
3. Never execute loop if condition is false
4. There is no semicolon at the end of while statement

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Syntax:
while(condition)
{
Statements;
}

Do-While loop:
1. In do while the statements are executed for the first time and then the conditions are
tested. If the condition turns out to be true then the statements are executed again.
2. It is exit-controlled loop.
3. A do while is used for a block of code that must be executed at least once.
4. There is semicolon at the end of while statement.
5. Syntax:
do
{
Statements;
} while (condition);
Q) Nested loops

A loop within another loop is called nested loop. Consider a loop where the outer loop runs
‘n’ time and consists of another loop inside it. The inner loop runs ‘m’ times. Then the total
number of times the inner loop runs during program execution is m*n times.

Example: Write a C program to print the following pattern.

*
**
***
****
*****

#include<stdio.h>
void main()
{
int i, j;
for(i=0;i<=5;i++)
{
printf(“\n”);

for(j=1;j<=i;j++)
{
printf(“*”);
}
}
getch();
}

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Q) Break and continue
In various scenarios, you need to either exit the loop or skip an iteration of loop when certain
condition is met. So, in those scenarios are known as jumping out of the loop. There are two
ways in which you can achieve the same.

break statement

When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.
In case of nested loop, if the break statement is encountered in the inner loop then inner loop is
Exited.

#include <stdio.h>
int main()
{
int counter;
for (counter=1; counter<=10; counter++)
{
if(counter==5)
{
break;
}
printf("%dn", counter);
}
return 0;
}
Output: 1 2 3 4

Continue statement

Continue Statement sends the control directly to the test-condition and then continue the loop
process.
On encountering continue keyword, execution flow leaves the current iteration of loop, and
starts with the next iteration.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
#include <stdio.h>
int main()
{
int counter;
for (counter =1; counter<=10; counter++)
{
if(counter%2==1)
{
continue;
}
printf("%dn", counter);
}
return 0;
}

Output:
2 4 6 8 10

Q) goto statement

A goto statement has two uses


1. A goto statement can transfer the control to any place in a program; it is useful to
provide branching within the loop.
2. A goto statement is used to exit from deeply nested loops when a error occurs.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
 The goto statement is used to jump from one line to another line in the program.
 Using goto statement we can jump from top to bottom or bottom to top.
 To jump from one line to another line, the goto statement requires a label.
 Label is a name given to the instruction or line in the program.
 When we use a goto statement in the program, the execution control directly jumps
tothe line with the specified label.

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
UNIT II
Chapter-II (Functions)
Introduction – using functions – Function declaration/ prototype – Function definition
– function call –return statement – Passing parameters – Scope of variables – Storage
Classes – Recursive functions.
Introduction to functions:

In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or subroutine in other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

 By using functions, we can avoid rewriting same logic/code again and again in a
program.
 We can call C functions any number of times in a program and from any place in a
program.
 We can track a large C program easily when it is divided into multiple functions.
 Reusability is the main achievement of C functions.
 However, Function calling is always a overhead in a C program.

If you want use functions in your C program you must declare, call and define it.

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.

Syntax: return_type function_name(argument list);


Example: int sum( int a, int b);

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.

Syntax: function_name(argument list);


Example: sum(a,b);

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 noticethat
only one value can be returned from the function.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Syntax: return_type function_name(argument list)
{
Function body
}

Example:

function body

int sum(int a, int b)


{

// some lines here


}

Q) Types of functions:
A function is a self contained block that always reduces to single value. A function may
return or may not return a value. If a function does not return any value a void data type is
used in front of it’s name.

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(),gets(), puts(), ceil(), floor() etc.

2. User-defined functions: are the functions which are created by the C programmer, so
that he/she canuse it many times. It reduces the complexity of a big program and
optimizes the code.

User Define functions:

C allows defining our own functions to reduce the program complexity. A user defined
function containthree sections

1. Function declaration
2. Function call
3. Function Definition
Example: Write a C program to perform addition of two numbers using functions.
#include<stdio.h>
int sum( int a, int b);
void main()
{
int a,b;
printf(“ enter a, b values”);
scanf(“%d %d”, &a, &b);
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
sum(a,b);
getch();
}
int sum( int a, int b)
{
int result=a+b;
printf(“sum=%d”,result);
}
Predefined functions:

Unlike user defined functions, predefined functions can’t be declared and defined in your C
program; it can be done by including appropriate header file.

The only thing you should remember while working with predefined functions is that you
should call it by appropriate syntax.

#include <stdio.h>
#include<math.h>
void main()
{
int a=5, b=3,result;
results=pow(a.b);
printf(“ result=%”,result);
getch();
}
Q) Difference between actual parameters and formal parameters.

Parameters are the input values to any function. C language supports two types of parameters:
actual and formal parameters.

Actual Parameters: Actual parameters are present in function call. These are the original
values supplied to the function.
Formal parameters: Formal parameters are present in function definition. These are
duplicate values for actual parameters.

#include<stdio.h>
int sum( int a, int b);
void main()
{
int a,b;

printf(“ enter a, b values”);

scanf(“%d %d”, &a, &b); Actual Parameters

sum(a,b);
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
getch(); Formal Parameters
}
int sum( int a, int b)
{
int result=a+b;
printf(“sum=%d”,result);
}

Q) Function declaration/ prototype (OR) User Defined functions in C


(OR) Three categories of function.

A user defined function has to be developed by the user at the time of writing a program. Every
function has the following elements associated with it.

1. Function declaration
2. Function call
3. Function Definition
4. Function parameters
5. Return statement.
Function declaration / Prototype: Before using any user defined function in your C program,
they must be declared. This type of declaration is called function prototype.

A function prototype tells to compiler information such as name of the function, the return
value, type of the parameters. More generally a function declaration tells us what a function
can do.

The general format to declare a function is


Syntax: return_type function_name(argument list);
Example: int sum( int a, int b);
Function call: Function call is a postfix expression. The operand is the function name and operators
are parameter list. The general form to call a function is
Syntax: function_name(argument list);
Example: sum(a,b);

Function definition: The function definition consists of code of the function. It is made up of
two parts: the function header and function body.
Syntax: return_type function_name(argument list)
{
ffunction body

Example:

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
int sum(int a, int b)
{

// some lines here


}

The function header consists of three parts: return type, function name and parameters list.
Function parameters: Parameters are input values to a function.

C supports two types of parameters Actual parameters and formal parameters.

Return statement: The return statement is used to terminate the execution of a function and
returns controlto the calling function.

A C function may or may not return a value from the function. If you don't have to return
any value from the function, use void for the return type.

Example: Write a C program to find biggest of two numbers using functions.

#include<stdio.h> Function Declaration


int large(int a, int b);.
void main()
{
int a,b, big;
printf(“ enter a, b values”); Function call
scanf(“%d%d”,&a, &b);
big=large(a,b);
getch(); Function definition or called function
}
int large( int x, int y)
{

if(x>y)
return x;
else
return y;
}

Q) Parameter passing techniques or inter function communication.

When a calling function is called the called function will invoke and return the value to the
calling function. This process is called inter function communication or parameter passing.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Call by value or pass by value: In the call by value method, the called function creates a
supplicate variables to store the values of the argument passed to it. Therefore the called
function uses a copy of the actual parameters to perform its task.

If the called function is supposed to modify the values of the parameters passed to it; then
changes will not reflect in actual parameters. Because changes are done only on copy of the
actual parameters but not on original values.

#include<stdio.h>
void swap(int a, int b);
void main()
{
int a,b; printf(“%d%d”,&a,&b);
printf(“a,b values before swapping %d %d”, a,b);
swap(a,b);
printf(“a,b values after swapping %d %d”, a,b);
getch();
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}

Call by reference or pass by address: In call by reference method, the called function does
not create duplicate variables to store the values of arguments passed in it; instead it stores the
address of the actual parameters.
If any changes made in called function will automatically reflect in the calling function,
because the changes are done in the memory not to the values.
Example: Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *a, int *b);
void main()
{
int a,b;
printf(“%d%d”,&a,&b);
printf(“a,b values before swapping %d %d”, a,b);
swap(&a,*b);
printf(“a,b values after swapping %d %d”, a,b);
getch();
}
void swap(int *a, int *b)
{
int *temp;
*temp=*a;
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
*a=*b;
*b=temp;
}

Q) Categories of function: A function depending on weather arguments are


present or not whether a value is returned or not may belong to one of the
following categories.
1. Function without arguments and no return value
2. Function with no arguments and return value.
3. Function with arguments and no return value.
4. Function with arguments and return value.

1.Function without arguments and no return value: This type of function has no
parameters meaning that it does not receive any data from calling function. Similarly this type
of function will not return any value to calling function. Therefore no data transfer between
calling and called function.

#include<stdio.h>
void sum();
void main()
{
sum();
getch();
}
void sum()
{
printf(“ function with no arguments and no return value”);
}
Function with no arguments and return value: In this category there is no data transfer from the
calling function to called function. But there is a data transfer from called function tocalling
function.

#include<stdio.h>
void sum();
void main()
{
int result=sum();
printf(“%d”,result);
getch();
}
void sum()
{
int x, y;
printf(“ enter values of x,y”);
scanf(“%d%d”,&x,&y);
return(x+y);
}
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
2. Function with arguments and no return value: In this category there is data transfer
between calling function and called function but there is no data transfer from called function
to calling function.

#include<stdio.h>
void sum(int,int);
void main()
{
int a,b;
printf(“ enter a,b values”);
scanf(“%d%d”,&a,&b);
sum(a,b);
getch();
}
void sum()
{
int z;
z=x+y;
printf(“z value is=%d”,z);
}
Function with arguments and return value: In this category there is a bi-directional
transmission of data between calling function and called function.

#include<stdio.h>
void sum(int,int);
void main()
{
int a,b;
printf(“ enter a,b values”);
scanf(“%d%d”,&a,&b); int
result=sum(a,b);
printf(“ sum of two numbers is =%d”,result);
getch();
}
void sum()
{
int z;
z=x+y;
return z;
}
Q) Scope of variables in C
In C all constants and variables have defined scope. By scope mean that the accessibility
and visibility at different points in the program. A variable or constant in C has four types of
scopes.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
1. Local scope / block scope
2. Global scope / Program scope
3. Function scope
4. File scope.

1.Local scope / block scope: Local variables are visible within a block or function where they
are declared.They are not accessible to outside of the block. If a variable is declared within a
block then as soon as the control exit that block the variable will erased. Such variables are
known as local variables and it’s have local scope.

#include<stdio.h>
void main()
{
int i=0;
while(i<3)
{
int y=i;
printf(“ y value inside block is %d”,y);
i++;
}
printf(“ y value outside block is %d”,y);
getch();
}

2. Global scope / Program scope: C allows us to declare a variable at global declaration section
and use anywhere throughout the program. Such variables are known as global variables and
they are program scope or global scope.
#include<stdio.h>
int y;
void main()
{
int i=0;
while(i<3)
{
y=i;
printf(“ y value inside block is %d”,y);
i++;
}
printf(“ y value outside block is %d”,y);
getch();
}

Function scope: function scope indicates that a variable is active and visible from the beginning to
the end of the function. In C only the goto label have function scope. This means that the
programmer can’t have the same label name inside a function.

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
File scope: when a global variable is accessible until the end of the file, the variable is said to be
have file scope. To allow a variable have file scope, declare that variable with the ‘static’
keyword before specifying it’s data type.

Example: static int a=10;

A global static variable can be used anywhere in the file.

Q) Storage classes:

All variables in C must have a data type and storage class. A storage class tells to the compiler three
things

1) Where the variable would be stored


2) What is the initial value of the variable if it is not initialized?
3) What is the scope of the variable?

In C there are four types of storage classes

Automatic storage class


 The keyword “auto” is used for this storage class.
 All local variables have automatic storage class.
 It is default storage class in C.

Storage: memory
Default value: garbage value.
Scope: local scope
Life time: till the program control within the block / function.

Example:

#include <stdio.h>
int main()
{
int a;
//auto
char b;
float c;
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b,
and c.
return 0;
}

External storage class


 “extern” keyword is used for this storage class.
 All global variables have external storage class.
 An external variable can be declared many times but can be initialized at only once.

Storage: memory
Default value: zero
Scope: global scope
Life time: during entire program execution.

Example:

extern int a;
void main()
{
a=25;
printf(“%d”,a); // give 25
printf(“%d”,F1()); // gives 25
printf(“%d”,F2());// gives 25
getch();
} F1(
)
{
a=a+10;
return a;
} F2(
)
{
a=a+5;
return a;
}

Static storage class.


 The keyword “static” is used for this storage class.
 All local and global variables can be declared using static keyword.
 The variables defined as static specifier can hold their value between the multiple function
calls.

Storage: memory
Default value: zero
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Scope: global scope / local scope
Life time: Value of the variable remains hold between different function calls.

Example:

static int a;
void main()
{
a=25;
printf(“%d”,a); // gives 25
printf(“%d”,F1()); // gives 35
printf(“%d”,F2()); // gives 40getch();
}

F1( )
{
a=a+10;
return a;
} F2(
)
{
a=a+5;
return a;
}
Register storage class
 The keyword “register” is used for this storage class. All local variables have register
storage class.
 The variables which are frequently used in your C program like loop control variable can
bedeclared using register storage class.
 Since register access is faster compared to memory.
Storage: CPU Registers
Default value: garbage value
Scope: local scope
Life time: Till the program control within the block.

Example:

#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default valueof
a is 0.
printf("%d",a); }

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Q) Recursion
A recursion is a repetitive process where a function calls its self. Every recursive
function has two major cases: base case and general case.

Base case: In this case the problem is simple enough to be solved directly without making any
further call to the same function.

General Case: In this case first the problem at hand is divided into simple sub parts. Second the
function call sits self with subparts of the problem obtained in the first step. Third the result is
obtained by combining the solutions of simple subparts.

The following are the rules for designing recursive function

 Determine the base case.


 Determine the general case.
 Combine the base case and general case into a function.

Here is an example how to calculate the factorial of a number using recursion.

As the program solves each general case in turn the program can solve next higher general case
until it finally solves the most general case. That is the original problem.
Example: Write a C program to find the factorial of a given number using recursion.
#include<stdio.h>
int fact(int n);
int main()
{
int m,f;
printf(“ enter a number”);
scanf(“%d”,&n);
f-fact(n);
printf(“ factorial of given number is=%d”,f);
return 0;
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED

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