0% found this document useful (0 votes)
27 views74 pages

Bsc I Year I Sem Notes 2021-22

The document provides an overview of computer fundamentals, including definitions, characteristics, limitations, classifications, and components of computers. It explains the types of computers based on input and speed, as well as the anatomy of a computer, detailing hardware and software components. Additionally, it discusses memory hierarchy, operating systems, and the classification of programming languages.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views74 pages

Bsc I Year I Sem Notes 2021-22

The document provides an overview of computer fundamentals, including definitions, characteristics, limitations, classifications, and components of computers. It explains the types of computers based on input and speed, as well as the anatomy of a computer, detailing hardware and software components. Additionally, it discusses memory hierarchy, operating systems, and the classification of programming languages.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 74

S.R.N.

K GOVERNMENT DEGREE COLLEGE ,BANSWADA


PROGRAMMING IN ' C '

Chapter - 1
Computer Fundamentals
Q). What is computer? what are the characteristics of computer &
limitations of a computer?
Computer:- The term "computer" is derived from the word " compute"
which means to calculate.
computer is a group of electronic devices used for "data processing". Data
processing involves following four steps.
1. Reading data.
2. Storing data
3. Manipulating data
4. Delivering the data in the form of output.
characteristics of computers:-
1. Speed:- Computer processes the data at an un-imaginable speed. The
speed of the computer is in Nano-seconds.

2. Accuracy:-computer provides a high degree of accuracy. Every


calculation is performed with the same accuracy. The accuracy level is
determined on the basis of design of computer. The errors in computer
are due to humans and inaccurate data.
3. Diligence: computer can work for hours with any break or boredom. it
does not get tired. it can perform complex calculations with the same
speed and accuracy from the start till the end.
4. Versatility: Computers can be used to perform different types of
tasks. At one point of time you can type a document, the next moment
you can listen to a song or watch a video.
5. Reliability: we can always rely on the information given by a
computer.
6. Large storage capacity: computers can store very large amount of
data. various storage devices are also available which store the data
temporarily or permanently.
7. Programmable: The computers can be programmed to match our
requirements. They can be programmed to work automatically.
8. compactness : computers come in various sizes. The size of
computers is decreasing due to technology. We can operate the
computers from anywhere and at anytime.

Limitations of the Computer:


1. Lack of decision making power: computers cannot decide on their
own. They are dependent on human instructions.
2. Zero IQ: Computers are dumb machines with Zero IQ.
3. Needs Electricity: computers work on electricity. They work as long
as the power is supplied.
4. Heavily dependent on Humans: Computers cannot do anything on
their own. They are heavily dependent on human beings.

B.SC (MPCS) I Year I Sem 1 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

5. Security Issues: with the increasing technology, viruses, worms etc.


have developed which causes serious security threats.
6. Operational Costs: There are some costs involved like installation,
maintenance, training costs.
7. Lack of creativity: computers lack of creativity. They cannot sing,
dance or draw.

Q. Classification of Computers ? (OR) Explain the Types of


Computers?
Computers are classified based on the type of input, speed, size etc.
classification of computer is as follows:
1. Based on the input:
a) Analog computers
b) Digital computers
c) Hybrid computers

a) Analog computers: Analog computers are used to process analog


data. Analog data continuous nature . Such type of data includes
temperature, pressure, speed weight, voltage, depth etc . These
quantities are continuous and having infinite variety of values.
Examples:
 Thermometer
 Analog clock
 Speedometer

b) Digital computer: A digital computer works with digits to represent


numerals, letters or other special symbols. A digital computer can be used
to process numeric and non-numeric data. It can perform arithmetic
operations like addition, subtraction, multiplication and division and also
logical operations.
Examples:
 IBM PC
 Apple Macintosh
 Calculators
 Digital watches

c) Hybrid computers: A hybrid computer is a combination of digital and


analog computers. It combines the best features of the both types of
computers. Hybrid computers are used mainly in specialized applications
where both kinds of data need to be processed.
Examples:
 Hybrid computer is used in hospitals to measure the heartbeat of
the patient.
 Devices used in petrol pump.

2. Based on the speed and size


Generally we can divide t into 4 major categories.

B.SC (MPCS) I Year I Sem 2 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

1. Micro computers
2. Mini computers
3. Mainframe computers
4. Super Computers.

classification of computers:
1. Micro Computers: Personal computer is also named as Micro
Computer. Micro computers are comparatively small, Generally these are
found in classrooms, offices & homes. They include desktop, handheld,
Notebook computers.

* Desktop:- The most common personal computer model sized to fit on a


desk, with a separate unit for the CPU & for the monitor.
some of the Pc manufactures are APPLE, IBM, Dell......
*Notebook(LAPTOP):- This is the smallest computer available today. It is
handy and has very less weight. Hence it is portable. They can operate on
current or batteries.
2. Mini computers:- Minicomputer lies between mainframe & personal
computer. Minicomputer can handle more input & output than personal
computer. Although minicomputer is designed for a single user, many can
handle hundreds of terminals. They are used as network servers &
internet severs.
3. Mainframe Computers:- Mainframe computers are the largest
computers in usage. Mainframe computers are generally used in
organizations that require data exchange among several users. Mainframe
computer is very big servers, which has some sharable resource. The data
from the mainframe server is distributed to several dummy terminals, that
are connected to the server.
4. Super Computers:- Super computers are fastest and most powerful
computers today. They process huge amount of data. Super computer can
be used to design simulations such as demonstration of nuclear fusion.
The applications of super computer include weather forecasting, atomic

B.SC (MPCS) I Year I Sem 3 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

bomb designing, satellite communication & space ship detection. India's


first super computer is "PARAM" designed by C-DAC.

Q) Anatomy of a Computer?
A computer can accept input, process or store data and produce
output according to a set of instructions which are fed into it.
A computer system can be divided into two components they are
Hardware and Software.
 Hardware: Hardware is a physical components of a computer that
includes all mechanical, electrical, electronic and magnetic parts
attached to it. A computer consists of the following major
components:
 Input and output devices
 Central processing unit
 Memory unit
 Interface unit.
 Software: Software is a set of programs where program is set of
instructions . Software's are 2 types
 System software
 Application Software.
System Software:
The software that is used for the purpose of a system can be called
as system software. This is mainly used to run the computer and manage
the functionality of the computer. Different types of software's are given
below.

Device Driver: It allows computer devices such as keyboard and to


communicate with the system.
Compiler:
It converts the high level language ( ge program to low level language
Whole program at once).
Interpreter: It converts high level program to low level program (line by
line).

Application Software: Application software tells the computer how to


perform tasks the user requires. Application software is some software
that is specially designed to suit the requirements of business purpose or
personalized or customized purpose.
EX: Bank management, Hotel management software etc.

Q) Memory Hierarchy?

Memory unit is the storage area in the computer. Computers can store
very huge amount of the data. Computers can store not only text, but
also images, graphics, videos, audio. All these are stored in the form of
bits (0 or 1). The computer memory is measured in terms of number of
bits.

B.SC (MPCS) I Year I Sem 4 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Units of Computer Memory Measurements


1 Bit = Binary Digit
8 Bits = 1 Byte
4 Bits = 1 Nibble
2 Nibbles = 1 Byte
1024 Bytes = 1 KB(Kilo Byte)
1024 KB = 1 MB(Mega Byte)
1024 MB = 1 GB(Giga Byte)
1024 GB = 1 TB(Terra Byte)
1024 TB = 1 PB(Peta Byte)
1024 PB = 1 EB(Exa Byte)
1024 EB = 1 ZB(Zetta Byte)
1024 ZB = 1 YB(Yotta Byte)

It has 2 sub units.


1. Primary Memory
2. Secondary Memory.

1. Primary Memory:-
 Primary memory is also called as main memory.
 Primary memory holds only those data and instructions on which
the computer is currently working.
 It is volatile (data gets lost when power is switch off.

Types of Primary Memory:


1. RAM: 1. RAM stands for Random Access Memory.
2. When we enter the data, the data first stored in RAM.
3. When system is switched off the information in the RAM is lost.
4. RAM is a temporary (or) Volatile Memory.
5.The Speed of computer depends on speed of RAM.
ex:512MB, 1 GB, 2GB etc.
Types of RAM:
1. SRAM: Static RAM uses multiple transistors for each memory cell. It is
used primarily for cache.

B.SC (MPCS) I Year I Sem 5 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

2.DRAM: Dynamic RAM has memory cells with a paired transistor and
capacitor. It requires constant refreshing.
2. ROM: 1. ROM stands for Read only memory.
2. The data stored in ROM cannot be changed and it is static.
3. When we switch off the system it will not affect the data in the ROM.
4. ROM contains a special program called "BIOS" (Basic Input Output
System).
5. ROM Memory is used to start up your computer.
6. It is permanently in-built, at the time of its manufacturing.
Types of ROM:
1)PROM: Programmable Read only memory on which data can be written
only once. Once programmed, PROM becomes ROM. PROM is a nonvolatile
memory.
2.EPROM (Erasable Programmable Read only Memory): In EPROM,
the information can be erased and reprogrammed using special PROM. A
EPROM can be programmed many times. But an ultraviolet light is used to
erase the contents of the EPROM.
3.EEPROM ( Electrically Erasable Programmable Read only
Memory): EEPROM is recently developed type of memory. It does not
require ultraviolet light to erase its content. It can be erased by exposing
it to an electrical charge.
Cache Memory: 1. It acts as a buffer between the CPU and main
memory.
2. Cache memory is faster than main memory.
3. It consumes less access time as compared to main memory.
4. When we enter some data, the data first moves into RAM & then CPU. It
is time consuming to collect the data every time from RAM. To avoid this,
Cache memory is included.

2. Secondary Memory: This is supporting memory for the computer.


These are used for storing data / instructions permanently. They are non-
volatile memory.
Types of Secondary Memories:
1.Magnetic devices:
1. Hard Disk: Hard disk is a magnetic disk on which you can store
computer data. It is essentially based on magnetic properties. The
magnetic disk consists of high speed rotating surface, it is called platter.
Such platters are placed one after the other, without touching each other.
Each plotter is divided into tracks and tracks are divided into sectors. The
data elements are stored in these sectors.
Advantages: .1.They are quickly accessible.
2. They support direct access.
3. They have large storage capacity.
4. capacity of hard disk is 10GB, 20 GB, 40 GB, 80 GB etc.
2.Magnetic Tapes:
1. It is coated with millions of iron particles that store the data.

B.SC (MPCS) I Year I Sem 6 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

2. They allow only sequential access of data.


