sem 1 cs
sem 1 cs
FACULTY OF SCIENCE
B.Sc. (Computer Science)
CBCS Pattern with Effect from the Academic Year 2019-2020
Structure of Curriculum
Course Title Hours/Week Credits
Theory Practical
Semester –I
Programming in C 4 3 4+1 = 5
Semester –II
Programming in C++ 4 3 4+1 = 5
Semester –III
Data Structures using C++ 4 3 4+1 = 5
Semester –IV
Data Base Management 4 3 4+1 = 5
Systems (DBMS)
Semester –V
Programming in Java 4 3 4+1 = 5
Semester –VI
Web Technologies 4 3 4+1 = 5
AECC
Hours/Week Credits
Theory
Fundamentals of Computers 2 2
SEC
Semester –III
Communication Skills(or) 2 2
Professional Skills (Sec –I)
Python –I (Sec –II) 2 2
Semester –IV
Leadership & Management 2 2
Skill (or) (Sec –III)
Universal Human Values
Python –II (Sec –IV) 2 2
Generic Elective (GE)
Information Technologies 4 4
Project/Optional
Semester –VI
PHP with MY SQL Theory Practical 3+1=4
3 3
OSMANIA UNIVERSITY
FACULTY OF SCIENCE
B.Sc. (Computer Science)
SEMESTER – I
Programming in C
Theory 4 Hours/Week 4 Credit Internal marks = 20
Practical 3 Hours/Week 1 Credit External Marks = 80
Unit – I
Computer Fundamentals: Introduction of Computers, Classification of Computers, Anatomy
of a Computer, Memory Hierarchy, Introduction to OS, Operational Overview of a CPU.
Program Fundamentals: Generation and Classification of Programming Languages,
Compiling, Interpreting, Loading, Linking of a Program, Developing Program, Software
Development.
Algorithms: Definitions, Different Ways of Stating Algorithms (Step-form, Pseudo-code,
Flowchart), Strategy for Designing Algorithms, Structured Programming Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program, Structure
of a C Program, Comments, Program Statements, C Tokens, Keywords, Identifiers, Data
Types, Variables, Constants, Operators and Expressions, Expression Evaluation–precedence
and associativity, Type Conversions.
Unit – II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape Sequences,
Control Statements: Selection Statements – if, if-else, nested if, nested if-else, comma operator,
conditional operator, switch; Iterative Statements–while, for, do-while; Special Control
Statement–goto, break, continue, return, exit.
Arrays and Strings: One-dimensional Arrays, Character Arrays, Functions from ctype.h,
string.h, Multidimensional Arrays.
Unit – III
Functions: Concept of Function, Using Functions, Call-by-Value Vs Call-by-reference,
Passing Arrays to Functions, Score of Variables, Storage Classes, Inline Functions, and
Recursion.
Pointers: Introduction, Address of Operator (&), Pointer, Uses of Pointers, Arrays and Pointers,
Pointers and Strings, Pointers to Pointers, Array of Pointers, Pointer to Array, Dynamic
Memory Allocation.
Unit – IV
User-defined Data Types: Declaring a Structure (Union) and its members, Initialization
Structure (Union), Accessing members of a Structure (Union), Array of Structures (Union),
Structures verses Unions, Enumeration Types.
Files: Introduction, Using Files in C, Working with Text Files, Working with Binary Files,
Files of Records, Random Access to Files of Records, Other File Management Functions.
Textbook: Pradip Dey, Manas Ghosh, Computer Fundamentals and Programming in C (2e)
References:
1. Ivor Horton, Beginning C
2. Ashok Kamthane, Programming in C
3. Herbert Schildt, The Complete Reference C
4. Paul Deitel, Harvey Deitel, C How to Program
5. Byron S. Gottfried, Theory and Problems of Programming with C
6. Brian W. Kernighan, Dennis M. Ritchie, The C Programming Language
7. B. A. Forouzan, R. F. Gilberg, A Structured Programming Approach Using C
OSMANIA UNIVERSITY
FACULTY OF SCIENCE
B.Sc. (Computer Science)
SEMESTER – I
Programming in C Lab
Practical 3 Hours/Week 1 Credit Marks: 25
Note:
• Programs of all the Concepts from Text Book including exercises must be practice and
execute.
• Faculty must take care about UG Standard Programs.
• In the external lab examination student has to execute two programs with compilation
and deployment steps are necessary. Write the Pseudo Code and draw Flow Chart for
the programs.
• Recommended to use Open Source Software: GCC on Linux; DevC++ (or) CodeBlocks
on Windows10.
• External Vice-Voce is compulsory.
1. Write a program to find the largest two (three) numbers using if and conditional
operator.
2. Write a program to print the reverse of a given number.
3. Write a program to print the prime number from 2 to n where n is given by user.
4. Write a program to find the roots of a quadratic equation using switch statement.
5. Write a program to print a triangle of stars as follows (take number of lines from user):
*
* * *
* * * * *
* * * * * **
6. Write a program to find largest and smallest elements in a given list of numbers.
7. Write a program to find the product of two matrices.
8. Write a program to find the GCD of two numbers using iteration and recursion.
9. Write a program to illustrate the use of storage classes.
10. Write a program to demonstrate the call by value and the call by reference concepts.
11. Write a program that prints a table indicating the number of occurrences of each
alphabet in the text entered as command line arguments.
12. Write a program to illustrate use of data type enum.
13. Write a program to demonstrate use of string functions string.h header file.
14. Write a program that opens a file and counts the number of characters in a file.
15. Write a program to create a structure Student containing fields for Roll No., Name,
Class, Year and Total Marks. Create 10 students and store them in a file.
16. Write a program that opens an existing text file and copies it to a new text file with all
lowercase letters changed to capital letters and all other characters unchanged.
UNIT-I
Chapter-1
Computer Fundamentals
⚫ CHARACTERISTICS OF COMPUTERS
The characteristics of computers have made them so powerful and universally
useful .They are:
1.Speed
• Computer is a very fast device.
• It is capable of performing calculation of very large amount of data.
• The computer has units of speed in microsecond, nanosecond, and even the picosecond.
• It can perform millions of calculations in a few seconds as compared to man who will
spend many months to perform the same task.
2.Accuracy
• In addition to being very fast, computers are very accurate.
• The calculations are 100% error free.
• Computers perform all jobs with 100% accuracy provided that the input is correct.
3. Storage Capability
• Memory is a very important characteristic of computers.
• A computer has much more storage capacity than human beings.
• It can store large amount of data.
• It can store any type of data such as images, videos, text, audio, etc.
4. Diligence
• Unlike human beings, a computer is free from monotony, tiredness, and lack of
concentration.
• It can work continuously without any error and boredom.
• It can perform repeated tasks with the same speed and accuracy.
5. Versatility
• A computer is a very versatile machine.
• A computer is very flexible in performing the jobs to be done.
• This machine can be used to solve the problems related to various fields.
• At one instance, it may be solving a complex scientific problem and the very next
moment it may be playing a card game.
6. Reliability
• A computer is a reliable machine.
• Modern electronic components have long lives.
• Computers are designed to make maintenance easy.
7.Automation
• Computer is an automatic machine.
• Automation is the ability to perform a given task automatically. Once the computer
receives a program i.e., the program is stored in the computer memory, then the
program and instruction can control the program execution without human interaction.
⚫ Classification of Computers
Most designs of computers today are based on concepts developed by John von
Neumann and are referred to as the von Neumann architecture. Computers can be classified in
variety of ways on the basis of various parameters such as usage, cost, size, processing power,
and so on. The classification of computers is presented below based on their power and their
use.
Based on Type:
Analog Computer
An analog computer (spelt analogue in British English) is a form of computer that
uses continuous physical phenomena such as electrical, mechanical, or hydraulic quantities to
model the problem being solved.
Digital Computer
A computer that performs calculations and logical operations with quantities
represented as digits, usually in the binary number system
Hybrid Computer
A combination of computers those are capable of inputting and outputting in both
digital and analog signals. A hybrid computer system setup offers a cost effective method of
performing complex simulations.
Supercomputer:
Supercomputer is the most expensive and fastest type of computer that performs at or
near the currently highest operational rate for computers. A Cray supercomputer is a typical
example. These are employed for specialized applications that require immense amounts of
mathematical calculations such as weather forecasting, nuclear energy research, and petroleum
exploration etc.
Mainframe:
A mainframe computer supports a vast number of users to work simultaneously and
remotely. Apart from providing multi-user facility, it can process large amounts of data at very
high speeds and support many input, output and auxiliary storage devices. These computers are
very large in size, and expensive. The main difference between a supercomputer and a
mainframe is that a supercomputer can execute a single program faster than a mainframe,
whereas a mainframe uses its power to execute many programs concurrently. The IBM 370 and
IBM 3090 are examples of mainframe computers.
Minicomputers
A minicomputer is powerful enough to be used by multiple users (between 10 to
100) but is smaller in size and memory capacity and cheaper than mainframes. Two classic
examples were the Digital Equipment Corporation VAX and the IBM AS/400.
Microcomputers:
The microcomputer has been intended to meet the personal computing needs of an
individual. It typically consists of a microprocessor chip, a memory system, interface units and
various I/O ports, typically resided in a motherboard. There are many types of microcomputers
available.
Desktop computer:
A microcomputer sufficient to fit on a desk.
Laptop computer
A portable microcomputer with an integrated screen and keyboard.
Palmtop computer/Digital diary/Notebook/PDAs
A handsized microcomputer having no keyboard. The screen serves both as an
input and output device.
Based on Purpose
1. General Purpose
General computers can do various everyday tasks such as writing a word
processing letter, Document preparation, recording, financial analysis, Printing documents,
creating databases, and calculations with accuracy and consistency.
The size, storage capacity, and cost of such computers are mainly less. The ability of these
computers is limited in performing specialized tasks. Still, it has versatility and useful for
serving people’s basic needs at home or in the workplace in the environment.
Examples:
The desktops, laptops, smartphones, and tablets are used on daily basis for general
purposes.
⚫ 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 which are responsible for providing the mechanisms to input and output data,
to manipulate and process data, and to electronically control the various input, output, and their
storage. They are known as hardware and software.
Input unit:
Data and instructions are fed into computer system for any calculation process.This
process is performed by the input that leads the external environment with computer system,the
data and instruction inter input units in the form that depends upon the media used. All input
devices provide data and instructions to the computer in binary form input inter faces converts
data instruction in computer acceptable form.
INPUT DEVICES:
1.Keyboard: -
➢ It is a input device consisting of a set of type writer like keys that enable you to enter
data into a computer.
➢ The keys on the computer keyboard are often classified as follows:
i) Alpha numeric keys numbers and characters.
ii) Puntuations keys (,,.,”, “,?,…..etc.)
iii) Special keys Function keys,control keys,Caps lock,Arrow keys.
➢ There are different personal computer keyboard are available.The original pc keyboard
with 84 keys,enhanced keyboard with 101 keys.
➢ IBM keyboards contain the following keys:-
➢ Page up,page down,home,end,insert pause,num lock,break,print screen.
2.Mouse:-
➢ Mouse is an input device that controls the movement of the cursor on a display screen.
➢ It is used to drive Microsoft windows.As you move the mouse,the pointer on the
display screen moves in the same direction.
3.Joystick:-
➢ This I one of the popular input device which is used to play video games.
➢ As the joystick is moved in the socket,the movements are converted into binary
instructions with help of electrical contacts at the base of joystick.
4.Track ball:-
➢ This is similar to joystick,the difference is that drag ball uses hardsphere instead of
handle for cursor controlThis hard ball can be rotated by hand in any direction.The
sphere speed and direction of the rotation is translated into digital signals which control
the cursor.
5.Scanner:-
➢ Scanner is an input device that can read text or pictures printed on paper and translates
the information into a term that the computer can use.
➢ The keyboard can only input text through keys provided in it .if the user wants to input
a picture, the keyboard cannot do that .
➢ A scanner is an optical device that can input any graphical matter and display it back.
➢ The common optical scanner device are Magnetic Ink Character
Recognition(MICR),Optical Mark Reader(OMR),and Magnetic Card Reader
(MCR).
Magnetic Ink Character Recognition(MICR):-
• This is widely used by banks to process large volumes of cheques and drafts
.cheques are kept inside the MICR.
• As they enter the reading unit ,the Cheques pass through the magnetic field ,which
causes the read head to recognize the character on the cheques.
Optical Mark Reader(OMR):-
This technique is used for evaluation of objective type answers .
• The answering will be done by darkening a square or circular space by pencil .
• The OMR is used to read and compares them with the answers in the memory for
evaluation.
Magnetic Card Reader (MCR):-
• It registers the data from the magnetic strip on a plastic card.When the employees go to
the office,they use these cards to punch their timings.
•
5.Touch screen:-
When the finger touches on any object of the screen,that object registers the input.
Storage Unit:
Data and Instructions that are entered into the computer system through input
units have to be stored some where in the computer,similarly result after processing are also
needed to be stored in the computer for this purpose there is a storage unit of the computer
system called primary memory or main memory.Thus provides space for data,instructions and
results every data,instruction and result is stored in the computer before and after the processing
Control Unit:
The control of all the operations like when to input data, apply instructions on
data, output the result, reading and writing from the memory is handled by the control unit
which works as central nerves system.
The control unit manages and coordinates the entire computer system.
Output unit:
Output unit supplies information and results of process to outside world,That links
the computer with external environment.Computer stores,data and instructions in binary
form,Similarly the output results are also stored in binary form.Hence before supplying the
result to the outside world,this must be converted into human acceptable form.This job is done
by output inter faces.
OUTPUT DEVICES
It displays the output from the computer processing for the user. The popular output
devices are:
1.MONITOR:
The monitor is a cathode ray tube display, which resembles a television. This can
generate electronic display of text or graphics. Images on the screen of the monitor are
displayed as a matrix of pixels. Monitor is known as the Visual Display Unit (VDU). It has a
screen which displays the output. The output displayed by the monitor is known as Soft Copy.
The monitor also displays the software which is loaded in the computer.
2 .PRINTER:
The printer is used to give output in the printed form. The printed output is called
Hard Copy. Printers produce the printed output of the results, instructions and data. These are
characterized by their speed and letter quality. Some printers print each character at a time and
some print each line at a time and so on. Some examples of printers include Dot Matrix
printers, Daisy Wheel printers, Line printers, Thermal printers and Laser printers. Printers are
classified as Impact printers and Non-Impact printers.
Impact printers use some electro-mechanical mechanism that causes head of the printer to
strike against a ribbon and paper to print the text. In a Non-Impact printer the mechanism will
not make any contact with the printer in order to print.
3.SPEAKERS:
Speakers are used to output sounds, voice, and music from the computer system.
The quality of music played on the computer is digital sound.
4.PLOTTERS:
⚫ Memory hierarchy:
Memory:
A memory is just like a human brain. It is used to store data and instructions.
Computer memory is the storage space in the computer, where data is to be processed and
instructions required for processing are stored. The memory is divided into large number of
small parts called cells. Each location or cell has a unique address, which varies from zero to
memory size minus one.
RAM:
Random Access Memory is where the programs are loaded. RAM is known as
temporary or volatile memory, i.e., the data stored in RAM gets erased when switch off the
computer. RAM can be accessed directly for reading or writing data in the same time
irrespective of its location.
ROM:
Read Only Memory contains a set of start-up instructions for the computer system
like checking the input and output devices, loading the Operating System into the RAM etc. It
is a permanent memory. The instructions stored here cannot be over written. These instructions
have been stored at the time of manufacture of the computer.
SECONDARY MEMORY:
It is the memory of the computer of the computer which is used for long term storage
of data. Secondary storage devices are Magnetic disk, Floppies, Hard disk, Compact disk, Pen
drive etc.
2) Floppy: It is a small plastic disk, coated with a magnetic material and enclosed in a plastic
casing. These are introduced in the early 1970’s and used on microcomputer. They are
reliable and portable. They are available in sizes like 51/4 inches and 31/2 inches. The 3.5
inch floppy can hold 1.44MB to 2.88 MB of storage and 5.2 inch floppy can hold 360 KB
to 1.2 MB of storage.
3) Hard Disk: It is a metal platter with magnetic coating on both sides. Several such disks are
stacked one on the other, without touching each other, into a disk pack for large storage.
The disk pack, housed in metal container with a read/write head unit, is fixed inside a
computer permanently. A disk pack is a collection of disks stacked vertically one on the
other and it is mounted on a disk drive. The disk drive has a head assembly with a
read/write arm for each pair of recording surfaces. Each disk has 2 surfaces for storage.
4) Optical Disk: It is a storage device which uses a laser beam to read and write data. The
Compact Disk and Digital Video Disk are types of optical disks.
i) Compact Disk: The compact disk or CD is a circular plastic disk encased within a
highly reflective metallic material. A CD can hold around 700MB of data. CDs are very useful
for storing images, music and video files. They are used to store and transfer application
software, computer games, utility programs, etc. CDs are 3 types. They are CD-ROM, CD-R,
CD-RW.
ii) Digital Video Disk: It is similar to CD but its storage capacity is 7 times that of CD.
A DVD has 4.7 GB of storage capacity.
5) USB/Pen Drive: This is a convenient way of transferring data. It is also known as USB
drive (Universal Service Bus). The storage capacity of a pen drive can be 1 GB or more. It
is a solid state device which means that it has no movable parts. It can be plugged into any
USB port of computer.
⚫Operating System
3. Device Management
An Operating System manages device communication via their respective drivers. It does the
following activities for device management −
• Keeps tracks of all devices. Program responsible for this task is known as the I/O
controller.
• Decides which process gets the device when and for how much time.
• Allocates the device in the efficient way.
• De-allocates devices.
6. Control over system performance − Recording delays between request for a service and
response from the system.
7. Error detecting aids − Production of dumps, traces, error messages, and other debugging
and error detecting aids.
⚫PROGRAMMING LANGUAGES:
A programming language is a formal language that specifies a set
of instructions that can be used to produce various kinds of output. Programming languages
generally consist of instructions for a computer. Programming languages can be used to
create programs that implement specific algorithms.
⚫Translators:
A program written in high-level language is called as source code. To convert the
source code into machine code, translators are needed.
A translator takes a program written in source language as input and converts it into a program
in target language as output.
It also detects and reports the error during translation.
Interpreter
Loader:
Loader is a program which is responsible for performing the loading function i.e. it brings
executable file into a given memory location. The loader carries out four functions.
1. It loads machine as well as data instruction into its specified memory location.
2. It assigns load time storage memory area to the program.
3. It relocates the program so that is can be executed appropriately.
4. It link two separate object programs with each other.
P.Sowmya Sree Unit-I Page 12
Linker:
Linker is a program in a system which helps to link a object modules of program
into a single object file. It performs the process of linking. Linker are also called link editors.
Linking is process of collecting and maintaining piece of code and data into a single file.
Linker also link a particular module into system library. It takes object modules from
assembler as input and forms an executable file as output for loader.
Linking is performed at both compile time, when the source code is translated into machine
code and load time, when the program is loaded into memory by the loader. Linking is
performed at the last step in compiling a program.
Source code -> compiler -> Assembler -> Object code -> Linker -> Executable file ->
Loader
Program Development
1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of
the problem. In this phase we need to understand the problem statement, what is our
requirement, what should be the output of the problem solution. These are defined in this first
phase of the program development life cycle.
2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to
solve the problem. That means we gather the required resources to solve the problem defined in
the problem definition phase. We also determine the bounds of the solution.
3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem
using the specification given in the previous phase. This phase is very important for program
development. That means we write the solution in step by step statements.
6. Maintenance
During this phase, the program is actively used by the users. If any enhancements
found in this phase, all the phases are to be repeated to make the enhancements. That means in
this phase, the solution (program) is used by the end-user. If the user encounters any problem or
wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.
Software Development
1. Planning
In the Planning phase, project leaders evaluate the terms of the project.
This includes calculating labor and material costs, creating a timetable with target
goals, and creating the project’s teams and leadership structure.
Planning can also include feedback from stakeholders. Stakeholders are
anyone who stands to benefit from the application. Try to get feedback from
potential customers, developers, subject matter experts, and sales reps.
2. Define Requirements
Defining requirements is considered part of planning to determine what the
application is supposed to do and its requirements. For example, a social media application
would require the ability to connect with a friend. An inventory program might require a search
feature.
4.Development:
Once the system design phase is over, the next phase is coding. In this phase,
developers start build the entire system by writing code using the chosen programming
language. In the coding phase, tasks are divided into units or modules and assigned to the
various developers. It is the longest phase of the Software Development Life Cycle process.
In this phase, Developer needs to follow certain predefined coding guidelines. They also need
to use programming tools like compiler, interpreters, debugger to generate and implement the
code.
5. Testing
When the software is ready, it is sent to the testing department where Test team
tests it thoroughly for different defects. They either test the software manually or using
automated testing tools depends on the process defined in STLC (Software Testing Life
Cycle) and ensure that each and every component of the software works fine. Once the QA
makes sure that the software is error-free, it goes to the next stage, which is Implementation.
6. Deployment
Once the software is complete, and it is deployed in the testing environment. The
testing team starts testing the functionality of the entire system. This is done to verify that the
entire application works according to the customer requirement.
During this phase, QA and testing team may find some bugs/defects which they
communicate to developers. The development team fixes the bug and send back to QA for a re-
test. This process continues until the software is bug-free, stable, and working according to the
business needs of that system.’
At this point, the development cycle is almost finished. The application is done
and being used in the field. The Operation and Maintenance phase is still important, though. In
this phase, users discover bugs that weren’t found during testing. These errors need to be
resolved, which can spawn new development cycles.
P.Sowmya Sree Unit-I Page 15
Algorithms
An algorithm is a method of representing step by step procedure for solving a
problem. An algorithm is very useful for finding the right answer to a problem or to a difficult
problem by breaking the problem into simple cases.
Advantages :-
1. It is the step by step solution to a given problem hence easy to understand.
2. It is very easy to draw a flowchart using Algorithm.
3. It is independent of programming language.
4. It is easy to debug as every step has got its own logical sequence.
5. It has got definite procedure to generate required output
Disadvantages
1. It is time consuming.
2. In large algorithm the flow of program controls becomes difficult to track
3. It is difficult to convert it into flowchart and then into a program
Flowchart Symbols
START
READ
A,B
C=A+B
PRINT
C
STOP
3. Pseudo code:
Pseudo code is a simple way of writing programming code in English. Pseudo
code is not actual programming language. It uses short phrases to write code for programs
before you actually create it in a specific language. Once you known what the program is about
and how it will function, then you can use pseudo code to create statements to achieve the
required results for your program.
It is used in planning an algorithm with sketching out the structure of the program before the
actual coding take a place.
Structured Programming
Introduction to C:
C is a procedural programming language. It was initially developed by
Dennis Ritchie in the year 1972 at bell laboratories of AT&T (American Telephone &
Telegraph), located in the U.S.A.It is developed for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
ALGOL 60
(Algorithmic Language developed in the year 1960 by an international committee)
CPL
(Combined Programming Language developed in 1963 by Cambridge University and
University of London)
BCPL
(Basic Combined Programming Language developed by Martin Richards of Cambridge
University in 1967)
B
(Developed by Ken Thompson of Bell Laboratories in 1970)
C
(Developed by Dennis Ritchie of Bell Laboratories in 1972)
Applications/uses of C Programming
C was initially used for system development work, particularly the
programs that make-up the operating system. C was adopted as a system
development language because it produces code that runs nearly as fast as the code
written in assembly language. Some examples of the use of C are -
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
It is a very simple and easy language, C language is mainly used for develop desktop based
application. All other programming languages were derived directly or indirectly from C
programming concepts. This language have following features;
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
6) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
documentation section :The documentation section contains a set of comment including the
name of the program other necessary details. Comments are ignored by compiler and are used
to provide documentation to people who reads that code. Comments are be giving in C
programming in two different ways:
1. Single Line Comment
2. Multi Line Comment
Link Section
The link section consists of header files while contains function prototype of Standard Library
functions which can be used in program. Header file also consists of macro declaration.
Example:
#include <stdio.h>
In the above code, stdio.h is a header file which is included using the preprocessing directive
#include. Learn more about header files in C programming.
Definition Section
The definition section defines all symbolic constants. A symbolic constant is a constant value
given to a name which can't be changed in program. Example:
#define PI 3.14
In above code, the PI is a constant whole value is 3.14
Global Declaration
In global declaration section, global variables and user defined functions are declared.
Subprogram Section
The subprogram section contains all the user defined functions. A complete and
fully functions C program can be written without use of user-defined function in C
programming but the code maybe be redundant and inefficient if user-defined functions are not
used for complex programs.
Note: Except for the main () function section, other sections of the C program may be omitted
as per the requirement of the program.
First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run
the first c program.
To write the first c program, open the C console and write the following code:
#include <stdio.h>
main()
{
printf("Hello C Language");
}
C Tokens
Classification of tokens in C
Keywords: These are certain reserved words. Those have a standard pre define meaning in C
language. These keywords can be used only for their internal purpose. They can not be used as
program defined identifiers. Identifiers are generally generated by the users. So these are called
user defined identifiers. But keywords are system define identifiers. They must be in lower case
letters.In ‘C’ we have 32 Keywords . They are as follows
Constants
C Constants is a most basic and important part of C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same
during the entire execution of the program.
• Constants are also called literals.
• Constants can be any of the data type.
• Syntax:
Constant Types in C
Integer Constant
Its refer to sequence of digits. Integers are of three types viz:
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Real constant
The numbers containing fractional parts like 99.25 are called real or floating points constant.
Single Character Constants
It simply contains a single character enclosed within ‘ and ‘ (pair of single quote). It is to be
noted that the character ‘8‘ is not the same as 8. Character constants have specific set of integer
values known as ASCII values (American Standard Code for Information Interchange).
Example:
‘X’, ‘5’, ‘;’
String Constants
These are sequence of characters enclosed in double quotes and they may include letters, digits,
special characters and blank-spaces. It is again to be noted that “G” and ‘G‘ are different –
because “G” represents string as it is enclosed within pair of double quotes whereas ‘G’
represents a single character.
Example:
“Hello!”, “2015”, “2+1”
Strings in C
Strings in C are always represented as an array of characters having null character '\0' at the end
of the string. This null character denotes the end of the string. Strings in C are enclosed within
double quotes, while characters are enclosed within single characters. The size of a string is a
number of characters that the string contains.
char a[10] = "Sowmya"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "Sowmya"; // The compiler allocates the memory at the run time.
Special characters in C
Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
Escape sequences :
A character constant can be any of the valid printing characters in
the ASCII character set enclosed in single quotes. They are assigned to an identifier through an
assignment statement just as in the case of the integer and floating point constants. We can
represent non printing characters such as a new line in a character constant with a two
character sequence. A new line character, for example, is represented as a backslash followed
by the letter n, (/n). Although, represented in two characters, it occupies only one character
space in storage. Some of the common escape sequences for character constants are,
\n new line
\r carriage return
\t horizontal tab
\f form feed
\a audible alert (bell)
\\ back slash
\v vertical tab
\’ single quote
\” double quotes
\? question mark
\-- null character
\b back space
Datatypes
Primary data types are the actual data types which are already defined in C and they
should be used in the same way as they are defined in C++.They are: integer (int), floating
(float), character (char) and void
Integer type : Integers are numbers without fractional points (i.e. decimal points).Integers are
allocated two bytes of storage i.e. two cells in the memory.
Example: int i;
Floating type: A float is a single precision floating point number. These numbers have a
precision of only 6 digits i.e. float can have 6 decimal points and it is fixed. Float are allocated
four bytes of storage i.e. four cells in the memory.
Character type: Character data type allocates one byte of memory i.e. one cell in the
memory. It capable of storing one character from the character set.
→Derived Datatypes: Derived data types are data types which can be created using basic data
types i.e. they are derived from basic data types
They are: arrays, pointers, functions.
→ User Defined Data types are the data types using which we can create our own data types
They are: structures, union, enumerations.
Operators
Operator is a symbol having pre defined meaning and that is used to perform some specific
operation. Operators acts on operands.
Here operands are nothing but a variable, a constant, or a value.
Based on the operands operators are classified into three types.
They are,
1. Unary operators: These operators act on single operand.
2. Binary operators: These operators act on two operands.
3. Ternary operators: These operators act on three operands.
1. Arithmetical Operators: C provides all the basic arithmetic operators which are used to
perform the basic arithmetic operations such as: “+ “Addition, “– “Subtraction
“* “Multiplication, “/ “Division,”%” Modules Division.
2.Relational Operators: Relational Operators is used to compare two operands given in the
expression. The result is either True or False. The relational operators come under category of
binary operator.
The Relational Operators are
“< “ Less than
“> “ Greater than Output:
“<= “ Less than or equal to The value of a<b is :1
“>= “ Greater than or equal to The value of a>b is: 0
“= “ Equal to The value of a<=b is :1
“== “ Comparison Equal to The value of a>=b is : 0
“!= “ Not equal to The value of a==b is :0
The value of a!=b is: 1
/*Sample program on Relational Operators*/
#include<stdio.h> Note: Here “1” means true and “0”
main() means false
{
int a=10,b=20;
3.Logical Operators: Logical Operators are used when we want to test more than one condition
in relational expression and making decision.
The expression which combines two or more relational expression is known as logical
expression or a compound relation expression.
False - True
4.Assignment Operators: It is used to assign or store a value on right hand side to the variable
on left hand side. There must be a single variable on the left hand side.
res = 11;
res -= 4;
printf("\nResult of Ex2 = %d", res);
res = 11;
res *= 4;
printf("\nResult of Ex3 = %d", res);
res = 11;
res /= 4;
printf("\nResult of Ex4 = %d", res);
res = 11;
res %= 4;
printf("\nResult of Ex5 = %d", res);
}
5.Increment And Decrement Operators These two operators are unary operators.
→Increment Operator: This Operator is used to increment the value of an integer by ‘1’.The
increment Operator symbol is ++ (double plus).
If we use this symbol (++) before an operand then it is known as prefix increment Operator.
Ex: ++a.
If we use this symbol (++) after an operator then it is known as post increment operator.
Ex: a++
Note: In the case of pre – fixing the operator with the variable it gets increments and then
participate in the operation whereas, if you post – fix the increment operation with the variable.
The variable participate in the expression with the old value and then increments
a = x++;
b = ++y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
getch();
}
→Decrement Operator: This operator is used to decrement the value of an integer by ‘1’,The
decrement operator symbol is—(double minus).
If we use this symbol (--) before an operand then it is known as prefix decrement Operator.
Ex:--a.
If we use this symbol (--) after an operator then it is known as post decrement operator.
Ex: a--
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,x=10,y=10;
clrscr();
a = x--;
b = --y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
getch();
}
6. Condition / Ternary Operator: They are also called as Ternary Operator .They also called as
“?:” operator. Ternary Operators takes on 3 Arguments
Note: In this, first, the condition is checked, if it returns true then the value returned by exp1
otherwise the value return by exp2
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf(“Even number”):printf(“Odd number);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b, c, big; Output:
clrscr(); Enter the Number : 58
printf(“Enter three numbers:”); Even number
scanf(“%d%d%d”,&a,&b,&c);
big=(a>b&&a>c)?a:((b>c)?b:c);
printf(“\nBiggest=%d”,big);
getch();
}
7.Bit wise Operators: All data items are stored in the computer’s memory as a sequences of
bits(0’s and 1’s).Bit wise operators are used for manipulation of the data at bit level. These
bitwise operators work with int and char type data only but not with float and double.
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
Comma Operator(,)
Sizeof() Operator
Address Operator(&)
Dereferencing Operator (*)
Dot Operator(.)
Arrow Operator(->)
→Sizeof() Operator: The sizeof operator is used with an operand,it returns the number of bytes
the operand occupies.The operand may be a variable,a constant or a datatype qualifier.
Expressions:
The combination of an operator and operands forms an expression.
The expressions are classified into 3 types.
They are,
Arithmetical Expression These are formed by using arithmetical operators.
Ex: a+b
Logical Expression These are formed by using relational operators.
Ex: a>b
Compound Expression These are formed by using logical operators.
Ex: a>b && a>c
Expression evaluation
In c++ language expression evaluation is mainly depends on priority and associativity.
Priority
This represents the evaluation of expression starts from "what" operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than
one operator with same priority.
Example 1:
Type Conversion
Converting one datatype into another is known as type casting or, type-conversion. There are
two types of type conversion:
1.Implicit Type Conversion
Implicit type casting means conversion of data types without losing its original
meaning. This type of typecasting is essential when you want to change data
types without changing the significance of the values stored inside the variable.
Implicit type conversion happens automatically when a value is copied to its
compatible data type.
//output
printf("Result = %d\n", result);
}
Output
Result=3
Chapter –I
Input and Output
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to display data
on screen when there is a need to output the result.
Unformatted console input/output functions are used to read a single input from the user at
console and it also allows us to display the value in the output to the user at the console.
1. getchar() : The getchar() function reads character type data form the input. The
getchar() function reads one character at a time till the user presses the enter key.
Syntax
/* getchar accepts character & stores in ch */
char ch = getchar();
Syntax:
putchar(var);
The gets() function reads string from user and puts() function prints the string. Both functions are
defined in <stdio.h> header file.
#include<stdio.h>
main()
{ Output:
char name[50]; Enter your name: Sowmya sree S
printf("Enter your name: "); Your name is: Sowmya sree
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
}
•scanf():
• scanf() function reads all the types of data values.
• It is used for runtime assignment of variables.
• The scanf() stops functioning when some input entered does not match format string
•printf()
❖ This function displays output with specified format
❖ It requires format conversion symbol or format string and variables names to the print the data
❖ The list of variables are specified in the printf() statement
❖ The values of the variables are printed as the sequence mentioned in printf()
❖ The format string symbol and variable name should be the same in number and type
Syntax
printf(“format specifier”, variable 1, variable 2,..., variable n);
Escape sequences are basically control characters used for formatting the output. These are
combinations of a backslash and a character in lowercase. We have already used “\n”, which shifts the
curser to the next line.
The following are the examples of an
escape sequence.
Chapter –II
Control Statements
Selection Statements
A structure which select which statement or block of statements will execute on the basis of our
programming logic.
The Selection statements /Decision making statements are:
➢ if
➢ if-else
➢ nested if
➢ nested if-else
Unit -2 C-language P.Sowmya Sree Page 4
➢ comma operator
➢ conditional operator
➢ Switch
if Statement:
The if statement is used to check some given condition and perform some operations
depending upon the correctness of that condition.
Syntax: if (condition)
{
Block of statements
}
if…else statement
It is similar to if statement i.e. It is also used to execute or ignore a set of statements
after testing a condition.In if-else statement one condition and two blocks of statements are
given.First blocks contain if statement with condition and its body
part.Second is else and it contain only body part.
Syntax:
if ( condition 1)
{
//If thecondition 1 is TRUE then it will check for condition 2
if (condition 2)
{
statement-1;
}
else
{
Statement-2;
}
else
{
//If the condition 1 is FALSE then these statements will be executed
statement-3
}
Here if the condition-1 is TRUE then it enters into if body and condition -2 will be checked ,if
condition-2 is TRUE then Statement-1 alone will be executed ,if condition-2 is FALSE then
Statement- alone will be executed .
If the Condition- 1 is FALSE then else block statement-3 will only be executed.
Flowchart of Nested if
#include<stdio.h>
main() Output:
{
int a=10,b=30,c=20; b is greatest number
if(a>b)
{
•Comma operator:
As an operator − The comma operator { , } is a binary operator that discards the first expression
(after evaluation) and then use the value of the second expression. This operator has the least
precedence.
Note: It gives a as output as it works because the ‘,’ works as operator but it precedence is below
assignment operator hence the output is a.
•conditional operator:
They are also called as Ternary Operator .They also called as “?:” operator. Ternary Operators
takes on 3 Arguments
Syntax: variable = (condition)? exp1: exp2;
❖ Switch statement:
o Switch is also a control structure and it is used to select one option from a set of options.
o It compares the value of an expression or a variable against a list of cases.
o The case labels and the value of expression or variable must be an integer or a character.
o It must not be a float or double value. If the value of expression in switch is float or double type
then the compiler will generate error message.
Syntax:
switch(expression)
{
case value 1: statement1;
break;
case value 2: statement 2;
break;
.
.
.
.
default: default statement;
}
for loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
for ( initialization; condition; increment /decrement)
{
statement(s);
}
Flow Chart
Output:
value of a:1
//Program to print numbers from 1 to 10 using for loop
value of a:2
#include<stdio.h>
value of a:3
void main()
value of a:4
{
value of a:5
int a;
value of a:6
for( a = 1; a <=10; a ++ )
value of a:7
{
value of a:8
printf("value of a: %d\n", a);
value of a:9
}
value of a:10
}
Syntax
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.
Flow Diagram
#include<stdio.h>
main()
{
int num,i=1,j,count;
printf(“Enter Num value To Print Prime Numbers between 1 and Num: ");
scanf(“%d”,&Num);
printf("Prime Numbers
upto:"<<num<<"\n");
Output:
while(i<=num)
Enter Num value To Print Prime Numbers between 1 and
{
Num: 10
count=0;
Prime Numbers upto: 10
for(j=1;j<=i;j++)
2
{
3
if(i%j==0)
5
count++;
7
}
if(count==2)
printf(“%d”,n);
i++;
}
Printf(“n\n”);
}
do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax do
{
statement(s);
}while( condition );
Flowchart
Output:
value of a:1
//Program to print numbers from 1 to 10 using do…while loop value of a:2
#include<stdio.h> value of a:3
main() value of a:4
{ value of a:5
int a = 1; value of a:6
do value of a:7
{ value of a:8
printf("value of a:%d\n ", a); value of a:9
a ++ ; value of a:10
} while( a <=10);
}
//Program to check whether a given number is amstrong or not
#include<stdio.h>
void main()
{
intorigNum, num, rem, sum = 0;
printf("Enter a positive integer: ");
scanf(“%d”,&origNum);
Output:
num = origNum;
Enter a positive integer: 153
while(num != 0)
{ 153 is an Armstrong number.
rem= num % 10;
sum =sum+(rem * rem * rem);
num =num/ 10;
}
if(sum == origNum)
► goto Statement:-
goto statement is used for altering the normal sequence of program execution by transferring
control to some other part of the program.
Syntax
goto label;
.. .. ... .
... .. ...
... .. ...
label:
statement;
... .. ...
The break statement terminates the loop (for, while and do...while loop) immediately when it is
encountered. The break statement is used with decision making statement such as if...else,switch.
Syntax break;
Flowchart
Output:
/*Example program on break*/ 0
#include<stdio.h> 1
main() 2
{ 3
int i; 4
for(i=0;i<=10;i++)
{
►continue Statement
The continue statement skips some statements inside the loop. The continue statement is used with
decision making statement such as if...else.
continue;
►return
The return statement returns the flow of the execution to the function from where it
is called. This statement does not mandatorily need any conditional statements. As soon as the
statement is executed, the flow of the program stops immediately and returns the control from where
it was called. The return statement may or may not return anything for a void function, but for a non -
void function, a return value is must be returned.
Examples:
return 10;
return a;
return a+b;
►exit: In C, exit() terminates the calling process without executing the rest code which is after the
exit() function. The return code "0" exits a program without any error message.
Syntax:
exit(0);
Chapter –III
ARRAYS:
Array is a collection of similar data type. A single variable can hold only one value at a time,
If we want a variable to store more than one value of same type we use array. Array is linear data
structure.
(Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.)
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −
Example:
int a[6];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as follows:
The number of values between braces { } cannot be larger than the number of elements that we declare
for the array between square brackets [ ].
Example: int a[5]={2,3,4,5,6};
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore,
if you write:
int a[]={2,3,4,5,6};
For example, an array containing 5 integer values of type int called ‘a’ could be represented as:
#include<stdio.h>
main()
{ Output:
int a[10],i,n; Enter the size of an array:5
printf(“Enter the size of an array:”); Enter the array elements
scanf(“%d”,&n); 12345
printf(“\nEnter the array elements”); the elements are:
for(i=0;i<n;i++)
1
scanf(“%d”,&a[i]); //reading elements into an array
2
printf(“\nthe elements are:\n”);
for(i=0;i<n;i++) 3
printf(“%d\n”,a[i]); //displaying elements from an array 4
} 5
for(i=0;i<n;i++)
{ Output:
printf("Enter element %d:",i+1); Enter number of elements
scanf(“%d”, Arr[i]); you want to insert 4
} Enter element 1:10
Enter element 2:1
small=Arr[0]; Enter element 3:30
large=Arr[0]; Enter element 4:100
for(i=1;i<n;i++) Largest element is : 100
{
Smallest element is : 1
if(Arr[i]<small)
small=Arr[i];
if(Arr[i]>large)
large=Arr[i];
}
Syntax:datstype name[size1][size2]...[sizeN];
datatype arrayName [ x ][ y ];
.Where type can be any valid C data type and arrayName will be a valid C identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four columns can be shown as
below:
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.
Two-Dimensionalarrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row have 4 columns.
int a[3][4]={
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous
example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array.
For example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row
of the array.
Output:
//Example Program on two dimensional array
#include<stdio.h> a[0][0]: 0
main()
{ a[0][1]: 0
// an array with 5 rows and 2 columns.
int i,j,a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; a[1][0]: 1
// output each array element's value a[1][1]: 2
for ( i=0; i < 5; i++ )
for ( j = 0; j < 2; j++ ) { a[2][0]: 2
printf( "a[%d][%d]:%d\n",i,j,a[i][j]);
a[2][1]: 4
}
} a[3][0]: 3
→Multi Dimensional array a[3][1]: 6
C++ allows multidimensional arrays.
Syntax: a[4][0]: 4
type name[size1][size2]...[sizeN];
Example:int threedim[5][10][4]; a[4][1]: 8
Initialisation of three dimensional array
Declaration of a String:
The general format for declaring String variable is
Initialization of String:
Character arrays may be initialize when they are declared.The initialization can be done in
either of the following ways.
'C' allows to initialize a character array without specifying the size .In this case, the size will be
determined automatically based on the number of elements initialized.
Ex:- char name[]="SACHIN";
}
/* Program to print the string in following format
S
SO
SOW
SOWM
SOWMY
SOWMYA
*/
#include<stdio.h>
main()
{
char name[]="SOWMYA";
int i,j;
for(i=0;i<=6;i++)
{
for(j=0;j<i;j++)
printf("%c",name[j]);
printf("\n");
}
}
1. strlen() function: This function counts and returns the number of characters in a string.
Syntax:n=strlen(string);
Here 'n' is an integer variable which receives the value of the length of the string.
/* program to calculate the length of the string */
#include<stdio.h>
#include<string.h>
main()
{
char s[15]="hello";
printf("length of hello is :%d",strlen(s));
}
Output:
Length of hello is :5
String 1 and string2 are character arrays.when the strcat() function is executed,string2 is appended to
string1.It does so by removing the null character at the end of string1 and placing string2 from there
.The string at string2 remains unchanged.
Output:
After concatenation:
Hello world
Output:
First string:hello
Second string:hello
4.strcmp() function:This function compares two strings and has a value 0 if they are equal.If they are
not equal it has the numberic difference between the ASCII values of the first non-matching pairs of
characters.
ctype.h
❖ The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.
❖ All the functions return non-zero (true) if the argument c satisfies the condition described, and
zero(false) if not.
1.isalnum():
The C library function void isalnum(int c) checks if the passed character is alphanumeric.
/*program on isalnum()*/
#include <stdio.h> OUTPUT:
main()
{ Enter any character
char ch; @
printf("Enter any character\n"); Entered character is not alphanumeric
scanf("%c", &ch);
if ( isalnum ( ch ) )
printf ( "\nEntered character is alphanumeric" ) ;
else
printf ( "\nEntered character is not alphanumeric" ) ;
}
2.isalpha():
3.iscntrl():
iscntrl( ) function in C language checks whether given character is control character or not.
Syntax
int iscntrl( int x );
4.isdigit():
Syntax
int isdigit ( int x );
5.isgraph():
isgraph( ) function in C language checks whether given character is graphical character or not.
Syntax
int isgraph( int x );
#include <stdio.h>
main()
{
char string[50] ="fresh 2 refresh \n string"; OUTPUT:
int i = 0; fresh
while(1)
{
if(isgraph(string[i]))
{
putchar(string[i]);
i++;
}
else break;
}
}
6.islower():
islower( ) function in C language checks whether given character is lower case or not.
Syntax
int islower( int x );
#include <stdio.h>
int main() OUTPUT:
{ Enter any character
char ch; a
printf("Enter any Entered character is lower case character
character\n");
scanf("%c", &ch);
if ( islower ( ch ) )
printf ( "\nEntered character is lower case character") ;
else
printf("\nEntered character is not lower case character");
}
7.isprint():
• isprint( ) function in C language checks whether given character is printable character or not.
Syntax for isprint( ) function is given below.
int isprint( int x );
8. ispunct()
9. isspace()
isspace( ) function in C language checks whether given character is space or not.
Syntax
int isspace( int x );
10. isupper()
isupper( ) function in C language checks whether given character is upper case or not.
Syntax
int isupper ( int x );
if ( isupper ( ch ) )
printf ("\nEntered character is uppercase character");
else
printf("\nEntered character is not uppercase character");
}
10. isxdigit()
isxdigit( ) function in C language checks whether given character is hexadecimal or not.
Syntax
int isxdigit( int x );
11. tolower()
tolower( ) function in C language checks whether given character is alphabetic and converts to
lowercase.
Syntax
int tolower( int x );
if(isalpha(ch))
printf ( "\nEntered character is converted into " \
"lower character : %c\n",tolower ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}
12. toupper()
toupper( ) function in C language checks whether given character is alphabetic and
converts to uppercase.
Syntax:
int toupper( int x );
Types of functions
Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming
♦ User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by
the user are called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many
user-defined functions as you want.
►USES OF FUNCTIONS:
o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
o
►Defining a Function
The general form of a function definition in C programming language is as follows –
►Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts − return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows –
Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration –
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top of the file
calling the function.
return result;
}
return statement
• A function may or may not return a value. A return statement returns a value to the calling
function and assigns to the variable in the left side of the calling function.
• If a function does not return a value, the return type in the function definition and declaration is
specified as void.
Syntax:
return(expression);
#include<stdio.h>
void fact(int,int);
main()
{
int f=1,n;
printf("Enter the number:");
scanf("%d",&n); Output:
fact(n,f);
} Enter the number:5
void fact(intn,int f)
{ Factorial of 5 is 120
int i;
for(i = 1; i <= n; i++)
{
f = f*i;
}
printf("Factorial of %d is %d", n , f);
}
Actual Parameters: Actual Parameters are those, which are specified at the time of
function calling.
Formal Parameters: Formal Parameters are those, which are defined in the function
declaration and function definition.
Call By Value
This is the safest way to call the functions. In this method, Values of the declared variables are passed as
the parameters to the function. When we pass the values to the function,
• Compiler is actually making a clone or copy of the original value and then passing that clone
values to the function instead of original values.
• So, Any changes made to the values of the variables inside function does not reflect the original
values.
#include <stdio.h>
void CallByValue(int , int );
int main()
{
int a, b;
printf ("\nPlease Enter 2 Integer Values\n");
scanf("%d %d", &a, &b);
printf("\nBefore Calling CallByValue() Function A = %d and B = %d", a, b);
CallByValue(a, b);
printf(" \nAfter Calling CallByValue From Main() A = %d and B = %d", a, b);
}
voidCallByValue(int a, int b)
{
a = a * 10;
b = b * 20;
printf(" \nFrom the CallByValue() Function A = %d and B = %d", a, b);
}
Output:
10
20
Call By Reference
In this method, Address of the declared variables are passed as the parameters to the function. When we
pass the address of the variable to the function,
• Function is actually accessing the address of the original value (Referring the address).
• So, Any changes made to the values of the variables inside function means we are actually
changing the original values.
#include <stdio.h>
void Swap(int *, int *);
int main()
{
int a, b;
UNIT-III P.SOWMYA SREE Page 7
printf ("Please Enter 2 Integer Values");
scanf("%d %d", &a, &b);
printf("\nBefore Swap A = %d and B = %d", a, b);
Swap(&a, &b);
printf(" \nAfter Swapping From Main() A = %d and B = %d", a, b);
}
Output:
Scope of a variable:
A scope is a region of a program. Variable Scope is a region in a program where a variable is
declared and used.
►Storage Classes in C
Storage Classes defines the scope and life time of variable declare in a function.Types of Storage
Classes
• Auto ( Automatic ) or Local Variable
• Static variable
• Extern ( External ) or Global Variable
• Register Variable
main()
{
int n; // n is a local variable to main() function
... .. ...
}
void func()
{
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed
when main() exits.
2. static Variable:
Static variable also have local scope as automatic variables. During multiple calling static
variables retains their previous value.
• We must declare variable as static.
• Static variables can't be accessed outside the function.
• If not initialized static variables have zero as initial value.
•
Syntax of static storage class
static Data-type Variable-name;
In the above example, we does not use static keyword then the output will be :
Output :
A:1
A:1
A:1
OR
Data-type Variable-name;
#include<stdio.h>
void display();
int a=10; //global variable
main()
{
printf("\nA : %d",a); Output :
increment();
display(); A : 10
printf("\nA : %d",a); A : 20
} A : 20
4. register variables:
Register variables have local scope as automatic variables. They are declared within
motherboard's register memory. All the arithmetic and logical operations are carried out within these
registers.
• These variables are stored in registers. If registers are not available values are stored in main
memory.
• Register variables works faster then other kind of variables because register memory is fatser
then main memory.
• Address operator '&' can't be used with these variables.
• Pointer to register variables are not allowed.
• These variables are used for loops to increase efficiency.
Syntax of register storage class
register Data-type Variable-name;
Inline Functions:
The inline function can be substituted at the place where the function call is happening. Function
substitution is always compiler choice.
• In an inline function, a function call is replaced by the actual program code.
• Most of the Inline functions are used for small computations. They are not suitable for large
computing.
• An inline function is similar to a normal function. The only difference is that we place a keyword
inline before the function name.
Syntax:
inline function_name ()
{
//function definition
}
Recursion in C
When a function calls itself from its body is called Recursion.
Advantages
• Reduce unnecessary calling of function.
• Through Recursion one can Solve problems in easy way while its iterative solution is very big
and complex.
/*factorial of a number using recursion*/
#include<stdio.h>
long Factorial(int);
main() Output :
{
int num; Enter any positive number :10
long fact;
printf("\n\tEnter any positive number : "); The Factorial of 10 is 3628800
scanf("%d",&num);
fact = Factorial(num);
printf("\n\tThe Factorial of %d is %ld",num,fact);
}
long Factorial(intnum)
{
if (num == 1)
return 1;
else
return num*Factorial(num-1);
}
Introduction to Pointers
A pointer is a derived data type in C. It is built from one of the fundamental data types available
in C. A Pointer is a variable that holds address of another variable of same data type.
Pointer concept
Whenever a variable is declared in the program, system allocates a location i.e an address to that
variable in the memory, to hold the assigned value. This location has its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;
We can access the value 10 by either using the variable name a or the address 80F. Since the memory
addresses are simply numbers they can be assigned to some other variable. The variable that holds
memory address are called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address, which is a location of
another variable. Value of pointer variable will be stored in another memory location.
data-type *pointer_name;
Data type of a pointer must be same as the data type of a variable to which the pointer variable is
pointing. void type pointer works with all data types, but is not used often used.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
►Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of
variable, pointer is dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will
be stored as follows:
Here variable arr will give the base address, which is a constant pointer pointing to the element,arr[0].
Therefore arr is containing the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of
an array and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] //by default
Now we can access every element of array arr using p++ to move from one element to
another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
printf("\nValues : ");
for(a=1;a<=10;a++)
{
printf("%d, ",*ptr); // Displaying values of array
// using pointer
ptr++; // Incrementing pointer variable
}
}
Output:
Values : 78, 45, 12, 89, 56, 23, 79, 46, 13, 82,
Syntax:
char var[size]=”value”;
char *ptr;
Example:
char str[6]=”Hello”
char *ptr;
ptr=str;
// pointer variable
char *ptr = str;
Pointer to Pointer:
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the
address of the second pointer, which points to the location that contains the actual value as shown
below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer
of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that
the asterisk operator be applied twice, as is shown below in the example:
Array of Pointer:
Array is a collection of values of similar type. It can also be a collection of references of similar type.
Example:
#include<stdio.h>
main()
{
int x=10,y=20,z=30;
int *arr[3],a; // Declaring array of three pointer
arr[0] = &x; // Assigning reference of x to array 0th position
arr[1] = &y; // Assigning reference of y to array 1th position
arr[2] = &z; // Assigning reference of z to array 2nd position
printf("\nValues : "); Output:
for(a=0;a<3;a++)
printf("%d, ",*arr[a]);
Values : 10, 20, 30,
}
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
► calloc()
This statement will allocate contiguous space in memory for an array of nelements. For example:
This statement allocates contiguous space in memory for an array of 25 elements each of size of float,
i.e, 4 bytes.
►free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
► realloc()
If the previously allocated memory is insufficient or more than required, you can change the previously
allocated memory size using realloc().
Syntax of realloc()
Structure
Syntax
struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
Example:
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Syntax:
struct struct-name variable1, variable2…;
Or
Structure variable can be declared while creating the structure
Example:
struct Employee e1,e2;
or
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
}e1,e2;
► Initialization of structure:
Like normal variable structures can be initialized at the time of declaration. Initialization of
structure is almost similar to initializing array. The structure object is followed by equal sign and
the list of values enclosed in braces and each value is separated with comma.
Syntax:
struct struct-name var_name={values….};
or
var_name.member=value;
Example:
struct Employeee E1={ 2,"Suresh",35,35000};
or
E1.Id=2;
E1.Name=”Suresh”;
Syntax
struct struct-name obj;
printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);
Details of Employees
printf("\n\tEnter Employee Id : ");
101 Suresh 29 45000
scanf("%d",&Emp[i].Id);
102 Mukesh 31 51000
103 Ramesh 28 47000
printf("\n\tEnter Employee Name : ");
scanf("%s",&Emp[i].Name);
printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
Union
Both structure and union are collection of different datatype. They are used to
group number of variables of different type in a single unit.
►Union declaration
Declaration of union must start with the keyword union followed by the union name and
union's member variables are declared within braces.
Syntax:
union union-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
Example:
Union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Defining an union like creating and naming a new data type. Memory is allocated to the
member variables of union when union variables are declared
Syntax:
union union -name variable1, variable2…;
Or
union variable can be declared while creating the union
Example:
union Employee e1,e2;
or
union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
}e1,e2;
► Initialization of union:
Like normal variable union can be initialized at the time of declaration. Initialization of
union is almost similar to initializing array.
Syntax:
var_name.member=value;
Example:
E1.Id=2;
Syntax
union union-name obj;
Example Output:
void main()
{
printf("\nSize of Employee1 is : %d",sizeof(E1));
printf("\nSize of Employee2 is : %d",sizeof(E2));
}
►Enumeration Types
The enum in C is also known as the enumerated type. It is a user-defined data type that
consists of integer values, and it provides meaningful names to these values. The use of enum in
C makes the program easy to understand and maintain. The enum is defined by using the enum
keyword.
syntax
Example:
enum fruits{mango, apple, strawberry, papaya};
main()
{
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
}
Output:
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C
programming language provides access on high level functions as well as low level (OS level)
calls to handle file on your storage devices.
►Types of Files
When dealing with files, there are two types of files you should know about:
Text files
Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than
text files.
FILE *fptr;
► File Operations
In C, you can perform four major operations on files, either text or binary:
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
ptr = fopen("fileopen","mode");
w+ Open for both reading and If the file exists, its contents
writing. are overwritten.
If the file does not exist, it
will be created.
wb+ Open for both reading and If the file exists, its contents
writing in binary mode. are overwritten.
If the file does not exist, it
will be created.
a+ Open for both reading and If the file does not exist, it
appending. will be created.
ab+ Open for both reading and If the file does not exist, it
appending in binary mode. will be created.
fopen("E:\\cprogram\\oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram. The
second function opens the existing file for reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
Closing a File
The file (both text and binary) should be closed after reading/writing.
For reading and writing to a text file, we use the functions fprintf() and fscanf()
They are just the file versions of printf() and scanf(). The only difference is that fprint() and
fscanf() expects a pointer to the structure FILE.
if(fptr == NULL)
{
printf("Error!");
}
fprintf(fptr,"%d",num);
fclose(fptr);
}
This program takes a number from the user and stores in the file ” program.txt.”
After you compile and run this program, you can see a text file “program.txt” created in C drive
of your computer. When you open the file, you can see the integer you entered.
fscanf(fptr,"%d", &num);
If you successfully created the file from Example 1, running this program will get you the integer
you entered.
Other functions like fgetw, fputc() etc. can be used in a similar way.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
int main()
{
int n;
struct threeNum num;
FILE *fptr;
We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main
function as num.
Now, inside the for loop, we store the value into the file using fwrite().
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter
*fptr points to the file we're storing the data.
Function fread() also take 4 arguments similar to the fwrite() function as above.
struct threeNum
{
int n1, n2, n3;
};
main()
{ Output
int n;
n1: 1 n2: 5 n3: 6
struct threeNum num;
FILE *fptr; n1: 2 n2: 10 n3: 11
}
In this program, you read the same file “program.bin” and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr
into the structure num.
There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.
Example:
#include <stdio.h>
main()
{ myfile.txt
FILE *fp;
This is sonoo jaiswal
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);
ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.
Syntax:
long int ftell(FILE *stream)
Example:
#include <stdio.h>
main () Output:
{
FILE *fp; Size of file: 21 bytes
int length;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}
rewind() function
Example:
File: file.txt
Output
this is a simple text
this is a simple textthis is a simple text
File: rewind.c
#include<stdio.h>
main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
}
As you can see, rewind() function moves the file pointer at beginning of the file that is why "this
is simple text" is printed 2 times. If you don't call rewind() function, "this is simple text" will be
printed only once.
function Purpose
fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax :
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello friend !\n");//writing data into file
fclose(fp);//closing file
}
fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Example:
#include <stdio.h> Output:
main()
{ Hello friend !
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a
stream.
Syntax:
int fputc(int c, FILE *stream)
Example:
file1.txt
#include <stdio.h>
main() a
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream.
It returns EOF at the end of file.
Syntax:
int fgetc(FILE *stream)
Example:
#include<stdio.h>
main() Output:
{
FILE *fp; a
char c;
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
}
putw() function
The putw() function is used to write integers to the file.
Syntax
putw(int number, FILE *fp);
The putw() function takes two arguments, first is an integer value to be written to the file and
second is the file pointer where the number will be written.
Example
#include<stdio.h>
main()
{ Output:
FILE *fp;
int num; Enter any number :59
char ch='n';
fp = fopen("file3.txt","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
putw(num,fp);
fclose(fp);
}
getw() function
The getw() function is used to read integer value form the file.
Example
#include<stdio.h>
void main()
{
FILE *fp;
int num; Output:
printf("\nData in file...\n");
fclose(fp);
}
1.Write a program to find the largest two (three) numbers using if and conditional
operator
#include<stdio.h>
main()
{
int a, b, res;
printf("Enter two numbers : ") ;
scanf("%d %d ", &a, &b) ;
res=a>b?a:b>a?b:-1;
if(res==-1)
printf("\nThe two numbers are equal”) ;
else
printf(“\n The larger number is %d”,res);
}
Output:
Enter two numbers :
40
50
The larger number is 50
#include<stdio.h>
main()
{
int n,sum = 0,rem,m;
printf("\nEnter a Number:\t");
scanf("%d", &n);
m= n;
while(n > 0)
{
rem = n%10;
sum = (sum*10) + rem;
n = n/10;
}
printf("\nReverse of %d:\t%d\n", m, sum);
}
Output:
1
Computer Science Sem-1
3. Write a program to print the prime number from 2 to n where n is given by user
#include<stdio.h>
main()
{
int num,i=1,j,count;
printf("Enter Num value To Print Prime Numbers between 1 and Num: ");
scanf("%d",&num);
printf("Prime Numbers upto %d :\n \n",num);
while(i<=num)
{
count=0;
for(j=1;j<=i;j++)
{
if(i%j==0) //checking whether num is dvisible by j
count++;
}
if(count==2) //if num is divisible by 2 numbers,then it is prime
printf("%d ",i);
i++;
}
printf("\n\n");
}
Output:
2357
4. Write a program to find the roots of a quadratic equation using switch statement
#include<stdio.h>
#include<math.h>
main()
{
int flag;
float x, x1, x2;
float a, b, c, d;
float rpart, ipart;
printf("\n Enter 3 numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a==0)
{
x=-b/c;
printf("\n Only root x : %7.3f", x);
exit();
}
d=(b*b)-(4*a*c);
if(d>0)
flag=1;
2
Computer Science Sem-1
else if(d==0)
flag=2;
else
flag=3;
switch(flag)
{
case 1: printf("\n Real & Distinct roots are: ");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("\n x1=%7.3f \n x2=%7.3f", x1, x2);
break;
case 3: d=sqrt(abs(d));
rpart=-b/(2*a);
ipart=d/(2*a);
printf("\n Complex Roots are: ");
printf("\n x1=%7.3f+i%7.3f", rpart, ipart);
printf("\n x2=%7.3f-i%7.3f", rpart, ipart);
}
}
Output:
Enter 3 numbers:
5
8
4
5.Write a program to print a triangle of stars as follows (take number of lines from user):
*
***
*****
*******
#include <stdio.h>
main()
{
int i, space, rows, k=0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i, k=0)
{
3
Computer Science Sem-1
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}
while(k != 2*i-1)
{
printf("* ");
++k;
}
printf("\n");
}
}
Output:
#include<stdio.h>
main()
{
int a[50],i,n,large,small;
printf("Enter the size of an Array");
scanf("%d",&n);
printf("Enter the Array:");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("The largest element is %d",large);
printf("\nThe smallest element is %d",small);
}
Output:
Enter the size of an Array 5
Enter the Array:
10
50
40
20
30
The largest element is 50
The smallest element is 10
4
Computer Science Sem-1
7. Write a program to find the product of two matrices.
#include <stdio.h>
main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
}
Output:
Enter the number of rows and columns of first matrix
2
2
Enter the elements of first matrix
1
2
3
4
Enter the number of rows and columns of second matrix
2
2
5
Computer Science Sem-1
Enter the elements of second matrix
2
3
4
5
Product of entered matrices:-
10 13
22 29
8. Write a program to find the GCD of two numbers using iteration and recursion.
a) Using iteration
#include <stdio.h>
main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
Output:
Enter two integers:
10
20
G.C.D of 10 and 20 is 10
b) Using Recursion
#include <stdio.h>
int gcd(int n1, int n2);
main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
#include<stdio.h>
extern int x=9;
int z=10;
main()
{
auto int a=32;
register char b='G';
extern int z;
printf("Hello World!\n");
printf("\n This is the value of the auto integer 'a':%d\n",a);
printf("\n These are the values of the extern integers 'x' and 'z'\n respectively:%d and
%d\n",x,z);
printf("\n This is the value of the \n register character 'b':%c\n",b);
x=2;
z=5;
printf("\n These are the modified values \n of the extern integers 'x' and \n 'z' respectively:%d
and %d \n",x,z);
printf("\n 'y' is a static variable and its \n value is NOT initialized to 5 after \n the first
iteration! see for \n yourself:");
while(x>0)
{
static int y=5;
y++;
printf("The value of y is %d\n",y);
x--;
}
}
Output:
Hello World!
These are the values of the extern integers 'x' and 'z'
respectively:9 and 10
7
Computer Science Sem-1
'y' is a static variable and its
value is NOT initialized to 5 after
the first iteration! see for
yourself:The value of y is 6
The value of y is 7
10. Write a program to demonstrate the call by value and the call by reference concepts
a)Call by Value
#include<stdio.h>
void swap(int,int);
main()
{
int a,b;
printf("Enter any 2 values\n");
scanf("%d%d",&a,&b);
printf("\nBefore swapping a and b values are \n %d \t %d \n",a,b);
swap(a,b);
printf("\nAfter swapping a and b values are \n %d \t %d in main()",a,b);
}
void swap(int a, int b)
{
int temp;
temp =a;
a=b;
b=temp;
printf("\nAfter swapping a and b values are \n %d \t %d \n",a,b);
}
Output:
b)Call by Reference
#include<stdio.h>
void swap(int *,int*);
main()
{
int a,b;
8
Computer Science Sem-1
printf("Enter any 2 values\n");
scanf("%d%d",&a,&b);
printf("\nBefore swapping a and b values are \n %d \t %d \n",a,b);
swap(&a,&b);
printf("\nAfter swapping a and b values are \n %d \t %d in main()",a,b);
}
void swap(int *a, int *b)
{
int temp;
temp =*a;
*a=*b;
*b=temp;
}
Output:
Enter any 2 values
10
20
11. Write a program that prints a table indicating the number of occurrences of each alphabet in
the text entered as command line arguments.
#include<stdio.h>
#include<string.h>
#define max_size 100 //maximum size of a string
int main()
{
char string[max_size];
int i,len;
int occurance[26];
/*Read the text from the user */
printf("Enter any Text\n");
gets(string);
len=strlen(string);
/*Initialized occurances of each character*/
for(i=0;i<26;i++)
{
occurance[i]=0;
}
/*Finding total number of occurrences*/
for(i=0;i<len;i++)
{
if(string[i]>='a' && string[i]<='z')
{
occurance[string[i]-97]++;
}
9
Computer Science Sem-1
else if(string[i]>='A' && string[i]<='Z')
{
occurance[string[i]-65]++;
}
}
#include<stdio.h>
main()
{
enum day
{
sunday,monday,tuesday,wednesday,thursday,
friday,saturday
};
enum day today;
int x;
printf("Enter the day of the week(0-6)\n");
scanf("%d",&x);
today=x;
if(today==sunday || today==saturday)
printf("\n Weekend\n");
else
10
Computer Science Sem-1
printf("Working day\n");
}
Output:
13. Write a program to demonstrate use of string functions string.h header file
#include <stdio.h>
#include<string.h>
main()
{
char ch1[10],ch2[10];
char ch3[15]="GoodMorning!";
int len;
printf("Enter the string\n");
scanf("%s",ch1);
len=strlen(ch1);
printf("Number of characters in a given string =%d",len);
strcpy(ch2,ch1);
printf("\n copied string is %s",ch2);
printf("\ncomparision of two strings is %d",strcmp(ch1,ch2));
printf("\nconcatination of two strings ch1 and ch3 %s",strcat(ch1,ch3));
}
Output:
14. Write a program that opens a file and counts the number of characters in a file.
#include<stdio.h>
main() {
char ch;
int count=0;
FILE *fptr;
fptr=fopen("text.txt","w");
if(fptr==NULL) {
printf("File can't be created\a");
exit(0);
}
printf("Enter some text and press enter key:\n");
while((ch=getche())!='\r') {
11
Computer Science Sem-1
fputc(ch,fptr);
}
fclose(fptr);
fptr=fopen("text.txt","r");
printf("\nContents of the File is:");
while((ch=fgetc(fptr))!=EOF) {
count++;
printf("%c",ch);
}
fclose(fptr);
printf("\nThe number of characters present in file is: %d",count);
}
Output:
Enter some text and press enter key:
hello how are you
Contents of the File is:hello how are you
The number of characters present in file is: 18
15. Write a program to create a structure Student containing fields for Roll No., Name, Class,
Year and Total Marks. Create 3 students and store them in a file.
#include<stdio.h>
struct student
{
int rollno;
char name[20];
char class[10];
int year;
int totalmarks;
}
main()
{
struct student s1[3],s2[3];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0; i<3; ++i) {
fflush(stdin);
printf("Enter roll number:");
scanf("%d",&s1[i].rollno);
printf("Enter your name");
scanf("%s",s1[i].name);
printf("Enter your class");
scanf("%s",s1[i].class);
printf("Enter Year");
scanf("%d",&s1[i].year);
printf("Enter totalmarks");
scanf("%d",&s1[i].totalmarks);
printf("\n");
}
fwrite(s1,sizeof(s1),1,fptr);
fclose(fptr);
12
Computer Science Sem-1
fptr=fopen("file.txt","rb");
fread(s1,sizeof(s1),1,fptr);
for(i=0; i<3; ++i)
{
printf("\n Roll no: %d \n Name: %s \n Class: %s \n Year:%d\n
Totalmarks:%d\n",s1[i].rollno,s1[i].name,s1[i].class,s1[i].year,s1[i].totalmarks);
}
fclose(fptr);
}
Output:
Roll no: 45
Name: AAA
Class: MPCs
Year:2020
Totalmarks:541
Roll no: 68
Name: BBB
Class: MSCs
Year:2021
Totalmarks:650
Roll no: 84
Name: CCC
Class: MECs
Year:2022
Totalmarks:490
13
Computer Science Sem-1
16. Write a program that opens an existing text file and copies it to a new text file with all
lowercase letters changed to capital letters and all other characters unchanged.
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("d:\myfile.txt","r");
if(fp1==NULL)
{
puts("\n cannot open file:");
exit(1);
}
fp2=fopen("d:\myfile1.txt","w");
if(fp2==NULL)
{
puts("\n Not able to open file:");
exit(1);
fclose(fp2);
}
do
{
ch=fgetc(fp1);
ch=toupper(ch);
fputc(ch,fp2);
}while(ch!=EOF);
fcloseall();
}
Note: The text in “myfile.txt” is copied into “myfile1.txt” with all lowercase letters changed to
uppercase letters. Check the file “myfile1.txt”.
14
Computer Science Sem-1