3.Floppy Disk:1. Floppy disk is similar to a magnetic disk.
2. The capacity of a 3.5 inch floppy is 1.44 mega bytes.
3. It is low cost device.
4. it is portable.
2. Optical storage devices:
1. CD- ROM: CD-ROM stands for Compact Disk - Read only Memory. It is
an optical disc used to store digital data. It is flat and round. It uses the
same technology as a musical CD does. A laser reads lands & pits from
the surface of the disk. It stores 650 MB of data.
2. DVD:(Digital Video Disk): DVD is a high density optical disk storing
large amounts of data. It is used to store audio - visual material. It has the
capacity to store 4.7 GB.
3.WORM ( Write Once Read Many): With a WORM disk drive, you can
write data onto a WORM disk, but only once, after that, WORM disk
behaves like CD- ROM.

Q)What is an Operating System? What are the functions of an


OS?
 Operating System is system software that acts like an
interface between user and the system.
 It makes a computer to actually work.
 operating system organizes and controls the hardware.
 The purpose of operating system is to provide an
environment in which a user can execute programs in a
convenient and efficient manner.
 It helps in booting up a computer and running other
applications.
 Examples: Windows, Linux, Unix, DOS etc.

Functions of an operating system:


1. Memory Management: OS manages computer memory effectively. It
allocates, reallocates and keep track of memory usage.
2. Process Management: All the processes given by the user are
handled by the OS.
3. File Management: The OS also handles the organization and tracking
of files and folders. It can performs various tasks such as creating a files
and directories, renaming the file , copying and moving the files and
deleting the files.
4. Resource Management: Os controls all the resources of computer
very efficiently. Those are file, memory, I/O and CPU.
5. Security and Protection: OS Protects resources of the system. It
allows a password to be set by the users. OS uses user authentication, file
attributes like read, write, encryption and backup of data to provide basic
protection.
6. User Interface: OS provides an interface between the computer user
and the computer hardware.

B.SC (MPCS) I Year I Sem 7 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

7. System Recovery and Backup: OS recovers the computer from any


kind of hardware and software failure. It provides the backup facility.
8. Command Interpretation: OS enables the computer to understand
the command given by the user
Chapter - 2
Program Fundamentals

Q) Generation and classification of programming languages? (or)


Explain about the Computer Languages?

Ans) Communication between two persons we need a language through


which persons can express their feelings . Similarly, when we want to
make communication between user and computer, user wants to give any
instructions to computer the user needs a language and that language is
known as computer language.

Computer languages are the languages through which user can


communicate with the computer by writing program instructions.

Classification of languages:

Computer
Languages

Low Level Assembly High Level


Language Language Language

Low Level Language: Low level language is only language which can be
understood by the computer. Binary Language is an example of Low
Level Language. Low Level Language is also known as Machine Language.
The binary language contains only two symbols 1&0. A computer can
directly understand the binary language . CPU directly understands the
binary language instructions, it does not require any translator.

Advantages:
 A computer can easily understand low level language.
 Low level language instructions are executed directly without any
translator.
 Low level language instructions require very less time for their
execution.
Disadvantages:
 Low level language instructions are very difficult to use and
understand.
 In low level language, there is more chance for errors and it is very
difficult to find errors, debug and modify.

B.SC (MPCS) I Year I Sem 8 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Assembly Language: Assembly language is an example of middle level


language. In assembly language, we use predefined words called
mnemonics. Binary code instructions in low level language are replaced
with mnemonics and operands in middle level language. But computer
cannot understand mnemonics, so we use a translator called Assembler to
translate mnemonics into binary language.

Advantages:
 Writing instructions in middle level language is easier than writing
instructions in low level language.
 Easy to understand, find errors and modify.
Disadvantages:
 Assembly language needs to be translated into low level language.
 Assembly language executes slower compared to low level
language.
High Level Language: High level language is a computer language which
can understood by the users. Every high level language have set of
predefined words known as keywords and set of rules known as syntax to
create instructions. We use compiler or interpreter to convert high level
language to low level language.

Advantages:
 Writing instructions in high level language is more easier.
 High level language is more readable and understandable.
 Easy to understand, create programs, find errors and modify.
Disadvantages:
 High level language needs to be translated to low level language.
 high level language executes slower compared to middle and low
level languages.

Q) Compiling, Interpreting , Loading and Linking of a Program?

Ans) There are three basic phases occurred when we execute any C
program.
 Preprocessing
 Compiling
 Linking

Preprocessing Phase:
A Pre-processors a program that accepts C code with preprocessing
statements and produces a pure form of C code that contains no
preprocessing statements ( like #include).

B.SC (MPCS) I Year I Sem 9 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Compilation Phase:
The compiler accepts a preprocessed output file from the
preprocessor and produces a special file called object file. Object file
contains machine code generated from the program.

Linking Phase:
The link phase is implemented by the linker. The Linker is a process
that accepts as input object files and libraries to produce the final
executable program.

Execution Process of a C Program:


We need to Run executable file. To run a program we press
CTRL+F9. The CPU performs the task according to the instructions written
in that program and place the result into user screen.
Then we press ALT + F5 to open user screen and check the result of
the program.

Q) Write about Creating and Running of C Program? (or)


Developing and Execution of program?

Step1 Create Source Code Write in editor save with .C extension

Step2 Compile Source Code Alt+F9

Step3 Run Executable Code Ctrl+F9

Step4 Check result Alt+F5

Step1:- Creating Source Code: Source code is a file with C programming


instructions in high level language. To create source code, we use any
text editor to write the program instructions.
Step2:- Compile Source Code (Alt+F9): Compilation is the process of
converting high level language instructions into low level language
instructions. We use the shortcut key Alt+F9 to compile a C Program in
Turbo C.
Whenever we press Alt+F9, the source file is going to be
submitted to the compiler. The compiler first checks for the Errors. If
there are any Errors then compiler returns List of Errors, if there are no
errors then the Source code is converted into object code and stores it
as file with .Obj Extension.
Step 3:- Executing / Running Executable File (Ctrl+F9): After Completing
compilation successfully, an executable file is created with .exe
extension. We use a shortcut key Ctrl+F9 to run a C program, the .exe
file is submitted to the CPU. The result generated from the execution is
placed in a window is called User Screen.

B.SC (MPCS) I Year I Sem 10 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Step 4:- Check Result (Alt +F5): After running the program, the result is
placed into User Screen. We use the shortcut key Alt +F5 to open the
user screen and check the result.
Chapter 3
Algorithms
Q) What is an Algorithm and analysis of an Algorithm?
Algorithm: A step by step method of solving a problem or
making decisions. It is used for solving certain mathematical
problems.
An algorithm is a finite set of well-defined instructions for
accomplishing some task. Which given an initial state. Will
terminate in a defined end state.
Characteristics of Algorithm:
1. Input: Every algorithm must take zero or more number of
input values from the external.
2. Output: Every algorithm must produce an output as
result.
3. Definiteness: Each step of an algorithm must be
precisely defined; the actions to be carried out must be
rigorously and unambiguously specified for each case .
4. Finiteness: For all different cases the algorithm must
produce result within finite number of steps.
5. Effectiveness: Every instruction must be basic enough to
be carried out and also must be feasible.
DIFFERENT WAYS OF STATING ALGORITHMS:
Two popular tools used the representation of algorithms
1. Pseudo Code
2. Flowchart
3. Step form
Pseudo Code: is a method of describing computer
algorithms using a combination of natural language and
programming language.
Flow Chart: are written with program flow from the top of a
page to the bottom. Each command is placed in a box of the
appropriate shape and arrows are used to flow of program.

B.SC (MPCS) I Year I Sem 11 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

STEP-FORM ALGORITHM:
In the step form representation, the procedure of solving a problem
is stated with written statements. Each statement solves a part of
problem and these together completes the solution. The step-form
uses just normal language to define each procedure. Every
statement , that defines an action, is logically related preceding
statement.
Q) Strategy for Designing Algorithm?
Now that the meaning of algorithm and data has been
understood, strategies can be devised for designing algorithms.
Investigation step:
 Identify the output needed.
 Identify the input variables available.
 Identify the major decisions and conditions.

B.SC (MPCS) I Year I Sem 12 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

 Identifies the processes required to transform inputs into


required outputs.
Top down development Step:
 devise the overall problem solution by identifying the major
components of the system.
Q) Structured Programming concept?
Structured Programming can be defined as a
 Top-down analysis for program solving.
 Modularization for program structure and organization.
Top-down analysis:
Top-down analysis is a method of problem solving and problem
analysis.
 The essential idea is to subdivide a large problem into several
smaller tasks or parts for ease of analysis.
 Top-down analysis, simplifies or reduces the complexity of the
process of problem solving.
 There are two essential ideas in top-down analysis
 subdivision of a problem
 hierarchy of taks.
Modular programming:
 Modular programming is a program that is divided into
logically independent smaller sections, which can be written
separately.
 Separate independent units are called modules.
 A module as a whole has unique name.
 complex program may be divided into simpler and more
manageable elements.

B.SC (MPCS) I Year I Sem 13 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Chapter - 4
Basics of C

Q) What is ‘C’ & History of the C-Language?

Ans) Before 1960’s COBOL, FORTRAN languages are used COBOL for
commercial application. FORTRAN for Engineering & scientific
applications. At this stage people started thinking that instead of learning
& using so many languages. Each for a different purpose why not use only
one language which can program. All possible applications then
international committee come out with one language called ALGOL-60 but
it never became popular because it is too abstract & too general CPL was
introduced. C language was developed by “ Dennis Ritche” in 1972 by
introducing the features of B & BCPL adding some more features in
1972 at AT & T’s BEEL Laboratory of USA.

History of C:
Year Language Purpose
1960 ALGOL Special purpose
1963 CPL Special Purpose
1967 BCPL Special Purpose
1970 B Special Purpose
1972 C All Purpose

Q) Parts of C program?Developing programin


c ,parts of c program

Example:
#include<stdio.h>
main()
{
printf("Hellow world");
getch();
return();
}

Output:
Hello world

B.SC (MPCS) I Year I Sem 14 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

#include <stdio.h>: This command is preprocessor directive in C that


includes all standard input-output files before compiling any c program so
as to make use of all those functions in our program.

void main(): This is the line from where the execution of program starts.
The main function starts the execution of any C program.

{ (Open bracket): This indicates the beginning of any function in a


program ( Here it indicates the beginning of the main function).

Printf("HellowWorld"): The printf ( ) command is included in the stdio.h


library, which helps to display the message on the output screen.

getch( ) : This command helps to hold the screen.

return 0: This command terminates the c program and returns the null
value, that is 0.

} ( Closing bracket): This indicates the end of the function.

Q) what is a ‘C’ structure?

A) The ‘c’ language program structure classified into different sections.


The sections are

Documentation section

Link section

Definition section

Global Declaration

Main()
{
Declaration part;
Executable Part;
}
Sub Program Section
{
Statements
}

Documentation Section:- Documentation Section consist of the


comment lines giving the name of the program, author name and other
details in which the programmer would like to use later.
Ex;- /* To find the area of circle */

B.SC (MPCS) I Year I Sem 15 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Link Section:-
The link section provides instruction the compiler to link the library
functions from library to the main() function. Linking is a process of
putting together the library files and functions that are required by the
program.
Ex:- If the program is using “exp” then the object code of the program
should be brought from the system given by <math.h> and should be
linked to the main program.
#include<stdio.h> instructs the compiler to search for a file “stdio.h”
from the system library and the contents of the header becomes the part
of source file.

Definition section:- The definition section defines all the symbolic


constants be represented with “#define”.. These instructions define
values to symbolic constants for use in the program whenever a symbolic
name is encountered by the compiler it will substitutes the values
associated with the names automatically.

#include<stdio.h>
#define pi 3.14
Main()
{
……….;
……….;
}

Global declaration section:-


There are some variable that are used in more than one function
and also can be used by any function in the program. Such variable are
called as “GLOBAL VARIABLES” and should be declared in the global
declaration i.e., the outside of all functions.
Ex:-
#include<stdio.h>
int a;
float b;
main()
{
………..;
……….. ;
}

Main function section:-


‘C’ program is nothing but a collection of one or more functions.
The MAIN FUNCTION is a special function used by the “C” compiler to
instruct the computer about the starting of a program. Every program
must have exactly one main function . The empty part of parenthesis

B.SC (MPCS) I Year I Sem 16 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

immediately following the main function indicates that the function main()
has no arguments or parameters.
The main function contains two parts
1. Declaration pat.
2. Execution part.

Declaration part:-
The declaration part declares all the variables used in the
executable part and there must be at least one statement in the
executable part. These two parts must appear between an opening brace
and should end with a closing brace. Hence the program execution begins
at the opening brace and ends with a closing brace.
Ex:-
#include<stdio.h> link section
#define pi 3.14 definition section
Main() main section
{
int a; declaration part
float b;
: executable part
}

Sub program section:-


The sub program section contains all the user defined functions.
which are to be called by the main function user defined functions are
generally placed immediately after the main function.
Main()
{
Statement1;
Statement2;
Add();
}
Add()
{
Statement3;
Statement4;
}

Q) Write short note on Header File? or preprocessor in C?


Header files contain definitions of functions and variables, into
any c program by using the preprocessor #include statement. Header file
have an extension ".h" which contains C function declaration and macro
definition.
When we want to use any function in our c program then first
need to import their definition from C library, for importing their
declaration and definition we need to include header file in program by
using #include.

B.SC (MPCS) I Year I Sem 17 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Each header file contains information for a particular group of


functions. Like stdio.h header file contains declarations of standard input
and output functions available in c which is used for get the input and
print the output. Similarly, the header file math.h contains declarations of
mathematical functions available in c.
Ex: #include<stdio.h>, #include<Math.h>, #include<string.h>

Q)symbolic constant (or) simple macro (or) #define:-

Ans) A symbolic constant is a name that substitutes for a sequence of


characters. The characters may represent a numeric constant a character
constant as string constant
Thus a symbolic constant allows a name to appear in place of a
numeric constant or a string. when a program is compiled each
occurrence of a symbolic constant is replaced by its corresponding
character sequence. a symbolic constants are usually defined at the
beginning of a program.

Ex:- # define name text


# define pi 3.1459
# define true 1
#define false 0

Q) Write short notes on comments in 'C'?


Generally Comments are used to providethe discription of the
program and about the logic written in the program.
There are two types of comments
1. Single line comments.
2. Multiple line comments.

Single line Comments: It is represented with //


Multiple line Comments: : It is represented with /* .............. */.

Q) What are the Character Set of C-Language?


Ans) There are so many characters used in C programming. A program
requires all these when designing it. The character set of ‘C’ is as follows:
1) Alphabets: upper case letters A..Z & Lower case letter a ..z are
allowed.
2) Digits: 0..9 are allowed
3) Special Characters: +,-,*,/,%,^,%,$,#,@,!,?,>,<,”,:,;,|,{,},[,] etc are
allowed.

Q) Define the ‘C’ Tokens?


Ans) C tokens include identifiers, keywords, variables, constants,
operators.

B.SC (MPCS) I Year I Sem 18 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Auto Double Int static


break Else Long typedef
case Enum register union
char Extern return Unsigne
d
const Float Size of void
continue For short volatile
default go to switch while
Do If struct no alias
C Tokens

Keywords Constants Identifiers Variables Operators

Keywords: Keywords are the reserved word. Each keyword has a


different meaning. These reserved words cannot be used as variable
names or function names. C has 32 keywords. They are listed below:

Identifier:-

Identifiers refer to the user defined names of program elements such


as variables, functions and arrays.

Rules for constructing the identifiers.

 The names of identifiers consist of sequence of letters and digits


with a letter as a first character.
 Both uppercase and lowercase letters are permitted. Lowercase
letters are commonly used.
 Blank spaces and special symbols are not permitted to construct
the identifier.
 The underscore character is permitted in identifiers. It is usually
used as a link between two words in long identifiers.

B.SC (MPCS) I Year I Sem 19 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Constants/Literals:
Constant is a value that can be stored in the memory and cannot be
changed during the execution of the program. There are three types of
constants.

constants

Numeric constant Character constant String constant

Integer constant Real constant

Numeric Constant : Numeric Constants are numeric digits which may or


may not have decimal point. The rules of the numeric constants are as
follows.

1. Numeric constant must have at least one digit.


2. No commas or spaces are allowed with in the numeric constant.
3. Numeric constants can either be positive or negative. By default
sign is always positive.
There are two types of numeric constants.
1. Integer Constant: Integer constants are whole numbers which has
no decimal point(.).An integer type of variables can hold integer
constants.
Ex:- int x=30.
2. Real constant: floating point constants are the numbers which
hold the decimal point. A float variable can hold float constants.
Ex:-float x=5.5,y=6.7;
3. Character Constant : A character variable can hold only one
character. Character
constant must be enclosed in single quotes.
Ex:- char a=’A’;
4. String constant : String constant is a character array that can hold
string values. Strings must be enclosed in double quotes.
Ex:- char x[]=”Govt degree & pg college,bhadrachalam”.

Q) What is variable?
A variable is a user defined word it has some storage area
depends on data type and it’s value will be changed during the
program execution.
The declaration of variable is
Data type variable1,variable2,……,variable;

Rules:

B.SC (MPCS) I Year I Sem 20 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

 It is a combination of letters and digits and starts with a letter.


 The length of the variable is up to 32 character. However the
length normally more than 8 characters.
 The variable should not be a reserve word.
 Special symbols, commas and blank spaces are not allowed
except underscore.
They are different type of variables are available in c language.
1.Integer variable 2.Float variable 3.Character Variable.

1. Integer Variable:-
Rules of integer variable
a) It should be the value.
b) It can’t accept any decimal values and special character.
c) The integer variable can occupies 2 bytes of memory location.
d) The range is -32,768 to +32,767.
e) It can take automatically positive sign.

2. Rules of float variable


a) It should be the value.
b) It can accept decimal values and it can’t accept special
character.
c) The float variable can occupies 4 bytes in memory location.
d) The range is -3.4*e-38 to +3.4*e+38
e) It can take automatically positive sign.

3. Rules for the character variable:


a) To give any character in program then it should have with in
the
single codes.
b) It can occupy 1 byte in memory location.
c) The range is -128 to +127.

Q) what are the data types available in ‘C’?

Ans) C supports different types of data, each of which may be


represented differently within the computer's memory ANSIC supports
4 types of data. They are

B.SC (MPCS) I Year I Sem 21 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

DATATYPES

PRIMARY DERIVED USERDEFINED EMPTY


DATATYPES DATATYPES DATATYPES DATATYPE

INTEGER ARRAYS ENUMERATED VOID

FLOAT FUNCTIONS TYPEDEF

DOUBLE POINTERS STRUCTURES

CHARACTER UNIONS

Primary data types:-

All C compilers support four fundamental data types


integer,character,float,double.
Integer:- The integer occupies 2 bytes in memory and the range of
values of integer is -32,768 to +32,767. The integer may be short int, long
int, signed and unsigned. The declaration of integer type data is “int”.
Ex:- int a,b,x;
Float:- A float occupies 4 bytes in memory and range from -3.4e-38 to
+3.4e+38. The declaration of real type is float.
Ex:- float a,b,z;
Character:- A single character can be defined with the help of a
character type data stores 8 bits or byte. The single character range is -
128 to +127.
Ex:- char ch,a,b;
Double:- This type of data holds real type numbers. It stores 8 bytes. This
range is -1.7e-308 to +1.7e+308.
Ex:- double ch,c,d;

Data type Key wordNo. of Range of Conversion


bytes values specifier
Character Char 1 byte -128 to +127 %c
Integer(or) signed int Int 2 bytes -2-15 to +2+15 %d
Unsigned integer Unsigned int 2 bytes 0 to 65535 %u
Short integer Short int 1 byte -128 to +127 %h
Unsigned short Unsigned short 1 byte 0 to 255 %u
integer int 4 bytes -2,147,483,648 %ld
Long integer Long int to
+2,147,483,648
Float Float 4 bytes -3.4e-38 to %f
+3.4e +38

Double Double 8 bytes -1.7e-308 to %lf


+1.7e+308

B.SC (MPCS) I Year I Sem 22 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

2.user defined data types:-


Which data types are created by the user requirement that data type are
called user defined data types.
1. Type def
2. Enumerated type data.
3. Structures & Unions

1. Type def:- Type definition allows users to define an identifier that


would present an existing data type. The user defined type data
identifies can be used later to declare the variables.
Ex:- type def int name;
Type def float college;

2. Enumerated data type:- The identifier is a user defined


enumerated data type which be used to declare the variable that
can have one of the values enclosed in parenthesis. The general
form of enumerated data type is given by
Enum id{v1,v2,…..vn}
Here the enumerated variables are having the values. Hence the
following assignments possible.
Value1=value3;
Value3=value2
Ex:- enum day{mon,tue,wed,thu,fri,sat,sun};

3.Derived data type:- When created derived data type then that derived
data types derived in memory location. The derived data type are arrays,
functions, pointers .
Array: Set of related data items is called Array. It can share a common
name. The Array variable start from 0th location in memory. The array
each cell can be created be separate address value.
Function: A Function is reusable block of statements, which is used to
perform a specific task. Generally C program is divided into basic building
blocks called C functions. C function contains set of instructions enclosed
by " { }" which performs specific operations in c program.
Pointer: A pointer is a variable. It contains the memory address of the
another variable and is declared as the pointer type.

4.Empty data type:- which data type are created by empty space in
memory location that data types are called empty data type.

Q)Explain different types of operators used in c?

Ans) Which is operate any two operands that type of symbol is called
operator.
The operators are used in programs to manipulate the data throw the
variables.
The following operators are provided in c language.

B.SC (MPCS) I Year I Sem 23 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

1. Arithmetic operator.
2. Relational operator.
3. Logical operator
4. Assignment operator
5. Increment and decrement operator.
6. Conditional operator.
7. Bitwise operator.
8. Special operator.

1.Arithematic operator:-Which operators are used for mathematical


purpose that
type of operators is called “Arithmetic operator”. These are used to
perform
arithmetic operations such as addition, subtraction, multiplication,
division and
modulo etc.
Operator Purpose example
+ Addition A+B
- Subtraction A-B
* Multiplication A*B
/ Division A/B
% Modular A%B
2. Relational Operators:-
The relation operators are used to compare two expressions
or operands, An expression which contains relational operators such a
expression is called relational expression. The relational operators are
Operator Purpose example
s
> Greater than A>B
< Less Than A<B
>= Greater than or A>=B
equal to
<= Less than or equal to A<=B
== Equal to A==B
!= Not Equal to A!=B
3.L ogical Operators:-
The logical operator which combines two or more relational
expressions into one expression. The logical operators are.

Symbol Meaning
&& AND
|| OR
! NOT

When two conditions are combined by logical AND then the resultant
condition becomes true if both conditions are true, otherwise the condition
is false.

B.SC (MPCS) I Year I Sem 24 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

When the two conditions are combined by the logical operator OR then
the result condition is true if any one of the condition is true otherwise the
resultant condition is false.

Condition 1 Condition2 Condition1 Condition


&& 1 ||
Condition2 Condition
2
True True True True
True False False True
False True False True
False False False False

4.Assignment operators:-
An assignment operators is used to assign a value or
expression to a variable. The most commonly used assignment operator
is “=”.
Syntax:-
Variable=Value(Or) Expression;
Ex:-
int i=5;
float a=5.5;
int c=a+b;
C contains the following assignment operators +=,-=,*=,/=,%= etc,

Ex:- a+=10 =>a=a+10


a-=10 => a=a-10
a*=10 => a=a*10
a/=10 => a=a/10
a%=10 => a=a%10

5.Increment And Decrement Operator:-


C has tow very useful operators not generally found in other
languages. These are the increment and decrement operators. The
operator ++ is called as increment operator and – is called as decrement
operator. The ++ operator add 1 to the operand and – used to subtract 1
from operand .
The are two formats of increment operator. They are pre
increment and post increment. The format of pre increment is
++ variable;
The format of post increment is
Variable++;
There is no difference for pre increment and post increment if these
statements are individual. There are tow formats of decrement operator.
They are pre decrement and post decrement. The format of pre
decrement is
--variable;

B.SC (MPCS) I Year I Sem 25 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

The format of post decrement is


Variable--;
There is no difference for pre decrement and post decrement if these
statements are individual.

6.Conditional operators:-
It is also called ternary (?:) . Because it uses three expressions.
Syntax:-
(exp1 ? exp2 : exp3);
exp1 is evaluated first; if exp1 is true then exp2 is evaluated other
wise it evaluate exp3.
7.Bitwise Operators:-
C supports some special operators known as bitwise operators for
manipulation of data at bit level. The bitwise operators are

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift
~ One’s
Complement

8. Special Operators:-
C supports some special operators such as comma operator, size of
operator, pointer operator(& and * ) and member selection operator(, and
->).

Q) Explain about Expressions?


Ans) Expressions:- An expression can be defined as a collection of
data object and operators that can be evaluate to lead a single new
data object. A data object is constant, variable or another data object.
Ex:- x+y,x+y+50,3.13*r*r;
The above expressions are called the arithmetic expressions.
Because the data objects are connected, using arithmetic operators.
Evaluation procedure:-
The evaluation of arithmetic expressions is as per the higher
rules for arithmetic expressions.
1. expression is scanned from left to right .
2. evaluation preference for the operators is as under
*,/,% evaluate first
+,- evaluate next.
3. To overcome the above precedence rules user has to make use of
parenthesis. If the parenthesis is used in the expression with in
parenthesis evaluated first.

B.SC (MPCS) I Year I Sem 26 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Q) Precedence of operators and its associativety?

Ans) If the expressions has more than one operator has it must be
necessary to give the precedence to each operator has the facility for
giving the precedence to each operator. Each operator precedence and
associativity of each operator are given below.

B.SC (MPCS) I Year I Sem 27 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

OPERATOR DESCRIPTION PRECEDENCE ASSOCIATIVITY


LEVEL
() Function call
[] Array expression
-> Structure operator 1 Left to right
. Structure operator
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Negation
~ One’s complement 2 Right to Left
& Address
* Value of address
Size of Size in bytes
Typedef Type cast
* Multiplication
/ Division
% Modulus 3 Left to right

+ Addition
- Subtraction 4 Left to right

<< Left shift


>> Right shift 5 Left to right

< Less than


> Greater than
<= Less than or equal
6 Left to right
>= to
Greater than or
equal to
== Equal to
!= Not equal to 7 Left to right

& Bitwise AND 8 Left to right


^ Bitwise XOR 9 Left to right
| Bitwise OR 10 Left to right
&& Logical AND 11 Left to right
|| Logical OR 12 Left to right
?: Ternary operator 13 Left to right
=,+=,- Assignment
14 Right to left
=,*=,/=,%= operator
, Comma 15 Left to right

B.SC (MPCS) I Year I Sem 28 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Q) Explain about data type conversion?

Ans) C has the facility to mix the different type of variables in expression.
In this type of operation one data type is converted into another data
type.

Type conversion techniques:-


1. Type conversion by assignment
2. Type conversion through the case operator.

Type conversion by assignment:-


In this technique we will make use of “=” assignment
operator to convert the value form one data type to the another data
type.
Ex:- int a;
Float b;
a =b;
This technique has got some draw back of terminator of
fractional part.
Type conversion through cast operator:-
The draw back associated with the first technique is removed
in this cast. Operator in the place of assignment operator. This
technique fairly convert one data type to another data type.
Ex:- int a,b,c;
A=10; b=3;
C=a/b=10/3=3.333;
Let us suppose ‘c’ is integer type instead of float type we may write
as
C=(int) 10/3=3;

Operand 1 operand 2 Result

Char Char Char


Char int int
Char float float
Char double double

Operand 1 operand 2 Result

int Char int


int int int
int float float
int double double

Operand 1 operand 2 Result

float Char float


float int float

B.SC (MPCS) I Year I Sem 29 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

float Float float


float double double

Operand 1 operand 2 Result

double Char double


double int double
double Float double
double double double

B.SC (MPCS) I Year I Sem 30 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Unit - II
Chapter - 5
Input - Output Functions

Q) Describe input and output functions in ‘C’ Language?

Ans) The I/O functions are classified into 2 types:


1. Formatted functions .
2. Unformatted functions

Formatted I/O Functions:


Input function:-
Input functions are used to read data from the computer. Input data
can be user’s data, which is entered through the keyboard or a file that is
stored in a secondary device like disk, tape etc.
scanf() function:-
This functions used to read the all types of value. The function will
have two parameters.
General form is:
Scanf(“control strings”, argument list);
Control string:-
This string contains the conversion characters and also determines
the no of arguments as per defined variable list. This string enclosed with
double quotation marks.
Argument list:-
This list contains variable names separated with commas and an
ampersand symbol(&) also called as the address operator must be
included as prefix to the variables of data type numeric character.

Ex:-
1. int a,b;
scanf(“%d%d”,&a,&B);
2. float x,y;
char p;
scanf(“%f%f%c”,&x,&y,&p);
3. char name[10];

B.SC (MPCS) I Year I Sem 31 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

scanf(“%s”,name);

Output Function:

The output functions are useful for us to obtain the results from the
computers. The user can get the results on the standard output device
VDU & later stored on disk .

printf() function:-

This function is used to display the formatted output data items on the
standard output device. The general form is
Printf(“control string”, argument list);

The control list is the user defined formatted codes and this may
also be a string constant . The argument list contains the set of data items
to display the proper format defined by the control string.
Ex:- 1. printf(“ PC SOFTWARE & C “);
2.printf(“%d%d%d%f”,a,b,c,area);

Unformatted Input Functions:

1.getch() function
2.getchar() function
3.gets() function

getch() Function:-
This is a function used as input statement to read only alpha
numeric character from the standard input device say keyboard.
Syntax:- getch();
Each time when this function is called it returns the next input character.
Ex:- d=getch();
The character accepted from keyboard assigned to variable “d”.

getchar() function:-
Single character can be entered into the computer using ‘C’ library
function getchar(). It returns a single character from a standard input
device the function does not required any arguments.
Syntax:- character variable=getchar();
Ex:- char c;
C=getchar();

gets():-
The gets () function is used to read a string from the keyboard until
a carriage return key or new line key is pressed. At the end the function
appends a “null” terminator.
Syntax:-
gets (variable name);

B.SC (MPCS) I Year I Sem 32 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Ex:-
gets(s);
gets(name);

Where name is the array storing the string. It is necessary to define name
as a array of characters.

Unformatted Output functions:-

1.putch() function
2.putchar() function
3.puts() function

Putch() function:-

This function is complimentary of getch() functions and is used to


display any alpha numeric character on the standard output device like
VDU.
Syntax:-
Putch(argument variable);
Each time when this function is called it returns one output character
by the argument variable.
Ex:
d=getch();
c= putch(d);

Putchar():-
This function used to display any alphabetic character. The format
of putchar function is

Syntax:
putchar(variable name);
Ex:-
answer=’y’;
putchar(answer);

Puts():-
The function puts() outputs the string to the standard output device.
Syntax:-
Puts(s);
Ex:-
main()
{
char line[80];
gets(line);
puts(line);
}

B.SC (MPCS) I Year I Sem 33 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Q) Explain the Escape sequences and format strings?

Ans) Normally the output of message from printf statement is a single


line. This is to be broken by using the escape sequence.
The escape sequences must be used along with the text
inside the printf statement . escape sequence are also called as
execution character set. The ‘\’ is considered as escape character it
causes an escape from the normal interpretation of a string . A string
means group of characters enclosed in double quotes. So that the next
characters, are invisible and cannot be printed or displayed directly.
These characters will have effect only when the program being executed
the escape sequences are.

Character Escape sequence


Bell or alert \a
Back slash \b
Horizontal tab \t
Vertical tab \v
Form feed \f
Question mark \?
Null character \0
New line character \n
Back slash \\
Single quote \’

B.SC (MPCS) I Year I Sem 34 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Chapter -6
Control Structures
Q) what are the control structures in “c” ?
Ans) Control structures are 3 types
1. sequential statements
2. conditional statements
3. Control statement (looping statements)
1.Sequential statements:-
The sequential statements will be executed one by one in the
given program.
2.Conditional statements:-
1. simple if statement.
2. if… else statement
3. if else …else if statement
4. nested if statement.
5. switch statement.

1. Simple if statement:-
General form:-

If (condition) if(condition)
Statement; {
Statement1;
(OR) Statement2;
. block
.
.
Statement n;
}
Flow Chart of IF

true

Test Condition

block

false

B.SC (MPCS) I Year I Sem 35 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Next statement

In this form if the condition is true a single or a group of statement with


in the braces are executed. It the condition is false next statement is
executed.

If .. else statement:-
The general form is

If(condition) if(condition)
Statement; (OR) {
else Statement 1;
statement; : block 1
Statement n;
}
Else
{
Statement 1;
: block2
Statement n;
}

FLOW CHART FOR IF..ELSE

entry

false True
Test Condition

Block 2 Block1

Next statement

In this form if the condition is true block 1 will be executed. It the


condition is false block2 is executed. A block may contain single
statement or group of statements with in the braces.

If else …else if statement:-


The general form is

B.SC (MPCS) I Year I Sem 36 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

if( condition 1)
statement 1;
else if( condition 2)
statement 2;
else if( condition 3)
statement 3;
:
:
else
statement n;
(OR)

if(condition 1)
block1;
else if(condition 2)
block 2;
else if(condition 3)
block 3;
:
:
else
block n;
In this form if the condition 1 is true block 1 is executed. If the
condition 2 is true block 2 is executed and on when all the conditions
are false default is executed. A block may contain single or group of
statements are executed with in the braces.

Nested if statement:-The general form is


if (condition 1)
if (condition 2)
statement 1;
else
statement 2;
else
statement 3;

(OR)

if (condition 1)
{
if (condition 2)
{
statement 1;
: block1
:
statement n;
}

B.SC (MPCS) I Year I Sem 37 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

else
{
statement 1;
: block2
:
statement n;
}
}

else
{
statement 1;
:
: block 3
statement n;
}

If statement contains with in another if statement is called nesting on if


statements when the both the conditions are true statement 1 is
executed .If the condition 1 is false then block 3 is executed .if the
condition 1 true & condition 2 are false statement 2 or block 2 is
executed.

Switch statement: -
General form is

switch (expression)
{
case constant 1: statement;
break;
case constant2: statement;
break;
:
:
:
case constant n: statement;
break;
default: statement;
}
The switch statements is multi way conditional statement .where
expression is an integer expression or character type expression and
constant1, constant2….constant n are the constants or constant
expression called case labels.
If the switch statement is executed , the value of the
expression is successively compared against the values of
constant1,constant2,…constant n. If a case is found whose value
matches with the constant of the expression the block of statement
that follows the ‘case ‘ are executed.

B.SC (MPCS) I Year I Sem 38 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

The break statement at the end of a particular case causes


an exit form the switch statement. The absence of break statement at
each block causes the sequential execution of all statements from the
block to the end of the switch structure.
The default statement is executed if no matches are found.
The default is optional and if not present, no actual takes place of all
matches fail. When a match is found, the statement associated with
that case is executed until the break statement is reached.

3.Decision making or looping:-

In looping a sequence of statements are executing repeatedly until


some condition is satisfied depending upon position of the condition.
There are three types of loops.
1. while statement
2. do .. while statement
3. for statement

while statement:- The general form of the while loop is

While(condition)
{
Statement 1;
: body of the loop
:
Statement n;
}

While is an entry control looping statement. Here first the condition is


tested, if it is true the body of the loop will be executed as long as the
condition is true. When if the condition is false the control comes out of
the loop.

Do..While Statement:-
The general form is
do
{
Statement 1;
: body of the loop
:
Statement n;
} while(condition);

Do .. while statement is an exit control loop statement. Here first the


body of the loop is executed and then condition is tested. If the
condition is true again the body of the loop is executed. If the condition
is false the statements of the loop will be terminated. i.e. control
transfers to the statement following do .. while statement.

B.SC (MPCS) I Year I Sem 39 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

For loop: For loop is another entry control loop . The general form of
for statement is
For(initialization; condition; increment/decrement)
{
Body of the loop;
}
The execution of for statements the initialization of control value is
done first. The value of control variable is tested by using test condition. If
the condition is true then the body of the loop will be executed then the
value of control variable is incremented. This new value again tested
using the test condition if it is true again the body of loop is executed. If
the condition is false control comes out of the loop. The for statement
allowed –ve increment.
Ex:- for(i=0;i>=0;i--)
Printf(“%d”,i);

Q) Explain briefly goto, break, and continue statements? or


Jumping
statements in 'C'?
Ans)
Go to Statement:-
‘C’ supports the goto statement to branch unconditionally from one point
to another in the program. Although it may not be essential to use the
goto statement in a highly structured language likes C.
The go to requires a label in order to identify the place where the
branch is to be made. A label is any valid variable name and must be
followed by a colon. The label is placed immediately before the statement
where the control is to be transferred. The general forms of goto and label
statements are shown below:

Goto label; Label:


------------ ; Statement;
------------ ; ________
------------ ; ________
label: ________
Statement; Goto label

Forward jump backward jump

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

B.SC (MPCS) I Year I Sem 40 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

int i=1;

Count:

printf("%d\n",i);
i++;
if(i<10)
{
goto Count;
}
getch();
}
Continue:-The continue statement works somewhat like break
statement. But instead of forcing termination, continue forces the next
iteration of the loop to take place, skipping any code in between. For
example the following routine displays only positive numbers.

continue

Next iteration takes place


Ex:-
do
{
Scanf(“%d”,&x);
If(x<0) continue;
Printf(“%d”,x);
}while(x!=100);

In while and do .. while loops, the continue statement causes control


to go directly to the conditional test and then continue the looping
process. In the case of for, first the increment part of the loop is
performed , next the conditional test is executed and finally the loop
continues.
Break:-The break statement is used to terminate a loop or exit form a
switch statement. It can be used with in a while or do-while or for or
switch statement.

This statement ca be written as break; when the break


statement is encountered inside a loop the loop is immediately exited
and the program continues with the statement immediately following
the loop.

B.SC (MPCS) I Year I Sem 41 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Then the loop are nested, then the break would only exit from
the loop containing it, i.e. the break will exit form that loop. The given
example shows the use of break statement in a switch statement.

next iteration will takes place

yes
break Outside
loop

Ex:-
switch(choice)
{
case ‘r’: printf(“red \n”);
break;
case ‘w’: printf(“white \n”);
break;
}

Q) write the differences between While and do while?


Ans)
While Do - while
1. while is a entry control loop. 1. Do-while is a exit control loop.

2. while is a top tested loop, 2.do-while is a bottom tested loop.

3. In while loop first condition is 3.In do-while loop first the body of
tested. the loop is executed and then
condition is tested.
4.If the condition is true then 4.If the condition is true again the
the body of the loop will be body of the loop will be executed.
executed
5.The condition is false control 5. If the condition false control
transfers to the statement transfers to the statement followed
followed by the while by do-while statement.
statement.
6.while(test expression) 6.do
{ {
Statement; Statement;
Statement; Statement;
………….; ………….;
} }while(test expression);
7. No semi colon following the 7. Semi colon following the while
while statement. statement at the bottom.

B.SC (MPCS) I Year I Sem 42 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Chapter - 7
ARRAYS & STRINGS

Q) What is an array? Explain about the different types of arrays in “C”


language?

Ans) Set of related data items is called Array. It can share a common
name. The Array variable start from 0th location in memory. The array
each cell can be created be separate address value.

Defining an Array:- Arrays are defined same as the ordinary variables.


Each array element is referred to by specifying the array name followed
by one or more subscripts, with each subscript enclosed in square
brackets. The number of subscripts determines the number of
dimensionality of the array.

Arrays are of three types:

1.one dimensional array.


2.Two dimensional array.
3.Multidimensional array.

One Dimensional array:- A list of items can be given one variable name
using only one subscript such a variable is called a single dimensional
array.
Syntax:-
Data type array name[array size];
Ex:- Char name[10];
Here name is one dimensional character array containing 10 elements
these are name[0],name[1],…,name[9];

Initialization of one dimensional arrays:


We can initialize the elements of arrays in the same way as the ordinary
variables when they are declared

General form:-
Data type array name[size]={list of values};

Ex:- int number[5]={1,34,56,32,66};


Ex 2:- char gdc[9]=”WEL COME”;

Here the gdc can be stored in the memory is as follows

‘W’ ‘E’ ‘L’ ‘ ’ ‘C’ ‘O’ ‘M’ ‘E’ ‘\0’

B.SC (MPCS) I Year I Sem 43 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Compiler sees the character string, it ends the string with additional null
character.
We can initialize or read the values to an array by using for loop.
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);

Displaying one dimensional elements:-


We can display the elements by using for loop
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);

Two dimensional array:


A list of items can be given one variable name using two subscripts such
a variable is called a tow dimensional array

General form:-
Data type array name[row size][column size];
Ex:- int a[3][4];

Initialization of two dimensional array:-


Two dimensional arrays can be initialized by following their declaration
with the list of initial values enclosed in braces.
Syntax:- data type array name[row size][column name]={list of values};
Ex:- int a[2][3]={0,1,2,1,3,4};
(OR)
int a[2][3]={ {0,2,3},{1,3,4});
(OR)
Int a[2][3]={ {0,2,3}
{1,3,4} };
Processing with two dimensional arrays:-
Elements of two dimensional arrays can be read accessed and printed
using a nested for loop.

Reading tow dimensional array:-


For(i=0;i<m;i++)
For(j=0;j<n;j++)
Scanf(“%d”,&a[i][j]);
Printing two dimensional array:-
For(i=0;i<m;i++)
{
For(j=0;j<n;j++)
{
Printf(“%d”,a[i][j]);
}
Printf(“\n”);
}

B.SC (MPCS) I Year I Sem 44 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Multidimensional arrays:-

C allows arrays of three or more dimensions.


General form:-
Data type array name[size1][size2]…..[size n];
Ex:-
Int a[3][5][12];
Here array a is the three dimensional array declared to contain 180
integer type of elements.

Q) What is a string? What are the String handling functions


c?

A) A set of characters are called a string . String can be represented as


the one dimensional character array. Each character with in the string will
be stored with in a particular memory location of the array. The string
characters are staring form 0th location and the string terminated with null
(\0) character to give any string with standard input function then to use
the “%s” format specifies .
The general form:-
Data type string name[size];
Ex:- char name[20];

Initialization of a string:-
Char name[5]={‘r’,’a’,’m’,’a’};
(or)
Char name[5]={“rama”};
/* Write a program to read and display any string from the key board */
#include<stdio.h>
Void main()
{
Char s[10];
Clrscr();
Printf(“enter any string \n”);l
Scanf(“%s”,s);
Getch();
}

String Handling functions in ‘C’:-

‘C’ library supports a large no. of string handling functions that can be
used to carry out many of the string manipulations. We are using the
string handling functions in our program we must define <string.h> as the
header file most commonly used string handling functions are as follows.

B.SC (MPCS) I Year I Sem 45 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Strcat() ---- Concatenation of two strings.


Strcpy() ---- Copying one string to another string
Strcmp ----- Comparing the two strings.
Strlen() ----- Finds length of a string.
Strrev() ---- Reverse the string.

1.Strcat:- This function is a library string handling function. This function


is used to concatenation of two strings.

General form:-
Strcat(string1,string2);

Where string1 and string2 as the character arrays. When the


function strcat( ) is executed string2 will be appended string1.

2.Strcpy():- This function is a library string handling function. This


function is used to copy from one string to another string.

General Form:-
Strcpy(string1,string2);

Where string1,string 2 are the two character strings when the


function strcpy is executed, then content of string2 is copied to string1.

3.Strcmp():- This function is library string handling function. This is


used to compare the two strings. The strcmp() function compares the two
strings identified by the arguments and had the value zero, if they are
equal, else the string are not equal.

General form:-
Strcmp(string1,stirng2)==0)

Where string1 & string2 may be string variables or string constants.

4.Strlen():- This functions library string handling function. This is used to


find the length of a given string. This counts are returns the number of
characters in a given string.

General form:-
Strlen(string1);

5.Strrev():- This function is a library string handling function. This is used


to convert reverse of the given string.

General form:-Strrev(string1);

Example Program:

B.SC (MPCS) I Year I Sem 46 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
intl;
clrscr();
printf("enter any 2 strings \n");
scanf("%s%s",s1,s2);
l=strlen(s1);
strcat(s1,s2);
printf("Length of string s1=%d\n",s1);
printf("After concatenation s1=%s\n",s1);
strrev(s1);
printf("Reversing the string s1=%s",s1);
getch();
}

ctype.h header file in c:

This function is used to make an upper case character into the lower case
character. This function takes a character in the form of parameter as a
character and returns a character. The character which will return lower-
case
Example Program:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void amin()
{
char a,b,c,d,e,f,g,h,i,j;
a='A';
b='B';
c='C';
d='D';
e='E';
f=tolower(a);
g=tolower(b);
h=tolower(c);
i=tolower(d);
j=tolower(e);

printf("%c is %c \n",a,f);
printf("%c is %c \n",b,g);
printf("%c is %c \n",c,h);
printf("%c is %c \n",d,i);
printf("%c is %c \n",e,j);

B.SC (MPCS) I Year I Sem 47 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

getch();
}

UNIT - III
Chapter -8
FUNCTIONS

Q) what is a function and its advantages? What are the types of


functions?

Ans) A Function is reusable block of statements, which is used to perform


a specific task. Generally C program is divided into basic building blocks
called C functions. C function contains set of instructions enclosed by "
{ }" which performs specific operations in c program. Every ‘C’ program
consists of one or more functions. functions are classified into 2
categories.

1.Library function. or Predefined library functions.


2.User defined functions.

Advantages of functions:-
 C functions to avoid rewriting same logic / code again and again in a
program.
 There is no limit in calling c functions to make use of same
functionality whenever required.
 We can call functions any number of times in a program and from
any place in a program
 The use of user defined functions allows a large program to be
broken down into a number of smaller self contained components.
 Program debugging is easier, if C Program contain functions.
 Once a function is called and debugged it can be generalized, tested
thoroughly and can be placed into a library so that it can be used
again and again by many programs.
 It is easy to locate and isolate a function.

Q) Write about Library functions or Predefined Functions in


C?

Ans) The Function whose definition is defined by the system is called as


system defined functions.

The system defined functions are also called as library functions or


standard functions or predefined functions. The implementation of system
defined functions is already defined by the system.

B.SC (MPCS) I Year I Sem 48 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

In C, all the system defined functions are defined inside the header
files like stdio.h, conio.h, math.h, string.h etc. For example the functions
printf(), Scanf() are defined in the header file called stdio.h. We must
include the respective header file using #include statements.
If we use a system defined functions like pow(), sqrt() in our
program we use math.h in our program.

List of library functions:

I/O functions : stdio.h


getchar() : returns the next character typed on the keyboard.
Putchar() : outputs a single character to the screen.
printf() : used to print data.
scanf() : used to read data.

Mathematical Functions: Math.h


abs() : returns the absolute value of the given number
floor() : returns nearest integer less than or equal
number
round() : returns nearest integer greater than the number
sqrt() : returns square root of number.
exp() : returns exponential "e" to the X th power.
pow() : used to find the power of a given number.
trunc() : eliminates decimal part of a float and returns
integer
cos() : This function is used to calculate cosine
sin() : This function is used to calculate sine value
log() : This function is used to calculates natural
logorithm
tan() : This function is used to calculate tangent
acos() : returns arc cosine of argument
asin() : returns arc sine of argument
atan() : returns arc tangent of argument

String Functions : String.h:


strlen() : returns the length of the given string
strcmp() : compares two strings
strcat() : concatenates two strings.
strcpy() : copies contents of one string to another string
strrev() : reverses the given string.
strlwr() : converts string to lowercase
strupr() : converts string to uppercase

Character functions : ctype.h:

isalpha() : checks whether the character is alphabetic


isdigit() : checks whether the character is digit
isalnum() : checks whether the character is alphanumeric

B.SC (MPCS) I Year I Sem 49 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

islower() : checks whether the character is lower case.


isupper() : checks whether the character is upper case.
isprint() : checks whether the character is a printable
character.
tolower() : checks whether character is alphabetic & converts
lower case
toupper() : checks whether character is alphabetic & converts
upper case.

Date and time functions : ctime.h:

setdate() : This function is used to modify the system date


getdate() : This function is used to get the CPU time.
clock() : This function is used to get current system time.
time() : returns current calendar time of system.
difftime() : This function is used to get difference between
tow
given times.
ctime() : This function is used to return string that contains
date and time information's.

Q) What is a function? Components of the Function? (OR) Modular


Programming? (OR) User Defined Functions in C?

Ans) In order to make use of user defined functions, we need to establish


three elements, they are

1. Function Prototype or declaration


2. Function Call
3. Function definition.

Function prototype (OR) Function declaration

A function declaration has three principal components. The first


component of a function declaration contain the data type of the value
returned by the function. The second component is the function name.
The third compound consists of a set of arguments separated by commas
and enclosed in a parentheses.

The General Form:-


return type function name(type arg1,type arg2,….type argn);
Ex:- float area (float);

Function Call:
This is the statement where the function is called and actually used . A
function can be called from main() function, other function in the program
or in the same function itself. A function can be called any number of
times in the program. When a function is called, the control of the

B.SC (MPCS) I Year I Sem 50 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

program is transferred to the function definition. And, the compiler starts


executing the codes inside the body of a function. In C programming,
"arguments" refers to the variables passed to the function.
Syntax:
Function_Name(argument list);

Function definition:- A function is a self contained program sequence


that carries out some specific well defined task. The function is having list
of parameters. These arguments are to send from main function to sub
function. The sub function send to return value to main function. It include
the following elements.
 Function name.
 Return type.
 List of arguments.
 Local variable declaration.
 Function statement.
 Return statement.

General form:-
return type Function name(arguments list)
argument declaration;
{
Local variable declaration;
function statements;
return statement;
}
The first line of function definition contains the type specification of the
value return by the function followed by the function name and a set of
arguments. An empty pair of parenthesis must follow the name of the
function definition does not include any arguments.

Ex:
#include<stdio.h>
int main()
{
int x,y,c;
int sum(int,int); // function prototype
clrscr();
printf("enter the x,y values \n");
scanf("%d%d", &x,&y);
c=sum(x,y); // function call
printf("Result c=%d", c);
getch();
}
int sum(int a, int b) // function definition
{
return(a+b);
}

B.SC (MPCS) I Year I Sem 51 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Q) How many ways the function can be implemented?


(or)
Categories of the functions?

Types of functions or categories of functions:-


1. Function with no arguments and no return values.
2. Function with arguments and no return values.
3. Function with no arguments and return value.
4. Function with arguments and return values.

1. Function with no arguments and no return value:


When a Function has no arguments it does not receive any data
from the calling function. Similarly the calling function does not
receive any data from the called function. In effect there is no data
transfer between calling function and called function.

The general form is :

main()
{
---------------;
function1();
}
function1()
{
--------------;
}

Example Program:-
#include<stdio.h>
void main()
{
void sum();
printf(“\n sum of 2 numbers\n”);
sum();
}
void sum()
{
int a,b;
printf(“enter any 2 numbers \n”);
scanf(“%d%d”,&a,&b);
printf(“sum=%d”,a+b);
}

2. Function with arguments and no return values:-In this method


the function receives data from the calling function, But it does not send

B.SC (MPCS) I Year I Sem 52 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

back any value. The data communication between calling function and
called function with arguments but no return value.

The general form:

main()
{
int x;
--------------;
function(x);
}
function(a)
int a;
{
--------------;
}
One way communication between function.

Example Program:-

#include<stdio.h>
void main()
{
int a,b;
void sum(int,int);
printf(“\n enter any 2 numbers\n”);
scanf(“%d%d”,&a,&b);
sum(a,b);
}
void sum(int x,int y)
{
printf(“sum=%d”,x+y);
}

Main () is a calling function that calls Sum() function. The Sum()


function has arguments. The calling function has some arguments
called as actual parameters and copy values of the actual parameters
are passed to the called function. Where the parameters called formal
parameters are used to accept the transferred values from the calling
functions.

3.Function with no arguments and return value: -Functions do not


receive any data from the calling function when they have no arguments.
But it return a value to the calling function .

The general form is :

B.SC (MPCS) I Year I Sem 53 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

main()
{
---------------;
function1();
}
function1()
{
--------------;
return(value);
}

Ex:-

#include<stdio.h>
void main()
{
int c;
int sum();
c=sum();
printf(“sum=%d”,c);
}
int sum()
{
int a.b;
printf(“\n enter any 2 numbers\n”);
scnaf(“%d%d”,&a,&b);
c=a+b;
return ( c );
}

4. function with arguments and return value:-


In this, function is called with passing of some formal arguments to the
function from calling program and intern the function returns back some
values to the calling program. Thus a two way data communication is
achieved between the calling program as well as the function sub
program.
General form:-
main()
{
---------------;
function1(a);
}
function1(a)
{
--------------;
return(value);
}

B.SC (MPCS) I Year I Sem 54 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

ex:-
#include<stdio.h>
void main()
{
int a,b,c;
int sum(int ,int);
printf(“\n enter any 2 numbers\n”);
scanf(“%d%d”,&a,&b);
c=sum(a,b);
printf(“sum=%d”,c);
}
void sum(int a,int b)
{
return ( a+b );
}

Q) Explain Actual parameter and Formal parameter?


A) The parameters that of specified in the function call are called Actual
parameters. The parameters that are specified in the function header
called formal parameters.
Function is called the name of the actual arguments
need not be the same as the names of formal arguments. However the
data types of the actual arguments.

EX:-

#include<stdio.h>
void main()
{
int a,b;
void sum(int,int);
printf(“\n enter any 2 numbers\n”);
scnaf(“%d%d”,&a,&b);
sum(a,b); //a,b are the actual parameters
}
void sum(int x,int y) //x,y are the formal parameters
{
printf(“sum=%d”,x+y);
}

Main () is a calling function that calls Sum() function. The Sum()


function has arguments. The calling function has some arguments
called as actual parameters and copy values of the actual parameters
are passed to the called function. Where the parameters called formal
parameters are used to accept the transferred values from the calling
functions.

B.SC (MPCS) I Year I Sem 55 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Q)Explain about the call-by value and Call-by-reference?

Ans)
CALL-BY-VALUE:- When a function is called the Actual parameters are
assigned to formal parameters. The process of passing the actual value of
variables is known as call by value. In call by value if there is any change
occurs in the called function it cannot be effected to the calling function.
(i.e. if there is any change occurs in the formal parameters it cannot be
effected to the actual parameters.)

Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“enter any 2 numbers\n”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping x=%d\t y=%d\n”,x,y);
swap(x,y);
printf(“After swapping x=%d\t y=%d\n”,x,y);
}
swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
printf(“In the function swapping a=%d \t b=%d\n”,a,b);
}
Output:
Enter any 2 numbers
10
20
Before swapping x=10 y=20
In the function swapping a=20 b=10
After swapping x=10 y=20

The values a and b are not changed even though the are swapped.
Because the parameter passing is call by value.

CALL BY REFERENCE:
When a function is called the Actual parameters are assigned to formal
parameter. The process of calling the function using pointers to pass the
address of variable is known as call by reference. In call by reference if
there is any change occurs in the called function it can be effected to the

B.SC (MPCS) I Year I Sem 56 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

calling function.(i.e., if there is any change occurs in the formal


parameters it can be effected to the actual parameters ) To pass the
address of the variable we use the ‘&’ followed by variable name.

Example program:
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“enter any 2 numbers\n”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping x=%d\t y=%d\n”,x,y);
swap(&x,&y);
printf(“After swapping x=%d\t y=%d\n”,x,y);
}
swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf(“In the function swapping a=%d \t b=%d\n”,*a,*b);
}

Output:
Enter any 2 numbers
10
20
Before swapping x=10 y=20
In the function swapping a=20 b=10
After swapping x=20 y=10

The values of a and b are changed because the parameter passing is call
by reference.

Q) Inline Functions?
Ans) c99 has added the keyword inline, which applies to functions. By
preceding a function declaration with inline, the compiler is instructed to
optimize calls to the function. Typically , this means that functions code
will be expanded inline, rather than called. Below is a definition of such
inline function.
inline int sum(int x, int y)
{
return(x+y);
}

B.SC (MPCS) I Year I Sem 57 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

The inline designation is only a hint to the compiler, suggesting that calls
to the inline function should be as fast as possible. The name comes from
a compiler optimization called inline expansion, where by a call to
function is replaced by copy of the function body.

Q) What is recursion function? Explain about the recursion


function in ‘C’ Language?

A) Recursion is a process which a function calls itself repeatedly until


some specified condition has been satisfied . The function itself it is calling
is called a recursion.
The recursion process is used for repetitive computations in which
each action is started of a previous result. In order to solve a problem
recursively 2 conditions must be satisfied.
1. The problem must be written in a recursive form.
2. The problem statement must include a stopping condition.

Ex:-
#include<stdio.h>
#include<conio.h>
void main()
{
long int n,f;
long int fact(int);
clrscr();
printf(“enter any number \n”);
scanf(“%d”,&n);
f=fact(n);
printf(“factorial of given number =%ld \n”,f);
getch();
}
long int fact (long int n)
{
int f1=1,i;
for(i=0;i<=n;i++)
f1=f1*i;
return(f1);
}

Q)Explain the Storage class in the ‘C’ Language?


A) The type of the data refer the size of the memory for a variable. These
variables also has storage class, that refers the life and scope of the
variables within programs, that is within blocks or functions. There are
four types of storage class specifiers

1.Automatic
2.Static

B.SC (MPCS) I Year I Sem 58 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

3.Register
4.Extern

General form is:-


Storage_class data type variable_name;

Automatic Storage class:- The local variables which are declared inside
the function are called automatic variable. All the variables declared
without any storage class specifier are assumed to be automatic variable.
The scope of the variable is inside the function in which they are declared.
We can use the same automatic variable in different function because
after the execution of the function, all automatic variables are disposed
off. The Keyword used for automatic storage class is auto.

/* program to understand the use of automatic storage class */

#include<stdio.h>
void main()
{
int no;
printf(“enter the number for table”);
for(i=1;i<=10;i++)
func(no);
}
func(int no)
{
auto int step=0;
step=step+no;
printf(“%d\n”,step);
}
Output:-
4
4
4
4
4
4
4
4
4
4

Static storage Class:- Static variables are same as the automatic


variable but it holds the latest value of the variable in the function in
which they declared. There are two types of static variable.

1.Local static variable.

B.SC (MPCS) I Year I Sem 59 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

2.Global static variable.

The scope of local static variable is local to that function in which


they appear, while the scope of the global static variable is through out
the program. By default it takes the initial value 0. The Keyword used for
static storage class is “Static”.

/* Program to understand the use of static variable */

#include<stdio.h>
void main()
{
int no;
printf(“enter the number for table”);
for(i=1;i<=10;i++)
func(no);
}
func(int no)
{
auto int step=0;
step=step+no;
printf(“%d\n”,step);
}
Output:-
4
8
12
16
20
24
28
32
36
40

Register Storage Class:- Register variable are used for storing the
value of variable into CPU registers. Access time of automatic variable is
more than accessing the register variable. Cpu register take less time &
for fast processing. The Keyword used for Register storage class is
“Register”.

Syntax: register datatype variable_name;

/* program to understand the use of register variable */

#include<stdio.h>
Main()
{

B.SC (MPCS) I Year I Sem 60 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Register int I;
For(i=0;i<200;i++)
Printf(“%d \n”,i);
}
External Storage Class:- The variables which are used in many
functions can be declared as external variable. The scope of the variable
is global. These variables are available to all functions in the program.
These are declared before the main() function. The Keyword used for
external storage class is extern.

Syntax:-
Extern datatype variable_name;

/* program to understand the use of extern variable */

#include<stdio.h>
int no,i;
main()
{
void fact(int);
clrscr();
printf(“enter the number \n”);
scanf(“%d”,&no);
fact(no);
}
void fact(int no)
{
int fact=1;
while(no>1)
{
fact=fact*no;
no--;
}
printf(“factorial of %d =%d \n”,no,fact);
}

Q) Differentiate between local and global variables in C?


A)
LOCAL VARIABLES GLOBAL VARIABLES
1. The variables which are declared 1. The variables which are declared
with the function are known as local above all the functions are known
variables. as global variables.
2. These variables are created at 2. These variables are created at
the time of function call and the time of program begin and
destroyed as soon as the function resides in memory until the whole
execution is over. program executes.
3. Local variables are accessible 3.Global variables are common to
only to that particular function. all the function sub programs

B.SC (MPCS) I Year I Sem 61 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

defined in the program.

Q) Passing arrays to function?


Arrays can also be arguments of functions. When an array is passed to a function, the
address of the array is passed and not copy the complete array.

Ex:
#include<stdio.h>
#include<conio.h>
void main( )
{
float avg, age[ ]={ 23.4,55,22.6,3,40.5,18};
float average(float age[]);
clrscr();
avg=average(age);
printf("Average age=%2f", avg);
getch();
}
float average(float age[ ])
{
int j;
float avg,sum=0.0;
for(i=0;i<6;i++)
{
sum=sum+age[i];
}
avg=sum/6;
return avg;
}

B.SC (MPCS) I Year I Sem 62 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Chapter -9
POINTERS
Q)What is pointer? How it can defined explain about the pointer in
‘c’language?

A) Pointer:-

A pointer is a variable. It contains the memory address of the


another variable and is declared as the pointer type. As an example if one
variable is a data type and second variable is the pointer type which
points to the first variables type, then the contents of the second variable
is the address of the first variable.
Ex:-

int a=5;
int *p;
p=&a;

value at 5 2000 address of the first


address variable

Declaring of pointer variable:- A pointer variable can be declared in


the same was as other variable. The general form of this pointer variable
same as ordinary variable but asterisk symbol should preceded the
variable declaration.
General form:-
Datatype *pointer name;
The datatype may be any of the datatype available in c.

Ex:- int *p;

Initialization of pointer variable:- we can initialize the pointer


variable by the following
int a=5;

B.SC (MPCS) I Year I Sem 63 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

int *p;
p=&a;
then
*p=5;

Advantages of pointers:-
 Pointer reduces the length and complexity of a program.
 Pointers are more efficient in handling the data tables.
 Pointers increase the execution speed.
 The use of a pointer array to character strings results in saving of
data storage space in memory.
 Pointer reduce the length and complexity of a program.
 Pointer is used for saving memory space.
 The Two dimensional and multi dimensional array represented is
easy with pointers.
 Pointer data manipulation is done with address, so the execution
time is faster.

The & And * Operator:-


The ‘&’ is the address operator, it represents the address of the variable
The ‘*’ operator is the value at address operator. It represents the value
at the specified address.

a Variable name

5 Value at address 2000


2000 address
Ex:-
#include<stdio.h>
Void main()
{
Int a=5;
Int *p;
P=&a;
Printf(“Value of a=%d\n”,a);
Printf(“Value of a=%d\n”,*p);
Printf(“Value of a=%d\n”,*(&a));
Printf(“Address of a=%u\n”,p);
Printf(“Address of a=%u\n”,&a);
}

Array of pointers:- Array is a collection of similar data type


elements. When we declare an array then consecutive memory locations

B.SC (MPCS) I Year I Sem 64 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

are allocated to the array elements. The base address of array is the
address of the 0th element of the array. The name of array also gives the
base address of the array.
Ex:-
int arr[4]={5,10,15,20};
int *A;
A=arr;
Or
A=&arr[0]
Every element of this array is a pointer variable. It is same as array
but it contains the collection of address.
Ex:-
#include<Stdio.h>
Void main()
{
int *arr[3];
int a=5,b=6,c=7,I;
arr[0]=&a;
arr[1]=&b;
arr[2]=&c;
for(i=0;i<3;i++)
{
printf(“address=%u\t”,arr[i]);
printf(“value =%d \n”,*(arr[i]);
}
}

Pointers to Strings:-
A character array occupies consecutive locations. As we know that
at the end of the string a null character (\0) stores in the character array.
name can be used like a pointer, it can be treated as string pointer
array.

Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
char *name[]={"Govt", "College"};
int i;
for(i=0;i<2;i++)
printf("%s \n", name[i]);

B.SC (MPCS) I Year I Sem 65 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

}
Pointer to Pointer:-
Pointer is a variable that contains the address of the another variable.
Similarly another pointer variable can store the address of this pointer
variable. Hence we can say this is a pointer to pointer variable.

Ex:-
#include<stdio.h>
Void main()
{
Int a=5;
Int *b;
Int **C;
B=&a;
c=&b;
Printf(“Value of a=%d\n”,a);
Printf(“Value of a=%d\n”,*b);
Printf(“Value of a=%d\n”,*(&a));
Printf(“Value of a=%d\n”,**c);
Printf(“Address of a=%u\n”,b);
Printf(“Address of a=%u\n”,&a);
Printf(“Address of a=%u\n”,*c);
Printf(“Address of b=%u\n”,c);
}

Q) Dynamic memory allocation?

‘C’ language has the facility to allocate memory at the of execution.


The process of allocating memory at the time of execution is called
dynamic memory allocation.
The allocation and releasing of this memory space can be done with
the use of some built in function which are find in alloc.h header file.

Size of():-
Size of is an unary operator this operator gives the size of its
argument in terms of bytes. The argument can be variable, array or any
data type. This operator also gives the size of any structure.
Ex:-
Size of (int);
This gives the bytes occupied by the int data type, that is 2.
Ex:-
/* program to understand the size of operator*/

B.SC (MPCS) I Year I Sem 66 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

# include<stdio.h>
main()
{
struct
{
char name[10];
int age;
float sal;
}rec;
int arr[10];
printf(“size of structure =%d”, size of(rec));
printf(“size of int = %d”, size of(int));
printf(“size of array =%d”, size of (char));
}

Malloc():-- This function is used to allocate memory space. The


malloc function reversed memory spaced of specified size & gives the
starting address to the pointer address to the pointer variable.
Syntax:--
Ptr=(data type *) malloc(specified size);
Ex:-
Ptr= (int *) malloc(10*size of(int));
This allocates the memory space 10 times, that is hold an int data
type. The base address is stored in the pointer variable ptr

/* program to enter the 5 no’s and print them */


# include<stdio.h>
main()
{
int j;
int *a;
a=(int *)malloc(5 * size of(int));
for(j=0;j<5;j++)
{
printf(“number %d +”, j+1);
scanf(“%d”, (a+j));
}
for(j=0; j<5;j++)
printf(“%d \n”, *(a+j));
}

Calloc():- the calloc function is used to allocate multiple block of memory


this has two arguments.
Ex:-
Ptr= (int *) calloc(5,2);

B.SC (MPCS) I Year I Sem 67 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

This allocates 5 blocks of memory, each block contain 2 bytes of memory


and this storing address is stored in the pointer variable ptr which is of
type int
The calloc() fun c. is generally used for allocating the memory space
for array and structure.
Ex:-
struct record
{
char name[10];
int age;
float sal;
};
int tot-rec = 100;
ptr = (record *) calloc (tot –rec, size of(record));

Free():--
For efficient use of memory space we can also release the memory
space that is not required. We can use the free functions for releasing the
memory space.

EX:- free(ptr);

Here ptr is a pointer variable that contains the base address of he


memory block that is created by malloc or calloc

Realloc():- There is a two possibility for that we want to change the size
of the block. In first case, we want more memory space in comparison to
allocated memory space.
In second case, the allocated memory is more than the required memory
space for changing the size of memory block we can use the function
realloc this is known as reallocation of memory.
Ptr = malloc (specified space);

The statement allocate the memory of the specified size and the base
address of memory block are stored in pointer variable ptr.
If we want to change the size of memory block
Ptr = recalloc (ptr , new size);

B.SC (MPCS) I Year I Sem 68 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

CHAPTER -10
USER DEFINED DATA TYPES
STRUCTURES & UNIONS

Q)What is a structure? How it can define?


Ans) A group of different data type are called a structure to create any
structure with ‘structure’ keyword. The structure elements are created
with separated address location in memory and a group of data items
that belongs to the same type such as int, float and character etc. but it
is not possible to represent a collection of data items of different type
using arrays, hence an alternate representation is structure.

Structure is data structure whose individual elements can be of


different type thus a single structure might contain integer, float and
character element pointer arrays and other structures can also be
included as elements with in a structures. The individual structure
element are referred to as members

The general form of a structure:-

Struct tag name


{
Data-type member1;
Data-type member2;
-------------------------;
-------------------------;
Data –type member n;
};
Where ‘struct’ is reserved word, tag name is a name that identifies
structure of this type.
Member1……………….member n are the individual fields.

Ex:- consider a book consisting of fields: name, author, pages and cost.
Then a structure to hold the information is as follows

struct class

B.SC (MPCS) I Year I Sem 69 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

{
char title[20];
char author[10];
int pages;
float cost;
};

Different ways to declaring the structure variable


Immediately after Structure Template:
struct class
{
char title[20];
char author[10];
int pages;
float cost;
}b1;

Declare variables using struct keyword:


struct book
{
char title[20];
char author[10];
int pages;
float cost;
};
sturct class b1;

Declaring Multiple structure variable:

struct book
{
char title[20];
char author[10];
int pages;
float cost;
}b1,b2, b3;

Accessing a structure:-
The link between a member and a variable is established
using the member operator, which is also known as ‘dot’ or ‘period’
operator.

Ex:-
book1.pages=250;
book 1.cost=75.50;
We can also use scanf() function to give values through the keyboard.

B.SC (MPCS) I Year I Sem 70 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Scanf(“%d%f”, &book1.pages & pages & book1.cost);

Q) Explain about the Arrays of structure?

We know array is collection of same data type of elements. For example


we can take 10 integer type of array. Similarly we can declare the array
of structure where every element of array is of structure type. Array of
structure can be declare as.

Struct rec
{
Char name [10];
Int age;
Char add[20];
} person [10];

Here person is an array of 10 elements and each element of person has


structure of rec, means each element of person have 3 member element
which are name, age and address.

Q)Explain about the Nested structured in ‘C’ language?

A)Structures with in structure:-


Nesting of structures is permitted in ‘c’ programming. Nesting
of structures means structures with in structures. Consider an example
that a structure defined to store information about the data of births of
students.
Syntax:-
Struct tag 1
{
Member1;
Member2;
…………;
Struct tag
{
Member1;
Member2;
………….;
Member m;
}var1;
………….;
}var2;

For accessing the memeber1 of inner structure we write as


var2.var1.member1;
Ex:-
Struct rec

B.SC (MPCS) I Year I Sem 71 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

{
Char name[20];
Int age;
Struct dob
{
Int day;
Int month;
Int year;
}birthday;
Char address[20];
} emp;

Here struct rec is the structure for the employee, record and struct dob
represent the birth date of that employee.

Q)Explain the pointer to structure?


Ans) Pointer is a variable which hold the starting address of another
variable, it may be of type int,float or char. Similarly , if the variable is of
structure type then for accessing they starting address of the structure,
we must declare pointer for a structure variable. These pointers are
called structure pointer.
Ex:- Struct rec
{
Char name[10];
Int age;
Int sal;
}data;
Struct rec *ptr;

UNIONS

UNIONS:- Union is same as the structure. As the structure contains


members of different data types. In the structure each member has its
own memory location. Where as members of unions has same memory
location. We can assign values to only one member at a time, so assigning
value to another member that time has no meaning.
When a union is declared, compiler automatically allocates a
memory locations to hold the largest data type of members in the union.
Thus the union is used for saving memory. Union can be declared as

Union unionname
{
Member 1;
Member 2;
------
-------

B.SC (MPCS) I Year I Sem 72 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Member n;
}variable name;

Ex:-
union emp
{
Int age;
Char code[4];
}e1;

Q)Explain about the difference between structure and


unions?

Structures Unions

Structure element are The union elements are created


created by with separate by same address value
address values
To use with struct keyword To use with the union keyword
The structure termination The union terminated with
with semicolon semicolon
To call all elements are To call all elements are with union
with structure variable variable
Syntax of structure is: Syntax of Union is:
Struct structname Union Unionname
{ {
Element1; Element1;
Element2; Element2;
…………; …………;
}; };

Q)Write about enumerated data types in ‘c’?


Ans)An enumerated data type is a set of integer constants which has
some value and called enumeration constants. This can be defined same
as structure or union. The general form is

Enum enum-tag
{
Member 1;
Member 2;
…………..;
Member n;
};
Where enum is a keyword and member 1, member 2……… is integer
identifier this can also be defined as

B.SC (MPCS) I Year I Sem 73 DEPT of Computer Science & Applications


S.R.N.K GOVERNMENT DEGREE COLLEGE ,BANSWADA
PROGRAMMING IN ' C '

Enum enum-tag
{
Member 1;
Member 2;
} variable;
Here variable is an enumeration variable. This variables can also
be defined as
Enum enum-tag variable;
Ex:-- enum month(jan, feb, mar, apr, may, june);

B.SC (MPCS) I Year I Sem 74 DEPT of Computer Science & Applications

You might also like