Introduction To Computer and Programming
Introduction To Computer and Programming
Computer is now an essential part of our daily life, and also an important factor in science and
technology.
A computer system consist of hardware, the mechanical and electronic devices that are capable
of computing and manipulating information, and software, i.e., programs that carry out
predefined instruction to complete a given task. Computer software communicates with the
hardware to perform useful tasks – the software organizes the control sequences, and the
hardware carry out the instructions defined by the software.
Electronic Computers
The advance of semiconductor technology has made computing affordable.
The reduction in price and improvement in performance has made computer much more
affordable and powerful.
The first important improvement of so-called computer is from mechanical to electronic in
1930s.
The first large-scale digital computer ENIVAC was built in 1946 by University of
Pennsylvania.
The first generation computer, built between 1939 and 1957, used vacuum tubes,
which consumed a lot of power and space. They tend to overheat and burn out
quickly; as a result they were expensive and unreliable. They are mainly for scientific
use due to its high costs.
The second-generation computers use transistors instead of vacuum tubes. They use
less power, take up less space, and become more reliable and less expensive. Now the
computers become more affordable and more business can use them.
The third-generation computers use integrated circuit (IC) technology that integrates
many electronic components into a single silicon chip, to make computers faster,
smaller, and cheaper.
The forth generation computers take one step further and introduce Large-scale
integration (LSI) and Very Large Scale Integration (VLSI) so that we can package an
entire processor into a single chip.
Programming has evolved from a tedious error-prone job to machine-assisted, semi-
automatic process.
Computers are classified according to their sizes and speed. They are microcomputer,
minicomputers, mainframe computers, and super computers.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Components of a Computer
There are four basic components in a computer system.
Central Processing Unit (CPU)
The main purpose of CPU is to process data in main memory. CPU is capable of
arithmetic and logic operation on data stored in main memory.
Main memory
The computer software (or program) and the data it wants to manipulate are stored in
main memory. The instruction of program are fetched from memory by CPU and
executed. The data are also stored in memory to retain their value, or state.
Secondary storage
The secondary storage provides large, non-volatile, and inexpensive storage for
program and data.
Input/Output (I/O) devices
I/O devices provide channels to transmit/receive data to/from a computer.
Memory consists of cells, which are indexed by address.
A cell consists of several bytes. Each byte has 8 bits.
Memory can be random access memory (RAM) or read-only memory (ROM), or FLASH.
RAM can only store data temporarily, i.e. it is a volatile storage device.
Secondary storage provides semi-permanent storing capability.
Hard disk is the most popular secondary storage devices for its high capacity and low
costs.
CPU is a complicated chip to handle all the computation within a computer. It has registers
and cache memory to store the instruction and data retrieved from main memory, and
complicated decoding circuit to determine what action should be performed, and an ALU
(arithmetic and logic unit) with circuit to carry out the actual computation.
A high level language can address memory cell by names, rather than address.
Different types of programming language
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers.
While easily understood by computers, machine languages are almost impossible for humans to use
because they consist entirely of numbers. Programmers, therefore, use either a high-level
programming language or an assembly language. An assembly language contains the same
instructions as a machine language, but the instructions and variables have names instead of being
just numbers.
Programs written in high-level languages are translated into assembly language or machine
language by a compiler. Assembly language programs are translated into machine language by a
program called an assembler.
Every CPU has its own unique machine language. Programs must be rewritten or recompiled,
therefore, to run on different types of computers.
Low level languages are used to write programs that relate to the specific architecture and hardware
of a particular type of computer.
They are closer to the native language of a computer (binary), making them harder for programmers
to understand.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Assembly Language
Machine Code
Assembly Language
Few programmers write programs in low level assembly language, but it is still used for developing
code for specialist hardware, such as device drivers.
It is easy distinguishable from a high level language as it contains few recognisable human words
but plenty of mnemonic code.
Advantages
Can make use of special hardware or special machine-dependent instructions (e.g. on the specific
chip)
Translated program requires less memory
Write code that can be executed faster
Total control over the code
Can work directly on memory locations
Machine Code
High level languages are written in a form that is close to our human language, enabling to
programmer to just focus on the problem being solved.
No particular knowledge of the hardware is needed as high level languages create programs that are
portable and not tied to a particular computer or microchip.
These programmer friendly languages are called ‘high level’ as they are far removed from the
machine code instructions understood by the computer.
Advantages
An operating system (OS) is system software that manages computer hardware and software
resources and provides common services for computer programs.Often abbreviated as OS, an
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
operating system is a powerful, and usually large, program that controls and manages the hardware
and other software on a computer.
All computers and computer-like devices have operating systems, including your laptop, tablet,
desktop, smartphone, smartwatch, router...you name it.
Laptops, tablets, and desktop computers all run operating systems that you've probably heard of.
Some examples include versions of Microsoft Windows (like Windows 10, Windows 8, Windows
7, Windows Vista, and Windows XP), Apple's macOS (formerly OS X), iOS, Chrome OS,
BlackBerry Tablet OS, and flavors of the open source operating system Linux.
Below are the steps to be followed for any C program to create and get the output. This is common
to all C program and there is no exception whether its a very small C program or very large C
program.
1. Create
2. Compile
3. Execute or Run
4. Get the Output
Prerequisite:
If you want to create, compile and execute C programs by your own, you have to install C
compiler in your machine. Then, you can start to execute your own C programs in your
machine.
You can refer below link for how to install C compiler and compile and execute C programs
in your machine.
Once C compiler is installed in your machine, you can create, compile and execute C
programs as shown in below link.
If you don’t want to install C/C++ compilers in your machine, you can refer online
compilers which will compile and execute C/C++ and many other programming languages
online and display outputs on the screen.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Basic structure of a C program:
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
1 /*
2 Documentation section
4 Author: fresh2refresh.com
5 Date : 01/01/2012
6 */
12 {
16 return 0;
17 }
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
18
20 {
22 }
Sections Description
We can give comments about the program, creation or modified date, author name
etc in this section. The characters or words or anything which are given between
Documentation
“/*” and “*/”, won’t be considered by C compiler for compilation process.These will
section
be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
Link Section Header files that are required to execute a C program are included in this section
Definition Section In this section, variables are defined and values are set to these variables.
Global declaration Global variables are defined in this section. When a variable is to be used throughout
section the program, can be defined in this section.
Function prototype Function prototype gives many information about a function like return type,
declaration section parameter names used inside the function.
Every C program is started from main function and this function contains two major
Main function
sections called declaration section and executable section.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
User defined User can define their own functions in this section which perform particular task as
function section per the user requirement.
File > New (as shown in above picture) and then write your C program
#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}
Step 3: Save the program using F2 (OR file > Save), remember the extension should be “.c”. In the
below screenshot I have given the name as helloworld.c.
Step 4: Compile the program using Alt + F9 OR Compile > Compile (as shown in the below
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
screenshot).
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C program.
Step 6: Alt+F5 to view the output of the program at the output screen.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Creating and Running Program in Unix or Linux Environment
$ vi helloworld.c
#include<stdio.h>
main()
{
printf("Hello World!");
Compile the helloworld.c using cc command as shown below. This will create the a.out file.
$ cc helloworld.c
$ ls -l
-rw-r--r-- 1 ramesh ramesh 71 2009-08-28 14:06 helloworld.c
-rwxr-xr-x 1 ramesh ramesh 9152 2009-08-28 14:07 a.out
You can either execute the a.out to see the output (or) rename it to some other meaningful name and
execute it as shown below.
$ ./a.out
Hello World!
Number System and base conversions
There are many methods or techniques which can be used to convert numbers from one base to
another.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Binary Numeral System - Base-2
Examples:
Examples:
308 = 3×81+0×80 = 24
Example:
253810 = 2×103+5×102+3×101+8×100
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Examples:
1 1 1 1
2 10 2 2
3 11 3 3
4 100 4 4
5 101 5 5
6 110 6 6
7 111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
15 1111 17 F
16 10000 20 10
17 10001 21 11
18 10010 22 12
19 10011 23 13
20 10100 24 14
21 10101 25 15
22 10110 26 16
23 10111 27 17
24 11000 30 18
25 11001 31 19
26 11010 32 1A
27 11011 33 1B
28 11100 34 1C
29 11101 35 1D
30 11110 36 1E
31 11111 37 1F
32 100000 40 20
1. Decimal to Binary
(10.25)10
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
(10.25)10
Note: Keep multiplying the fractional part with 2 until decimal part 0.00 is obtained.
(0.25)10 = (0.01)2
2. Binary to Decimal
(1010.01)2
(1010.01)2 = (10.25)10
3. Decimal to Octal
(10.25)10
(10)10 = (12)8
Fractional part:
0.25 x 8 = 2.00
Note: Keep multiplying the fractional part with 8 until decimal part .00 is obtained.
(.25)10 = (.2)8
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
4. Octal to Decimal
(12.2)8
1 x 81 + 2 x 80 +2 x 8-1 = 8+2+0.25 = 10.25
(12.2)8 = (10.25)10
(3A)16 = (00111010)2
To convert from Binary to Hexadecimal, group the bits in groups of 4 and write the hex for the 4-bit
binary. Add 0's to adjust the groups.
1111011011
(001111011011 )2 = (3DB)16
ALGORITHM
An algorithm is a step by step method written in simple language for solving a problem. It is
commonly used for data processing, calculation and other related computer and mathematical
operations.
An algorithm is a detailed series of instructions for carrying out an operation or solving a problem.
In a non-technical approach, we use algorithms in everyday tasks, such as a recipe to bake a cake or
a do-it-yourself handbook.
Technically, computers use algorithms to list the detailed instructions for carrying out an operation.
For example, to compute an employee’s paycheck, the computer uses an algorithm. To accomplish
this task, appropriate data must be entered into the system. In terms of efficiency, various
algorithms are able to accomplish operations or problem solving easily and quickly.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Step 6: Stop
Write an algorithm to find the largest among three different numbers entered by user.
Step 1:
Start
Step 2:
Declare variables a,b and c.
Step 3:
Read variables a,b and c.
Step 4:
If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0.
Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D←b2-4ac
Step 4: If D≥0
r1←(-b+√D)/2a
r2←(-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp←b/2a
ip←√(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop
FLOWCHART
A graphical representation of a computer program in relation to its sequence of functions (as distinct from
the data it processes).
A flowchart is a type of diagram that represents an algorithm, workflow or process. The flowchart shows
the steps as boxes of various kinds, and their order by connecting the boxes with arrows. This diagrammatic
representation illustrates a solution model to a given problem. Flowcharts are used in analyzing, designing,
documenting or managing a process or program in various fields.
Flowchart
Name Description
Symbol
Also known as an “Action Symbol,” this shape represents a
Process symbol process, action, or function. It’s the most widely-used symbol in
flowcharting.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Flowchart
Name Description
Symbol
Also known as the “Terminator Symbol,” this symbol represents
Start/End symbol the start points, end points, and potential outcomes of a path.
Often contains “Start” or “End” within the shape.
Represents the input or output of a document, specifically.
Examples of and input are receiving a report, email, or order.
Document symbol
Examples of an output using a document symbol include
generating a presentation, memo, or letter.
Indicates a question to be answered — usually yes/no or
Decision symbol true/false. The flowchart path may then split off into different
branches depending on the answer or consequences thereafter.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Draw a flowchart to add two numbers entered by user.
Draw flowchart to find the largest among three different numbers entered by user.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0
Introduction to C Language
C is a general-purpose programming language used for wide range of applications from Operating
systems like Windows and iOS to software that is used for creating 3D movies.
C programming is highly efficient. That’s the main reason why it’s very popular .
Standard C programs are portable. The source code written in one system works in another
operating system without any change.
As mentioned, it’s a good language to start learning programming. If you know C programming,
you will not just understand how your program works, but will also be able to create a mental
picture on how a computer works.
History of C Language
The origin of C is closely tied to the development of the Unix operating system, originally
implemented in assembly language on a PDP-7 by Dennis Ritchie and Ken Thompson,
incorporating several ideas from colleagues. Eventually, they decided to port the operating system
to a PDP-11. The original PDP-11 version of UNIX was developed in assembly language. The
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
developers were considering rewriting the system using the B language, Thompson's simplified
version of BCPL. However B's inability to take advantage of some of the PDP-11's features,
notably byte addressability, led to C. The name of C was chosen simply as the next after B.
The development of C started in 1972 on the PDP-11 Unix system and first appeared in Version 2
Unix. The language was not initially designed with portability in mind, but soon ran on different
platforms as well: a compiler for the Honeywell 6000 was written within the first year of C's
history, while an IBM System/370 port followed soon.
Also in 1972, a large part of Unix was rewritten in C.By 1973, with the addition of struct types, the
C language had become powerful enough that most of the Unix kernel was now in C.
In 1978, Brian Kernighan and Dennis Ritchie published the first edition of The C Programming
Language. This book, known to C programmers as "K&R", served for many years as an informal
specification of the language. The version of C that it describes is commonly referred to as K&R C.
The second edition of the book[16] covers the later ANSI C standard, described below.
Compound assignment operators of the form =op (such as =-) were changed to the form op= (that
is, -=) to remove the semantic ambiguity created by constructs such as i=-10, which had been
interpreted as i =- 10 (decrement i by 10) instead of the possibly intended i = -10 (let i be -10).
Features of C language
It is a robust language with rich set of built-in functions and operators that can be used to
write any complex program.
The C compiler combines the capabilities of an assembly language with features of a high-level
language.
Programs Written in C are efficient and fast. This is due to its variety of data type and powerful
operators.
It is many time faster than BASIC.
C is highly portable this means that programs once written can be run on another machines with
little or no modification.
Another important feature of C program, is its ability to extend itself.
A C program is basically a collection of functions that are supported by C library. We can also create
our own function and add it to C library.
C language is the most widely used language in operating systems and embedded system
development today.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Identifiers
Identifiers are the names you can give to entities such as variables, functions, structures etc.
Identifier names must be unique. They are created to give unique name to a C entity to identify it
during the execution of a program. For example:
1. int money;
2. double accountBalance;
Here,
money
and
accountBalance
are identifiers.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Also remember, identifier names must be different from keywords. You cannot use
int
as an identifier because
int
is a keyword.
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscore only.
2. The first letter of an identifier should be either a letter or an underscore. However, it is
discouraged to start an identifier name with an underscore. It is because identifier that starts
with an underscore can conflict with system names.
In such cases, compiler will complain about it. Some system names that start with
underscore are _fileno, _iob, _wfopen etc.
3. There is no rule on the length of an identifier. However, the first 31 characters of identifiers
are discriminated by the compiler. So, the first 31 letters of two identifiers in a program
should be different.
You can choose any name for an identifier. However, if the programmer choose meaningful name
for an identifier, it will be easy to understand and work on.
An Indetifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ). The first
character of an identifier can only contain alphabet( a-z , A-Z ) or underscore ( _ ). Identifiers are
also case sensitive in C. For example name and Name are two different identifier in C.
DATA TYPES in C
Data types specify how we enter data into our programs and what type of data we enter. C language
has some predefined set of data types to handle various kinds of data that we can use in our
program. These datatypes have different storage capacities.
Derived data types are nothing but primary datatypes but a little twisted or grouped together
like array, stucture, union and pointer. These are discussed in details later.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be declared
as what data-type it is.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Integer type
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Floating point type
Character type
void type
void type means no value. This is usually used to specify the type of functions which returns
nothing. We will get acquainted to this datatype as we start learning more advanced topics in C
language, like functions, pointers etc.
OPERATORS IN C
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler
to perform a certain mathematical or logical manipulation. Operators are used in programs to
manipulate data and variables.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
C operators can be classified into following types:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description
% remainder of division
Relational operators
Operator Description
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
> Check if operand on the left is greater than operand on the right
Logical operators
|| Logical OR (a || b) is true
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting
of bits from right to left. Bitwise operators are not applied to float or double(These are datatypes,
we will learn about them in the next tutorial).
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Now lets see truth table for bitwise &, | and ^
aba&ba|ba^b
000 0 0
010 1 1
100 1 1
111 1 0
The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and
the right operand specifies the number of positions that the bits in the value have to be shifted. Both
operands have the same precedence.
Example :
a = 0001000
b = 2
a << b = 0100000
a >> b = 0000010
Assignment Operators
= assigns values from right side operands to left side operand a=b
a+=b is same as
+= adds right operand to the left operand and assign the result to left
a=a+b
subtracts right operand from the left operand and assign the result to left
-= a-=b is same as a=a-b
operand
mutiply left operand with the right operand and assign the result to left a*=b is same as
*=
operand a=a*b
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
operand
a%=b is same as
%= calculate modulus using two operands and assign the result to left operand
a=a%b
Conditional operator
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
Explanation:
Special operator
Operator Description Example
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Variables
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location. For example:
Here, playerScore is a variable of integer type. Here, the variable is assigned an integer value 95.
char ch = 'a';
// some code
ch = 'l';
1. A variable name can have letters (both uppercase and lowercase letters), digits and underscore
only.
2. The first letter of a variable should be either a letter or an underscore.
3. There is no rule on how long a variable name (identifier) can be. However, you may run into
problems in some compilers if variable name is longer than 31 characters.
Note: You should always try to give meaningful names to variables. For example: firstName is a
better variable name than fn.
C is a strongly typed language. This means, variable type cannot be changed once it is declared. For
example:
Here, the type of number variable is int. You cannot assign floating-point (decimal) value 5.5 to this
variable. Also, you cannot redefine the type of the variable to double. By the way, to store decimal
values in C, you need to declare its type to either double or float.
Constants/Literals
A constant is a value (or an identifier) whose value cannot be altered in a program. For example: 1,
2.5, 'c' etc.
Here, 1, 2.5 and 'c'are literal constants. Why? You cannot assign different values to these terms.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
You can also create non-modifiable variables in C programming. For example:
Here, PI is a symbolic constant. It's actually a variable however, it's value cannot be changed.
1. Integers
An integer is a numeric constant (associated with number) without any fractional or exponential
part. There are three types of integer constants in C programming:
For example:
2. Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or an exponent
form. For example:
-2.0
0.0000234
-0.22E-5
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
3. Character constants
A character constant is created by enclosing a single character inside single quotation marks. For
example: 'a', 'm', 'F', '2', '}' etc;
4. Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C
programming. For example: newline(enter), tab, question mark etc. In order to use these characters,
escape sequence is used.
For example: \n is used for newline. The backslash \ causes escape from the normal way the
characters are handled by the compiler.
Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
5. String Literals
6. Enumerations
Here, color is a variable and yellow, green, black and white are the enumeration constants having
value 0, 1, 2 and 3 respectively.
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.
All these built-in functions are present in C header files, we will also specify the name of header
files in which a particular function is defined while discussing about it.
The standard input-output header file, named stdio.h contains the definition of the functions
printf() and scanf(), which are used to display output on screen and to take input from user
respectively.
#include<stdio.h>
void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect and in
printf() it is used to give a heads up to the compiler, what type of output to expect.
We can also limit the number of digits or characters that can be input or output, by adding a
number with the format string specifier, like "%1d" or "%3s", the first one means a single numeric
digit and the second one means 3 characters, hence if you try to input 42, while scanf() has "%1d",
it will take only 4 as input. Same is the case for output.
In C Language, computer monitor, printer etc output devices are treated as files and the same
process is followed to write output to these devices as would have been followed to write the output
to a file.
NOTE : printf() function returns the number of characters printed by it, and scanf() returns the
number of characters read by it.
int i = printf("studytonight");
In this program printf("studytonight"); will return 12 as result, which will be stored in the
variable i, because studytonight has 12 characters.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you want to
read more than one character. The putchar() function displays the character passed to it on the
screen and returns the same character. This function too displays only a single character at a time.
In case you want to display more than one characters, use putchar() method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.
The gets() function reads a line from stdin(standard input) into the buffer pointed to by str
pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function writes
the string str and a trailing newline to stdout.
str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not
able to understand this now.)
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
When you will compile the above code, it will ask you to enter a string. When you will enter the
string, it will display the value you have entered.
The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space as character too.
If you enter name as Study Tonight using scanf() it will only read and store Study and will leave
the part after space. But gets() function will read it completely.
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d",&testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output
Enter an integer: 4
Number = 4
Output
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Enter a number: 23.45
Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.
Output
Enter a character: g
You entered g.
When a character is entered in the above program, the character itself is not stored. Instead, a
numeric value(ASCII value) is stored.
And when we displayed that value using "%c" text format, the entered character is displayed.
Output
Enter a character: g
You entered g.
ASCII value of g is 103.
The ASCII value of character 'g' is 103. When, 'g' is entered, 103 is stored in
variable var1 instead of g.
You can display a character if you know ASCII code of that character. This is shown by following
example.
Output
// Tries to print number right justified to 3 digits but the number is not
right adjusted because there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
// Rounds to 0 digit places
printf("Floating point number rounded to 0 digits: %.f\n",987.6543);
Output
C Programming Expression :
C Programming code gets compiled firstly before execution. In the different phases of compiler, c
programming expression is checked for its validity.
Expressions Validity
In order to solve any expression we should have knowledge of C Programming Operators and their
priorities.
Types of Expression :
In Programming, different verities of expressions are given to the compiler. Expressions can be
classified on the basis of Position of Operators in an expression –
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Type Explanation Example
Examples of Expression :
Algebraic Expression C Expression
a x b – c a * b – c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a * b / c
(x / y) + c x / y + c
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression
is evaluated first and then replaces the previous value of the variable on the left hand side.
All variables used in the expression must be assigned values before evaluation is
attempted.
Example of evaluation statements are
x = a * b – c
y = b / c * a
z = a – b / c + d;
The following program illustrates the effect of presence of parenthesis in expressions.
main ()
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf ("x = %f",x);
printf ("y = %f",y);
printf ("z = %f",z);
}
output
x = 10.00
y = 7.00
z = 4.00
Operator Precedence in C
Operator precedence determines which operator is evaluated first when an expression has more
than one operators. For example 100-2*30 would yield 40, because it is evaluated as 100 – (2*30)
and not (100-2)*30. The reason is that multiplication * has higher precedence than subtraction(-).
Associativity in C
Associativity is used when there are two or more operators of same precedence is present in an
expression. For example multiplication and division arithmetic operators have same precedence,
lets say we have an expression 5*2/10, this expression would be evaluated as (5*2)/10 because the
associativity is left to right for these operators. Similarly 20/2*5 would be calculated as (20*2)/5.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Type cast (data type) Right to Left
Arithmetic Operators
Multiplication operator, Divide by, Modulus *, /, % Left to Right
Relational Operators
Less Than < Left to Right
Logical Operators
AND && Left to Right
OR || Left to Right
Bitwise Operators
AND & Left to Right
Assignment Operators
= Right to Left
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
*= Right to Left
/= Right to Left
%= Right to Left
+= Right to Left
-= Right to Left
^= Right to Left
|= Right to Left
Other Operators
Comma , Right to Left
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
Expression evaluation
Priority
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Example 1:
Example 2:
Type Conversion
In computer science, type conversion or typecasting refers to changing an entity of one datatype
into another. There are two types of conversion: implicit and explicit. The term for implicit type
conversion is coercion. Explicit type conversion in some specific way is known as casting.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
Output:
x = 107, z = 108.000000
2. Explicit Type Conversion– This process is also called type casting and it is user defined.
Here the user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double x = 1.2;
return 0;
}
Output:
sum = 2
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, i.e., 0011 1101
operand.
Example
#include <stdio.h>
main() {
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 );
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
UNIT II
Logical operators in C:
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical
NOT (!).
Operators Example/Description
(x>5)&&(y<5)
&& (logical AND)
It returns true when both conditions are true
(x>=10)||(y>=10)
|| (logical OR)
It returns true when at-least one of the condition is true
!((x>5)&&(y<5))
! (logical NOT) It reverses the state of the operand “((x>5) && (y<5))”
1 #include <stdio.h>
3 int main()
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
4 {
5 int m=40,n=20;
6 int o=20,p=30;
8 {
10 }
11 if (o>p || p!=20)
12 {
14 }
16 {
18 }
19 else
20 {
23 }
24 }
Output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
&& operator – “if clause” becomes true only when both conditions (m>n and m! =0) is true. Else, it
becomes false.
|| Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by “!” operator.
So, “! (m>n and m! =0)” returns false (0).
The following table shows the 6 relational operators and their meaning, by example:
Operator Meaning
C if statement
if (testExpression)
{
// statement(s)
}
If the test expression is evaluated to true (nonzero), statement(s) inside the body of if is executed.
If the test expression is evaluated to false (0), statement(s) inside the body of if is skipped from
execution.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
To learn more on when test expression is evaluated to nonzero (true) and 0 (false), check relational
and logical operators.
Example 1: if statement
// Program to display a number if user enters negative number
#include <stdio.h>
int main()
{
int number;
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When user enters -2, the test expression (number < 0) is evaluated to true. Hence, You
entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement is easy.
When user enters 5, the test expression (number < 0) is evaluated to false and the statement inside
the body of if is skipped.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
C if...else statement
The if statement may have an optional else block. The syntax of if..else statement is:
if (testExpression) {
// statement(s) inside the body of if
}
else {
// statement(s) inside the body of else
}
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed and
the statement inside the body of if is skipped.
The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check for multiple test expressions and execute different
statement(s).
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
Nested if...else
It is possible to include if...else statement(s) inside the body of another if...else statement.
This program below relates two integers using either <, > and = similar like in if...else ladder
example. However, we will use nested if...else statement to solve this problem.
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
If the body of if...else statement has only one statement, you do not need to use parenthesis { }.
This code
if (a > b) {
print("Hello");
}
print("Hi");
is equivalent to
if (a > b)
print("Hello");
print("Hi");
return 0;
}
Output
Enter an integer: -7
-7 is odd.
Switch statement in C
When you want to solve multiple option type problems, for example: Menu like program, where
one value is associated with each option and you need to choose only one at a time, then, switch
statement is used.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then
compared to the values present in different cases. It executes that block of code which matches the
case value. If there is no match, then default block is executed(if present). The general form of
switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
1. The expression (after switch keyword) must yield an integer value i.e the expression should be an
integer or a variable or an expression that evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.
Points to Remember
1. We don't use those expressions to evaluate switch case, which may return floating point values or
strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after the
matching block.
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
11. printf("C");
12. break;
}
ABC
The output was supposed to be only A because only the first case matches, but as there is no
break statement after that block, the next blocks are executed too, until it a break statement
in encountered or the execution reaches the end of the switch block.
13. default case is executed when none of the mentioned case matches the switch expression. The
default case can be placed anywhere in the switch case. Even if we don't include the default case,
switch statement works.
14. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch block. However, nested switch statements should be avoided as it makes the
program more complex and less readable.
Switch case statements are a substitute for long if statements that compare a variable to several
integral values
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
The expression provided in the switch should result in a constant value otherwise it would not be
valid.
Valid expressions for switch:
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions for switch:
// Variable expression not allowed
switch(ab+cd)
switch(a+b+c)
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Duplicate case values are not allowed.
The default statement is optional.Even if the switch case statement do not have a default statement,
it would run without any problem.
The break statement is used inside the switch to terminate a statement sequence. When a break
statement is reached, the switch terminates, and the flow of control jumps to the next line following
the switch statement.
The break statement is optional. If omitted, execution will continue on into the next case. The flow
of control will fall through to subsequent cases until a break is reached.
Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.
Flowchart
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
// Following is a simple program to demonstrate
// syntax of switch.
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Standard Functions
C Standard library functions or simply C Library functions are inbuilt functions in C programming.
The prototype and data definitions of the functions are present in their respective header files, and
must be included in your program to access them.
For example: If you want to use printf() function, the header file <stdio.h> should be included.
#include <stdio.h>
int main()
{
// If you use printf() function without including the <stdio.h>
// header file, this program will show an error.
printf("Catch me if you can.");
}
There is at least one function in any C program, i.e., the main() function (which is also a library
function). This function is automatically called when your program starts.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
abort stdlib.h void abort(void); Stops a program abnormally.
abs stdlib.h int abs(int n); Calculates the absolute value of
an integer argument n.
acos math.h double acos(double x); Calculates the arc cosine of x.
asctime time.h char *asctime(const struct Converts the time that is stored as
tm *time); a structure to a character string.
asctime_r time.h char *asctime_r (const Converts tm that is stored as a
struct tm *tm, char *buf); structure to a character string.
(Restartable version of asctime.)
asin math.h double asin(double x); Calculates the arc sine of x.
assert assert.h void assert(int expression); Prints a diagnostic message and
ends the program if the expression
is false.
atan math.h double atan(double x); Calculates the arc tangent of x.
atan2 math.h double atan2(double y, Calculates the arc tangent of y/x.
double x);
atexit stdlib.h int atexit(void Registers a function to be called at
(*func)(void)); normal termination.
atof stdlib.h double atof(const char Converts string to a double-
*string); precision floating-point value.
atoi stdlib.h int atoi(const char *string); Converts string to an integer.
atol stdlib.h long int atol(const char Converts string to a long integer.
*string);
bsearch stdlib.h void *bsearch(const void Performs a binary search on an
*key, const void *base, array of num elements, each of
size_t num, size_t size, int size bytes. The array must be
(*compare) (const void sorted in ascending order by the
*element1, const void function pointed to by compare.
*element2));
btowc stdio.h wint_t btowc(int c); Determines whether c constitues a
wchar.h valid multibyte character in the
initial shift state.
calloc stdlib.h void *calloc(size_t num, Reserves storage space for an
size_t size); array of num elements, each of
size size, and initializes the values
of all elements to 0.
catclose6 nl_types.h int catclose (nl_catd catd); Closes a previously opened
message catalog.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
6
catgets nl_types.h char *catgets(nl_catd catd, Retrieves a message from an open
int set_id, int msg_id, const message catalog.
char *s);
catopen6 nl_types.h nl_catd catopen (const char Opens a message catalog, which
*name, int oflag); must be done before a message
can be retrieved.
ceil math.h double ceil(double x); Calculates the double value
representing the smallest integer
that is greater than or equal to x.
clearerr stdio.h void clearerr(FILE Resets the error indicators and the
*stream); end-of-file indicator for stream.
clock time.h clock_t clock(void); Returns the processor time that
has elapsed since the job was
started.
cos math.h double cos(double x); Calculates the cosine of x.
cosh math.h double cosh(double x); Calculates the hyperbolic cosine
of x.
ctime time.h char *ctime(const time_t Converts time to a character
*time); string.
ctime64 time.h char *ctime64(const Converts time to a character
time64_t *time); string.
ctime_r time.h char *ctime_r(const time_t Converts time to a character
*time, char *buf); string. (Restartable version of
ctime.)
ctime64_r time.h char *ctime64_r(const Converts time to a character
time64_t *time, char *buf); string. (Restartable version of
ctime64.)
difftime time.h double difftime(time_t Computes the difference between
time2, time_t time1); time2 and time1.
difftime64 time.h double Computes the difference between
difftime64(time64_t time2, time2 and time1.
time64_t time1);
div stdlib.h div_t div(int numerator, int Calculates the quotient and
denominator); remainder of the division of
numerator by denominator.
erf math.h double erf(double x); Calculates the error function of x.
erfc math.h double erfc(double x); Calculates the error function for
large values of x.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
exit stdlib.h void exit(int status); Ends a program normally.
exp math.h double exp(double x); Calculates the exponential
function of a floating-point
argument x.
fabs math.h double fabs(double x); Calculates the absolute value of a
floating-point argument x.
fclose stdio.h int fclose(FILE *stream); Closes the specified stream.
fdopen5 stdio.h FILE *fdopen(int handle, Associates an input or output
const char *type); stream with the file identified by
handle.
feof stdio.h int feof(FILE *stream); Tests whether the end-of-file flag
is set for a given stream.
ferror stdio.h int ferror(FILE *stream); Tests for an error indicator in
reading from or writing to stream.
fflush1 stdio.h int fflush(FILE *stream); Writes the contents of the buffer
associated with the output stream.
fgetc1 stdio.h int fgetc(FILE *stream); Reads a single unsigned character
from the input stream.
fgetpos1 stdio.h int fgetpos(FILE *stream, Stores the current position of the
fpos_t *pos); file pointer associated with stream
into the object pointed to by pos.
fgets1 stdio.h char *fgets(char *string, Reads a string from the input
int n, FILE *stream); stream.
fgetwc6 stdio.h wint_t fgetwc(FILE Reads the next multibyte character
wchar.h *stream); from the input stream pointed to
by stream.
fgetws6 stdio.h wchar_t *fgetws(wchar_t Reads wide characters from the
wchar.h *wcs, int n, FILE *stream); stream into the array pointed to by
wcs.
fileno5 stdio.h int fileno(FILE *stream); Determines the file handle
currently associated with stream.
floor math.h double floor(double x); Calculates the floating-point value
representing the largest integer
less than or equal to x.
fmod math.h double fmod(double x, Calculates the floating-point
double y); remainder of x/y.
fopen stdio.h FILE *fopen(const char Opens the specified file.
*filename, const char
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
*mode);
fprintf stdio.h int fprintf(FILE *stream, Formats and prints characters and
const char *format-string, values to the output stream.
arg-list);
fputc1 stdio.h int fputc(int c, FILE Prints a character to the output
*stream); stream.
fputs1 stdio.h int fputs(const char *string, Copies a string to the output
FILE *stream); stream.
fputwc6 stdio.h wint_t fputwc(wchar_t wc, Converts the wide character wc to
wchar.h FILE *stream); a multibyte character and writes it
to the output stream pointed to by
stream at the current position.
fputws6 stdio.h int fputws(const wchar_t Converts the wide-character string
wchar.h *wcs, FILE *stream); wcs to a multibyte-character string
and writes it to stream as a
multibyte character string.
fread stdio.h size_t fread(void *buffer, Reads up to count items of size
size_t size, size_t count, length from the input stream, and
FILE *stream); stores them in buffer.
free stdlib.h void free(void *ptr); Frees a block of storage.
freopen stdio.h FILE *freopen(const char Closes stream, and reassigns it to
*filename, const char the file specified.
*mode, FILE *stream);
frexp math.h double frexp(double x, int Separates a floating-point number
*expptr); into its mantissa and exponent.
fscanf stdio.h int fscanf(FILE *stream, Reads data from stream into
const char *format-string, locations given by arg-list.
arg-list);
fseek1 stdio.h int fseek(FILE *stream, Changes the current file position
long int offset, int origin); associated with stream to a new
location.
fsetpos1 stdio.h int fsetpos(FILE *stream, Moves the current file position to
const fpos_t *pos); a new location determined by pos.
ftell1 stdio.h long int ftell(FILE Gets the current position of the
*stream); file pointer.
fwide6 stdio.h int fwide(FILE *stream, int Determines the orientation of the
wchar.h mode); stream pointed to by stream.
fwprintf6 stdio.h int fwprintf(FILE *stream, Writes output to the stream
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
wchar.h const wchar_t *format, pointed to by stream.
arg-list);
fwrite stdio.h size_t fwrite(const void Writes up to count items of size
*buffer, size_t size,size_t length from buffer to stream.
count, FILE *stream);
fwscanf6 stdio.h int fwscanf(FILE *stream, Reads input from the stream
wchar.h const wchar_t *format, pointed to by stream.
arg-list)
gamma math.h double gamma(double x); Computes the Gamma Function
getc1 stdio.h int getc(FILE *stream); Reads a single character from the
input stream.
getchar1 stdio.h int getchar(void); Reads a single character from
stdin.
getenv stdlib.h char *getenv(const char Searches environment variables
*varname); for varname.
gets stdio.h char *gets(char *buffer); Reads a string from stdin, and
stores it in buffer.
getwc6 stdio.h wint_t getwc(FILE Reads the next multibyte character
wchar.h *stream); from stream, converts it to a wide
character and advances the
associated file position indicator
for stream.
getwchar6 wchar.h wint_t getwchar(void); Reads the next multibyte character
from stdin, converts it to a wide
character, and advances the
associated file position indicator
for stdin.
gmtime time.h struct tm *gmtime(const Converts a time value to a
time_t *time); structure of type tm.
gmtime64 time.h struct tm *gmtime64(const Converts a time value to a
time64_t *time); structure of type tm.
gmtime_r time.h struct tm *gmtime_r (const Converts a time value to a
time_t *time, struct tm structure of type tm. (Restartable
*result); version of gmtime.)
gmtime64_r time.h struct tm *gmtime64_r Converts a time value to a
(const time64_t *time, structure of type tm. (Restartable
struct tm *result); version of gmtime64.)
hypot math.h double hypot(double side1, Calculates the hypotenuse of a
double side2); right-angled triangle with sides of
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
length side1 and side2.
isalnum ctype.h int isalnum(int c); Tests if c is alphanumeric.
isalpha ctype.h int isalpha(int c); Tests if c is alphabetic.
isascii ctype.h int isascii(int c); Tests if c is within the 7-bit US-
ASCII range.
iscntrl ctype.h int iscntrl(int c); Tests if c is a control character.
isdigit ctype.h int isdigit(int c); Tests if c is a decimal digit.
isgraph ctype.h int isgraph(int c); Tests if c is a printable character
excluding the space.
islower ctype.h int islower(int c); Tests if c is a lowercase letter.
isprint ctype.h int isprint(int c); Tests if c is a printable character
including the space.
ispunct ctype.h int ispunct(int c); Tests if c is a punctuation
character.
isspace ctype.h int isspace(int c); Tests if c is a whitespace
character.
isupper ctype.h int isupper(int c); Tests if c is an uppercase letter.
4
iswalnum wctype.h int iswalnum (wint_t wc); Checks for any alphanumeric
wide character.
iswalpha4 wctype.h int iswalpha (wint_t wc); Checks for any alphabetic wide
character.
iswcntrl4 wctype.h int iswcntrl (wint_t wc); Tests for any control wide
character.
iswctype4 wctype.h int iswctype(wint_t wc, Determines whether or not the
wctype_t wc_prop); wide character wc has the
property wc_prop.
iswdigit4 wctype.h int iswdigit (wint_t wc); Checks for any decimal-digit wide
character.
iswgraph4 wctype.h int iswgraph (wint_t wc); Checks for any printing wide
character except for the wide-
character space.
iswlower4 wctype.h int iswlower (wint_t wc); Checks for any lowercase wide
character.
iswprint4 wctype.h int iswprint (wint_t wc); Checks for any printing wide
character.
iswpunct4 wctype.h int iswpunct (wint_t wc); Test for a wide non-alphanumeric,
non-space character.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
4
iswspace wctype.h int iswspace (wint_t wc); Checks for any wide character
that corresponds to an
implementation-defined set of
wide characters for which
iswalnum is false.
iswupper4 wctype.h int iswupper (wint_t wc); Checks for any uppercase wide
character.
iswxdigit4 wctype.h int iswxdigit (wint_t wc); Checks for any hexadecimal digit
character.
isxdigit4 wctype.h int isxdigit(int c); Tests if c is a hexadecimal digit.
j0 math.h double j0(double x); Calculates the Bessel function
value of the first kind of order 0.
j1 math.h double j1(double x); Calculates the Bessel function
value of the first kind of order 1.
jn math.h double jn(int n, double x); Calculates the Bessel function
value of the first kind of order n.
labs stdlib.h long int labs(long int n); Calculates the absolute value of n.
ldexp math.h double ldexp(double x, int Returns the value of x multiplied
exp); by (2 to the power of exp).
ldiv stdlib.h ldiv_t ldiv(long int Calculates the quotient and
numerator, long int remainder of
denominator); numerator/denominator.
localeconv locale.h struct lconv Formats numeric quantities in
*localeconv(void); struct lconv according to the
current locale.
localtime time.h struct tm *localtime(const Converts timeval to a structure of
time_t *timeval); type tm.
localtime64 time.h struct tm Converts timeval to a structure of
*localtime64(const type tm.
time64_t *timeval);
localtime_r time.h struct tm *localtime_r Converts a time value to a
(const time_t *timeval, structure of type tm. (Restartable
struct tm *result); version of localtime.)
localtime64_r time.h struct tm *localtime64_r Converts a time value to a
(const time64_t *timeval, structure of type tm. (Restartable
struct tm *result); version of localtime64.)
log math.h double log(double x); Calculates the natural logarithm of
x.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
log10 math.h double log10(double x); Calculates the base 10 logarithm
of x.
longjmp setjmp.h void longjmp(jmp_buf env, Restores a stack environment
int value); previously set in env by the setjmp
function.
malloc stdlib.h void *malloc(size_t size); Reserves a block of storage.
mblen stdlib.h int mblen(const char Determines the length of a
*string, size_t n); multibyte character string.
mbrlen4 wchar.h int mbrlen (const char *s, Determines the length of a
size_t n, mbstate_t *ps); multibyte character. (Restartable
version of mblen.)
mbrtowc4 wchar.h int mbrtowc (wchar_t Convert a multibyte character to a
*pwc, const char *s, size_t wide character (Restartable
n, mbstate_t *ps); version of mbtowc.)
mbsinit4 wchar.h int mbsinit (const Test state object *ps for initial
mbstate_t *ps); state.
mbsrtowcs4 wchar.h size_t mbsrtowc (wchar_t Convert multibyte string to a wide
*dst, const char **src, character string. (Restartable
size_t len, mbstate_t *ps); version of mbstowcs.)
mbstowcs stdlib.h size_t mbstowcs(wchar_t Converts the multibyte characters
*pwc, const char *string, in string to their corresponding
size_t n); wchar_t codes, and stores not
more than n codes in pwc.
mbtowc stdlib.h int mbtowc(wchar_t *pwc, Stores the wchar_t code
const char *string, size_t corresponding to the first n bytes
n); of multibyte character string into
the wchar_t character pwc.
memchr string.h void *memchr(const void Searches the first count bytes of
*buf, int c, size_t count); buf for the first occurrence of c
converted to an unsigned
character.
memcmp string.h int memcmp(const void Compares up to count bytes of
*buf1, const void *buf2, buf1 and buf2.
size_t count);
memcpy string.h void *memcpy(void *dest, Copies count bytes of src to dest.
const void *src, size_t
count);
memmove string.h void *memmove(void Copies count bytes of src to dest.
*dest, const void *src, Allows copying between objects
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
size_t count); that overlap.
memset string.h void *memset(void *dest, Sets count bytes of dest to a value
int c, size_t count); c.
mktime time.h time_t mktime(struct tm Converts local time into calendar
*time); time.
mktime64 time.h time64_t mktime64(struct Converts local time into calendar
tm *time); time.
modf math.h double modf(double x, Breaks down the floating-point
double *intptr); value x into fractional and integral
parts.
nextafter math.h double nextafter(double x, Calculates the next representable
double y); value after x in the direction of y.
nextafterl math.h long double nextafterl(long Calculates the next representable
double x, long double y); value after x in the direction of y.
nexttoward math.h double nexttoward(double Calculates the next representable
x, long double y); value after x in the direction of y.
nexttowardl math.h long double Calculates the next representable
nexttowardl(long double x, value after x in the direction of y.
long double y);
nl_langinfo4 langinfo.h char *nl_langinfo(nl_item Retrieve from the current locale
item); the string that describes the
requested information specified
by item.
perror stdio.h void perror(const char Prints an error message to stderr.
*string);
pow math.h double pow(double x, Calculates the value x to the
double y); power y.
printf stdio.h int printf(const char Formats and prints characters and
*format-string, arg-list); values to stdout.
putc1 stdio.h int putc(int c, FILE Prints c to the output stream.
*stream);
putchar1 stdio.h int putchar(int c); Prints c to stdout.
putenv stdlib.h int *putenv(const char Sets the value of an environment
*varname); variable by altering an existing
variable or creating a new one.
puts stdio.h int puts(const char Prints a string to stdout.
*string);
putwc6 stdio.h wint_t putwchar(wchar_t Converts the wide character wc to
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
wchar.h wc, FILE *stream); a multibyte character, and writes it
to the stream at the current
position.
putwchar6 wchar.h wint_t putwchar(wchar_t Converts the wide character wc to
wc); a multibyte character and writes it
to stdout.
qsort stdlib.h void qsort(void *base, Performs a quick sort of an array
size_t num, size_t width, of num elements, each of width
int(*compare)(const void bytes in size.
*element1, const void
*element2));
raise signal.h int raise(int sig); Sends the signal sig to the running
program.
rand stdlib.h int rand(void); Returns a pseudo-random integer.
rand_r stdlib.h int rand_r(void); Returns a pseudo-random integer.
(Restartable version)
realloc stdlib.h void *realloc(void *ptr, Changes the size of a previously
size_t size); reserved storage block.
regcomp regex.h int regcomp(regex_t *preg, Compiles the source regular
const char *pattern, int expression pointed to by pattern
cflags); into an executable version and
stores it in the location pointed to
by preg.
regerror regex.h size_t regerror(int errcode, Finds the description for the error
const regex_t *preg, char code errcode for the regular
*errbuf, size_t expression preg.
errbuf_size);
regexec regex.h int regexec(const regex_t Compares the null-ended string
*preg, const char *string, string against the compiled
size_t nmatch, regmatch_t regular expression preg to find a
*pmatch, int eflags); match between the two.
regfree regex.h void regfree(regex_t Frees any memory that was
*preg); allocated by regcomp to
implement the regular expression
preg.
remove stdio.h int remove(const char Deletes the file specified by
*filename); filename.
rename stdio.h int rename(const char Renames the specified file.
*oldname, const char
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
*newname);
rewind1 stdio.h void rewind(FILE Repositions the file pointer
*stream); associated with stream to the
beginning of the file.
scanf stdio.h int scanf(const char Reads data from stdin into
*format-string, arg-list); locations given by arg-list.
setbuf stdio.h void setbuf(FILE *stream, Controls buffering for stream.
char *buffer);
setjmp setjmp.h int setjmp(jmp_buf env); Saves a stack environment that
can be subsequently restored by
longjmp.
setlocale locale.h char *setlocale(int Changes or queries variables
category, const char defined in the locale.
*locale);
setvbuf stdio.h int setvbuf(FILE *stream, Controls buffering and buffer size
char *buf, int type, size_t for stream.
size);
signal signal.h void(*signal (int sig, Registers func as a signal handler
void(*func)(int))) (int); for the signal sig.
sin math.h double sin(double x); Calculates the sine of x.
sinh math.h double sinh(double x); Calculates the hyperbolic sine of
x.
snprintf stdio.h int snprintf(char *outbuf, Same as sprintf except that the
size_t n, const char*, ...) function will stop after n
characters have been written to
outbuf.
sprintf stdio.h int sprintf(char *buffer, Formats and stores characters and
const char *format-string, values in buffer.
arg-list);
sqrt math.h double sqrt(double x); Calculates the square root of x.
srand stdlib.h void srand(unsigned int Sets the seed for the pseudo-
seed); random number generator.
sscanf stdio.h int sscanf(const char Reads data from buffer into the
*buffer, const char locations given by arg-list.
*format, arg-list);
strcasecmp strings.h int srtcasecmp(const char Compares strings without case
*string1, const char sensitivity.
*string2);
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
strcat string.h char *strcat(char *string1, Concatenates string2 to string1.
const char *string2);
strchr string.h char *strchr(const char Locates the first occurrence of c in
*string, int c); string.
strcmp string.h int strcmp(const char Compares the value of string1 to
*string1, const char string2.
*string2);
strcoll string.h int strcoll(const char Compares two strings using the
*string1, const char collating sequence in the current
*string2); locale.
strcpy string.h char *strcpy(char *string1, Copies string2 into string1.
const char *string2);
strcspn string.h size_t strcspn(const char Returns the length of the initial
*string1, const char substring of string1 consisting of
*string2); characters not contained in
string2.
strerror string.h char *strerror(int errnum); Maps the error number in errnum
to an error message string.
strfmon4 wchar.h int strfmon (char *s, size_t Converts monetary value to string.
maxsize, const char
*format, ...);
strftime time.h size_t strftime (char *dest, Stores characters in an array
size_t maxsize, const char pointed to by dest, according to
*format, const struct tm the string determined by format.
*timeptr);
strlen string.h size_t strlen(const char Calculates the length of string.
*string);
strncasecmp strings.h int strncasecmp(const char Compares strings without case
*string1, const char sensitivity.
*string2, size_t count);
strncat string.h char *strncat(char *string1, Concatenates up to count
const char *string2, size_t characters of string2 to string1.
count);
strncmp string.h int strncmp(const char Compares up to count characters
*string1, const char of string1 and string2.
*string2, size_t count);
strncpy string.h char *strncpy(char Copies up to count characters of
*string1, const char string2 to string1.
*string2, size_t count);
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
strpbrk string.h char *strpbrk(const char Locates the first occurrence in
*string1, const char string1 of any character in string2.
*string2);
strptime4 time.h char *strptime (const char Date and time conversion
*buf, const char *format,
struct tm *tm);
strrchr string.h char *strrchr(const char Locates the last occurrence of c in
*string, int c); string.
strspn string.h size_t strspn(const char Returns the length of the initial
*string1, const char substring of string1 consisting of
*string2); characters contained in string2.
strstr string.h char *strstr(const char Returns a pointer to the first
*string1, const char occurrence of string2 in string1.
*string2);
strtod stdlib.h double strtod(const char Converts nptr to a double
*nptr, char **endptr); precision value.
strtod32 stdlib.h _Decimal32 strtod32(const Converts nptr to a single-precision
char *nptr, char **endptr); decimal floating-point value.
strtod64 stdlib.h _Decimal64 strtod64(const Converts nptr to a double-
char *nptr, char **endptr); precision decimal floating-point
value.
strtod128 stdlib.h _Decimal128 Converts nptr to a quad-precision
strtod128(const char *nptr, decimal floating-point value.
char **endptr);
strtof stdlib.h float strtof(const char Converts nptr to a float value.
*nptr, char **endptr);
strtok string.h char *strtok(char *string1, Locates the next token in string1
const char *string2); delimited by the next character in
string2.
strtok_r string.h char *strtok_r(char *string, Locates the next token in string
const char *seps, char delimited by the next character in
**lasts); seps. (Restartable version of
strtok.)
strtol stdlib.h long int strtol(const char Converts nptr to a signed long
*nptr, char **endptr, int integer.
base);
strtold stdlib.h long double strtold(const Converts nptr to a long double
char *nptr, char **endptr); value.
strtoul stdlib.h unsigned long int Converts string1 to an unsigned
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
strtoul(const char *string1, long integer.
char **string2, int base);
strxfrm string.h size_t strxfrm(char Converts string2 and places the
*string1, const char result in string1. The conversion
*string2, size_t count); is determined by the program's
current locale.
swprintf wchar.h int swprintf(wchar_t Formats and stores a series of
*wcsbuffer, size_t n, const wide characters and values into
wchar_t *format, arg-list); the wide-character buffer
wcsbuffer.
swscanf wchar.h int swscanf (const wchar_t Reads data from buffer into the
*buffer, const wchar_t locations given by arg-list.
*format, arg-list)
system stdlib.h int system(const char Passes string to the system
*string); command analyzer.
tan math.h double tan(double x); Calculates the tangent of x.
tanh math.h double tanh(double x); Calculates the hyperbolic tangent
of x.
time time.h time_t time(time_t Returns the current calendar time.
*timeptr);
time64 time.h time64_t time64(time64_t Returns the current calendar time.
*timeptr);
tmpfile stdio.h FILE *tmpfile(void); Creates a temporary binary file
and opens it.
tmpnam stdio.h char *tmpnam(char Generates a temporary file name.
*string);
toascii ctype.h int toascii(int c); Converts c to a character in the 7-
bit US-ASCII character set.
tolower ctype.h int tolower(int c); Converts c to lowercase.
toupper ctype.h int toupper(int c); Converts c to uppercase.
towctrans wctype.h wint_t towctrans(wint_t Translates the wide character wc
wc, wctrans_t desc); based on the mapping described
by desc.
towlower4 wctype.h wint_t towlower (wint_t Converts uppercase letter to
wc); lowercase letter.
towupper4 wctype.h wint_t towupper (wint_t Converts lowercase letter to
wc); uppercase letter.
ungetc1 stdio.h int ungetc(int c, FILE Pushes c back onto the input
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
*stream); stream.
ungetwc6 stdio.h wint_t ungetwc(wint_t wc, Pushes the wide character wc back
wchar.h FILE *stream); onto the input stream.
va_arg stdarg.h var_type va_arg(va_list Returns the value of one argument
arg_ptr, var_type); and modifies arg_ptr to point to
the next argument.
va_end stdarg.h void va_end(va_list Facilitates normal return from
arg_ptr); variable argument list processing.
va_start stdarg.h void va_start(va_list Initializes arg_ptr for subsequent
arg_ptr, variable_name); use by va_arg and va_end.
vfprintf stdio.h int vfprintf(FILE *stream, Formats and prints characters to
stdarg.h const char *format, va_list the output stream using a variable
arg_ptr); number of arguments.
vfscanf stdio.h int vfscanf(FILE *stream, Reads data from a specified
stdarg.h const char *format, va_list stream into locations given by a
arg_ptr); variable number of arguments.
vfwprintf6 stdarg.h int vfwprintf(FILE Equivalent to fwprintf, except that
stdio.h *stream, const wchar_t the variable argument list is
wchar.h *format, va_list arg); replaced by arg.
vfwscanf stdio.h int vfwscanf(FILE Reads wide data from a specified
stdarg.h *stream, const wchar_t stream into locations given by a
*format, va_list arg_ptr); variable number of arguments.
vprintf stdio.h int vprintf(const char Formats and prints characters to
stdarg.h *format, va_list arg_ptr); stdout using a variable number of
arguments.
vscanf stdio.h int vscanf(const char Reads data from stdin into
stdarg.h *format, va_list arg_ptr); locations given by a variable
number of arguments.
vsprintf stdio.h int vsprintf(char *target- Formats and stores characters in a
stdarg.h string, const char *format, buffer using a variable number of
va_list arg_ptr); arguments.
vsnprintf stdio.h int vsnprintf(char *outbuf, Same as vsprintf except that the
size_t n, const char*, function will stop after n
va_list); characters have been written to
outbuf.
vsscanf stdio.h int vsscanf(const Reads data from a buffer into
stdarg.h char*buffer, const char locations given by a variable
*format, va_list arg_ptr); number of arguments.
vswprintf stdarg.h int vswprintf(wchar_t Formats and stores a series of
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
wchar.h *wcsbuffer, size_t n, const wide characters and values in the
wchar_t *format, va_list buffer wcsbuffer.
arg);
vswscanf stdio.h int vswscanf(const wchar_t Reads wide data from a buffer
wchar.h *buffer, const wchar_t into locations given by a variable
*format, va_list arg_ptr); number of arguments.
vwprintf6 stdarg.h int vwprintf(const wchar_t Equivalent to wprintf, except that
wchar.h *format, va_list arg); the variable argument list is
replaced by arg.
vwscanf stdio.h int vwscanf(const wchar_t Reads wide data from stdin into
wchar.h *format, va_list arg_ptr); locations given by a variable
number of arguments.
wcrtomb4 wchar.h int wcrtomb (char *s, Converts a wide character to a
wchar_t wchar, mbstate_t multibyte character. (Restartable
*pss); version of wctomb.)
wcscat wchar.h wchar_t *wcscat(wchar_t Appends a copy of the string
*string1, const wchar_t pointed to by string2 to the end of
*string2); the string pointed to by string1.
wcschr wchar.h wchar_t *wcschr(const Searches the wide-character string
wchar_t *string, wchar_t pointed to by string for the
character); occurrence of character.
wcscmp wchar.h int wcscmp(const wchar_t Compares two wide-character
*string1, const wchar_t strings, *string1 and *string2.
*string2);
wcscoll4 wchar.h int wcscoll (const wchar_t Compares two wide-character
*wcs1, const wchar_t strings using the collating
*wcs2); sequence in the current locale.
wcscpy wchar.h wchar_t *wcscpy(wchar_t Copies the contents of *string2
*string1, const wchar_t (including the ending wchar_t null
*string2); character) into *string1.
wcscspn wchar.h size_t wcscspn(const Determines the number of
wchar_t *string1, const wchar_t characters in the initial
wchar_t *string2); segment of the string pointed to
by *string1 that do not appear in
the string pointed to by *string2.
wcsftime wchar.h size_t wcsftime(wchar_t Converts the time and date
*wdest, size_t maxsize, specification in the timeptr
const wchar_t *format, structure into a wide-character
const struct tm *timeptr); string.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
wcslen wchar.h size_t wcslen(const Computes the number of wide-
wchar_t *string); characters in the string pointed to
by string.
wcslocaleconv locale.h struct wcslconv Formats numeric quantities in
*wcslocaleconv(void); struct wcslconv according to the
current locale.
wcsncat wchar.h wchar_t *wcsncat(wchar_t Appends up to count wide
*string1, const wchar_t characters from string2 to the end
*string2, size_t count); of string1, and appends a wchar_t
null character to the result.
wcsncmp wchar.h int wcsncmp(const wchar_t Compares up to count wide
*string1, const wchar_t characters in string1 to string2.
*string2, size_t count);
wcsncpy wchar.h wchar_t *wcsncpy(wchar_t Copies up to count wide
*string1, const wchar_t characters from string2 to string1.
*string2, size_t count);
wcspbrk wchar.h wchar_t *wcspbrk(const Locates the first occurrence in the
wchar_t *string1, const string pointed to by string1 of any
wchar_t *string2); wide characters from the string
pointed to by string2.
wcsptime wchar.h wchar_t *wcsptime ( const Date and time conversion.
wchar_t *buf, const Equivalent to strptime(), except
wchar_t *format, struct tm that it uses wide characters.
*tm );
wcsrchr wchar.h wchar_t *wcsrchr(const Locates the last occurrence of
wchar_t *string, wchar_t character in the string pointed to
character); by string.
wcsrtombs4 wchar.h size_t wcsrtombs (char Converts wide character string to
*dst, const wchar_t **src, multibyte string. (Restartable
size_t len, mbstate_t *ps); version of wcstombs.)
wcsspn wchar.h size_t wcsspn(const Computes the number of wide
wchar_t *string1, const characters in the initial segment of
wchar_t *string2); the string pointed to by string1,
which consists entirely of wide
characters from the string pointed
to by string2.
wcsstr wchar.h wchar_t *wcsstr(const Locates the first occurrence of
wchar_t *wcs1, const wcs2 in wcs1.
wchar_t *wcs2);
wcstod wchar.h double wcstod(const Converts the initial portion of the
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
wchar_t *nptr, wchar_t wide-character string pointed to
**endptr); by nptr to a double value.
wcstod32 wchar.h _Decimal32 Converts the initial portion of the
wcstod32(const wchar_t wide-character string pointed to
*nptr, wchar_t **endptr); by nptr to a single-precision
decimal floating-point value.
wcstod64 wchar.h _Decimal64 Converts the initial portion of the
wcstod64(const wchar_t wide-character string pointed to
*nptr, wchar_t **endptr); by nptr to a double-precision
decimal floating-point value.
wcstod128 wchar.h _Decimal128 Converts the initial portion of the
wcstod128(const wchar_t wide-character string pointed to
*nptr, wchar_t **endptr); by nptr to a quad-precision
decimal floating-point value.
wcstok wchar.h wchar_t *wcstok(wchar_t Breaks wcs1 into a sequence of
*wcs1, const wchar_t tokens, each of which is delimited
*wcs2, wchar_t **ptr) by a wide character from the wide
string pointed to by wcs2.
wcstol wchar.h long int wcstol(const Converts the initial portion of the
wchar_t *nptr, wchar_t wide-character string pointed to
**endptr, int base); by nptr to a long integer value.
wcstombs stdlib.h size_t wcstombs(char Converts the wchar_t string into a
*dest, const wchar_t multibyte string dest.
*string, size_t count);
wcstoul wchar.h unsigned long int Converts the initial portion of the
wcstoul(const wchar_t wide-character string pointed to
*nptr, wchar_t **endptr, by nptr to an unsigned long
int base); integer value.
wcsxfrm4 wchar.h size_t wcsxfrm (wchar_t Transforms a wide-character
*wcs1, const wchar_t string to values which represent
*wcs2, size_t n); character collating weights and
places the resulting wide-
character string into an array.
wctob stdarg.h int wctob(wint_t wc); Determines whether wc
wchar.h corresponds to a member of the
extended character set whose
multibyte character representation
is a single byte when in the initial
shift state.
wctomb stdlib.h int wctomb(char *string, Converts the wchar_t value of
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
wchar_t character); character into a multibyte string.
wctrans wctype.h wctrans_t wctrans(const Constructs a value with type
char *property); wctrans_t that describes a
mapping between wide characters
identified by the string argument
property.
wctype4 wchar.h wctype_t wctype (const Obtains handle for character
char *property); property classification.
wcwidth wchar.h int wcswidth(const wchar_t Determine the display width of a
*pwcs, size_t n); wide character string.
wmemchr wchar.h wchar_t *wmemchr(const Locates the first occurrence of c in
wchar_t *s, wchar_t c, the initial n wide characters of the
size_t n); object pointed to by s.
wmemcmp wchar.h int wmemcmp(const Compares the first n wide
wchar_t *s1, const wchar_t characters of the object pointed to
*s2, size_t n); by s1 to the first n characters of
the object pointed to by s2.
wmemcpy wchar.h wchar_t Copies n wide characters from the
*wmemcpy(wchar_t *s1, object pointed to by s2 to the
const wchar_t *s2, size_t object pointed to by s1.
n);
wmemmove wchar.h wchar_t Copies n wide characters from the
*wmemmove(wchar_t *s1, object pointed to by s2 to the
const wchar_t *s2, size_t object pointed to by s1.
n);
wmemset wchar.h wchar_t Copies the value of c into each of
*wmemset(wchar_t *s, the first n wide characters of the
wchar_t c, size_t n); object pointed to by s.
wprintf6 wchar.h int wprintf(const wchar_t Equivalent to fwprintf with the
*format, arg-list); argument stdout interposed before
the arguments to wprintf.
wscanf6 wchar.h int wscanf(const wchar_t Equivalent to fwscanf with the
*format, arg-list); argument stdin interposed before
the arguments of wscanf.
y0 math.h double y0(double x); Calculates the Bessel function
value of the second kind of order
0.
y1 math.h double y1(double x); Calculates the Bessel function
value of the second kind of order
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
System
Function Include File Function Prototype Description
1.
yn math.h double yn(int n, double x); Calculates the Bessel function
value of the second kind of order
n.
Loops in C
Looping statement are the statements execute one or more statement repeatedly several number of
times. In C programming language there are three types of loops; while, for and do-while.
When you need to execute a block of code several number of times then you need to use looping
concept in C language.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Types of Loops.
while loop
for loop
do..while
Conditional statement executes only once in the program where as looping statements executes
repeatedly several number of time.
While loop
In while loop First check the condition if condition is true then control goes inside the loop body
other wise goes outside the body. while loop will be repeats in clock wise direction.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Syntax
Assignment;
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}
Note: If while loop condition never false then loop become infinite loop.
void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("\n%d",i);
i++;
}
getch();
}
Output
1
2
3
4
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
For loop
for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts
Initialization, Condition and Increment or Decrements.
void main()
{
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}
Output
1
2
3
4
do-while
A do-while loop is similar to a while loop, except that a do-while loop is execute at least one time.
A do while loop is a control flow statement that executes a block of code at least once, and then
repeatedly executes the block, or not, depending on a given condition at the end of the block (in
while).
Syntax
do
{
Statements;
........
Increment/decrement (++ or --)
} while();
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
When use do..while Loop
When we need to repeat the statement block at least 1 time then we use do-while loop.
void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Output
1
2
3
4
Nested loop
When we need to repeated loop body itself n number of times use nested loops. Nested loops can be
design upto 255 blocks.
Basis for
while do-while
comparison
do{
while ( condition) { .
General Form statements; //body of loop statements; // body of loop.
} .
} while( Condition );
Controlling In 'while' loop the controlling condition In 'do-while' loop the controlling
Condition appears at the start of the loop. condition appears at the end of the loop.
The iterations do not occur if, the The iteration occurs at least once even if
Iterations condition at the first iteration, appears the condition is false at the first iteration.
false.
1. The while loop checks the condition at the starting of the loop and if the condition is satisfied
statement inside the loop, is executed. In do-while loop, the condition is checked after the
execution of all statements in the body of the loop.
2. If the condition in a while loop is false not a single statement inside the loop is executed, and if the
condition in ‘do-while’ loop is false then also the body of the loop is executed at least once then the
condition is tested.
#include <stdio.h>
int main()
{
int number;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
long long factorial;
factorial = 1;
return 0;
}
do {
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
Flow Diagram
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Example
#include <stdio.h>
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
A loop is used for executing a block of statements repeatedly until a given condition returns false.
C For loop
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Flow Diagram of For loop
Step 1: First initialization happens and the counter variable gets initialized.
Step 2: In the second step the condition is checked, where the counter variable is tested for the
given condition, if the condition returns true then the C statements inside the body of for loop gets
executed, if the condition returns false then the for loop gets terminated and the control comes out
of the loop.
Step 3: After successful execution of statements inside the body of loop, the counter variable is
incremented or decremented, depending on the operation (++ or –).
Output:
1
2
3
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Various forms of for loop in C
2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop.
int num=10;
for (;num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before condition is must,
without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case semicolon
(;) is must after condition logic. In this case the increment or decrement part is done inside the loop.
4) This is also possible. The counter variable is initialized before the loop and incremented inside
the loop.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) As mentioned above, the counter variable can be decremented as well. In the below example the
variable gets decremented each time the loop runs until the condition num>10 returns false.
#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
In the above example we have a for loop inside another for loop, this is called nesting of loops. One
of the example where we use nested for loop is Two dimensional array.
What’s the difference between above for loop and a simple for loop?
1. It is initializing two variables. Note: both are separated by comma (,).
2. It has two test conditions joined together using AND (&&) logical operator. Note: You cannot
use multiple test conditions separated by comma, you must use logical operator such as && or || to
join conditions.
3. It has two variables in increment part. Note: Should be separated by comma.
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
If you are using nested loops, the break statement will stop the execution of the innermost loop and
start executing the next line of code after the block.
Syntax
break;
Flow Diagram
goto can transfer the program’s within the same block and there must a label, where you want to
transfer program’s control.
Defining a label
label_name:
goto label_name;
We can use goto statement to transfer program’s control from down to top (↑) and top to down (↓).
Here, if any-test-condition is true, goto will transfer the program’s control to the specified label-
name.
repeat:
printf("%d\n",number);
number++;
if(number<=10)
goto repeat;
return 0;
}
Output
1
2
3
4
5
6
7
8
9
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
10
Here, if any-test-condition is true, goto will transfer the program’s control to the specified label-
name.
if(number<=0)
goto end;
printf("Number is : %d", number);
end:
printf("Bye Bye !!!");
return 0;
}
Output
First run:
Enter an integer number: 123
Number is : 123
Bye Bye !!!
Second run:
Enter an integer number: 0
Bye Bye !!!
Continue
The continue statement in C programming works somewhat like the break statement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in
between.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
For the for loop, continue statement causes the conditional test and increment portions of the loop
to execute. For the while and do...while loops, continue statement causes the program control to
pass to the conditional tests.
Syntax
continue;
Flow Diagram
Example
#include <stdio.h>
int main () {
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
} while( a < 20 );
return 0;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
An array is a collection of data items, all of the same type, accessed using a common name.
A one-dimensional array is like a list; A two dimensional array is like a table; The C language places
no limits on the number of dimensions in an array, though specific implementations may.
Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use
the general term arrays when the number of dimensions is unspecified or unimportant.
Declaring Arrays
Array variables are declared identically to variables of their data type, except that the variable
name is followed by one pair of square [ ] brackets for each dimension of the array.
Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square
brackets.
Dimensions used when declaring arrays in C must be positive integral constants or constant
expressions.
o In C99, dimensions must still be positive integers, but variables can be used, so long as the
variable has a positive value at the time the array is declared. ( Space is allocated only once,
at the time the array is declared. The array does NOT change sizes later if the variable used
to declare it changes. )
Examples:
const int NROWS = 100; // ( Old code would use #define NROWS
100 )
const int NCOLS = 200; // ( Old code would use #define NCOLS
200 )
float matrix[ NROWS ][ NCOLS ];
Example:
int numElements;
printf( "How big an array do you want? " );
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
scanf( "%d", &numElements; )
if( numElements <= 0 ) {
printf( "Error - Quitting\n" );
exit( 0 );
}
double data[ numElements ]; // This only works in C99, not in
plain C
Initializing Arrays
Arrays may be initialized when they are declared, just as any other variables.
Place the initialization data in curly {} braces following the equals sign. Note the use of commas in
the examples below.
An array may be partially initialized, by providing fewer data items than the size of the array. The
remaining array elements will be automatically initialized to zero.
If an array is to be completely initialized, the dimension of the array is not required. The compiler
will automatically size the array to fit the initialized data. ( Variation: Multidimensional arrays - see
below. )
Examples:
int i = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 }, k;
float sum = 0.0f, floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
double piFractions[ ] = { 3.141592654, 1.570796327, 0.785398163
};
Designated Initializers:
In above there is an alternate mechanism, that allows you to initialize specific elements, not
necessarily at the beginning.
This method can be mixed in with traditional iniitalization
For example:
int numbers[ 100 ] = { 1, 2, 3, [10] = 10, 11, 12, [60] = 50, [42] = 420 };
Using Arrays
Elements of an array are accessed by specifying the index ( offset ) of the desired element within
square [ ] brackets after the array name.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Array subscripts must be of integer type. ( int, long int, char, etc. )
VERY IMPORTANT: Array indices start at zero in C, and go to one less than the size of the array. For
example, a five element array will have indices zero through four. This is because the index in C is
actually an offset from the beginning of the array. ( The first element is at the beginning of the
array, and hence has zero offset. )
Landmine: The most common mistake when working with arrays in C is forgetting that indices
start at zero and stop one less than the array size.
Arrays are commonly used in conjunction with loops, in order to perform the same calculations on
all ( or some part ) of the data items in the array.
The first sample program uses loops and arrays to calculate the first twenty Fibonacci
numbers. Fibonacci numbers are used to determine the sample points used in certain optimization
methods.
#include <stdlib.h>
#include <stdio.h>
int i, fibonacci[ 20 ];
fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;
#include <stdlib.h>
#include <stdio.h>
int numbers[ 10 ];
int i, index = 2;
numbers[ 8 ] = 25;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
numbers[ 5 ] = numbers[ 9 ] / 3;
numbers[ 4 ] += numbers[ 2 ] / numbers[ 1 ];
numbers[ index ] = 5;
++numbers[ index ];
numbers[ numbers[ index++ ] ] = 100;
numbers[ index ] = numbers[ numbers[ index + 1 ] / 7 ]--;
Multidimensional Arrays
Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after
the variable name in the declaration statement.
One dimensional arrays do not require the dimension to be given if the array is to be completely
initialized. By analogy, multi-dimensional arrays do not require the first dimension to be given if
the array is to be completely initialized. All dimensions after the first must be given in any case.
For two dimensional arrays, the first dimension is commonly considered to be the number of rows,
and the second dimension the number of columns. We will use this convention when discussing
two dimensional arrays.
Two dimensional arrays are considered by C/C++ to be an array of ( single dimensional arrays ). For
example, "int numbers[ 5 ][ 6 ]" would refer to a single dimensional array of 5 elements, wherein
each element is a single dimensional array of 6 integers. By extension, "int numbers[ 12 ][ 5 ][ 6 ]"
would refer to an array of twelve elements, each of which is a two dimensional array, and so on.
Another way of looking at this is that C stores two dimensional arrays by rows, with all elements of
a row being stored together as a single unit. Knowing this can sometimes lead to more efficient
programs.
Multidimensional arrays may be completely initialized by listing all data elements within a single
pair of curly {} braces, as with single dimensional arrays.
It is better programming practice to enclose each row within a separate subset of curly {} braces, to
make the program more readable. This is required if any row other than the last is to be partially
initialized. When subsets of braces are used, the last item within braces is not followed by a
comma, but the subsets are themselves separated by commas.
Multidimensional arrays may be partially initialized by not providing complete initialization
data. Individual rows of a multidimensional array may be partially initialized, provided that subset
braces are used.
Individual data items in a multidimensional array are accessed by fully qualifying an array
element. Alternatively, a smaller dimensional array may be accessed by partially qualifying the
array name. For example, if "data" has been declared as a three dimensional array of floats, then
data[ 1 ][ 2 ][ 5 ] would refer to a float, data[ 1 ][ 2 ] would refer to a one-dimensional array of
floats, and data[ 1 ] would refer to a two-dimensional array of floats. The reasons for this and the
incentive to do this relate to memory-management issues that are beyond the scope of these
notes.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Sample Program Using 2-D Arrays
/* Sample program Using 2-D Arrays */
#include <stdlib.h>
#include <stdio.h>
return 0;
}
int main()
{
int ageArray[] = {2, 3, 4};
display(ageArray[2]); //Passing array element ageArray[2]
return 0;
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Output
#include <stdio.h>
float average(float age[]);
int main()
{
float avg, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}
Output
To pass an entire array to a function, only the name of the array is passed as an argument. However,
notice the use of [] after argument name in float average(float age[]). This informs the
compiler that you are passing a one-dimensional array to the function.
To pass multidimensional arrays to a function, only the name of the array is passed (similar to one
dimensional array).
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Linear search is a very basic and simple search algorithm. In Linear search, we search an element or
value in a given array by traversing the array from the starting, till the desired element or value is
found.
As we learned in the previous tutorial that the time complexity of Linear search algorithm is O(n),
we will analyse the same and see why it is O(n) after implementing it.
To search the number 5 in the array given below, linear search will go step by step in a sequential
order starting from the first element in the given array.
/*
below we have implemented a simple function
for linear search in C
target = 77
Output: 4
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search
algorithm works on the principle of divide and conquer. For this algorithm to work properly, the
data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection. If a
match occurs, then the index of item is returned. If the middle item is greater than the item, then the
item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for
in the sub-array to the right of the middle item. This process continues on the sub-array as well until
the size of the subarray reduces to zero.
For a binary search to work, it is mandatory for the target array to be sorted. We shall learn the
process of binary search with a pictorial example. The following is our sorted array and let us
assume that we need to search the location of value 31 using binary search.
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that
the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a
sorted array, so we also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
The value stored at location 7 is not a match, rather it is more than what we are looking for. So, the
value must be in the lower part from this location.
We compare the value stored at location 5 with our target value. We find that it is a match.
Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.
Pseudocode
Procedure binary_search
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
end procedure
#include <stdio.h>
#define MAX 20
printf("=\n");
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
// compute the mid point
// midPoint = (lowerBound + upperBound) / 2;
midPoint = lowerBound + (upperBound - lowerBound) / 2;
// data found
if(intArray[midPoint] == data) {
index = midPoint;
break;
} else {
// if data is larger
if(intArray[midPoint] < data) {
// data is in upper half
lowerBound = midPoint + 1;
}
// data is smaller
else {
// data is in lower half
upperBound = midPoint -1;
}
}
}
printf("Total comparisons made: %d" , comparisons);
return index;
}
void display() {
int i;
printf("[");
printf("]\n");
}
void main() {
printf("Input Array: ");
display();
printline(50);
//find location of 1
int location = find(55);
If we compile and run the above program then it would produce following result −
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Output
Input Array: [1 2 3 4 6 7 9 11 12 14 15 16 17 19 33 34 43 45 55 66 ]
==================================================
Comparison 1
lowerBound: 0, intArray[0] = 1
upperBound : 19, intArray[19] = 66
Comparison 2
lowerBound : 10, intArray[10] = 15
upperBound : 19, intArray[19] = 66
Comparison 3
lowerBound : 15, intArray[15] = 34
upperBound : 19, intArray[19] = 66
Comparison 4
lowerBound : 18, intArray[18] = 55
upperBound : 19, intArray[19] = 66
Total comparisons made: 4
Element found at location: 19
SELECTION SORT
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost element,
and that element becomes a part of the sorted array. This process continues moving unsorted array
boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case complexities are of
Ο(n2), where n is the number of items.
For the first position in the sorted list, the whole list is scanned sequentially. The first position
where 14 is stored presently, we search the whole list and find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the
list, appears in the first position of the sorted list.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Now, let us learn some programming aspects of selection sort.
Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Pseudocode
procedure selection sort
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
end procedure
1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], n, c, d, position, swap;
6.
7. printf("Enter number of elements\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d integers\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. for (c = 0; c < (n - 1); c++)
16. {
17. position = c;
18.
19. for (d = c + 1; d < n; d++)
20. {
21. if (array[position] > array[d])
22. position = d;
23. }
24. if (position != c)
25. {
26. swap = array[c];
27. array[c] = array[position];
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
28. array[position] = swap;
29. }
30. }
31.
32. printf("Sorted list in ascending order:\n");
33.
34. for (c = 0; c < n; c++)
35. printf("%d\n", array[c]);
36.
37. return 0;
38. }
BUBBLE SORT
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in
which each pair of adjacent elements is compared and the elements are swapped if they are not in
order. This algorithm is not suitable for large data sets as its average and worst case complexity are
of Ο(n2) where n is the number of items.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
How Bubble Sort Works?
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it short
and precise.
Bubble sort starts with very first two elements, comparing them to check which one is greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33
with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one iteration, the
array should look like this −
To be precise, we are now showing how an array should look like after each iteration. After the
second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
Algorithm
We assume list is an array of n elements. We further assume that swap function swaps the values of
the given array elements.
begin BubbleSort(list)
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole
array is completely sorted in an ascending order. This may cause a few complexity issues like what
if the array needs no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap has
happened or not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it
will come out of the loop.
loop = list.count;
end for
end for
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Implementation
One more issue we did not address in our original algorithm and its improvised pseudocode, is that,
after every iteration the highest values settles down at the end of the array. Hence, the next iteration
need not include already sorted elements.
#include <stdio.h>
#include <stdbool.h>
#define MAX 10
void display() {
int i;
printf("[");
printf("]\n");
}
void bubbleSort() {
int temp;
int i,j;
swapped = true;
printf(" => swapped [%d, %d]\n",list[j],list[j+1]);
} else {
printf(" => not swapped\n");
}
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
// if no number was swapped that means
// array is sorted now, break the loop.
if(!swapped) {
break;
}
void main() {
printf("Input Array: ");
display();
printf("\n");
bubbleSort();
printf("\nOutput Array: ");
display();
}
INSERTION SORT
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
Algorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
Example:
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Another Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 5 (Size of input array)
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position
ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of
their current position.
5, 6, 11, 12, 13
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in
above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
MERGE SORT
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time
complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic
values are achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two
arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the
color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted
manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list
of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44
are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them
into a list of found data values placing all in a sorted order.
After the final merging, the list should look like this −
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Now we should learn some programming aspects of merge sorting.
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By
definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller
sorted lists keeping the new list sorted too.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main
functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.
l1 = mergesort( l1 )
l2 = mergesort( l2 )
var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if
end while
return c
end procedure
1. #include <stdio.h>
2.
3. void mergeSort(int [], int, int, int);
4. void partition(int [],int, int);
5.
6. int main()
7. {
8. int list[50];
9. int i, size;
10.
11. printf("Enter total number of elements:");
12. scanf("%d", &size);
13. printf("Enter the elements:\n");
14. for(i = 0; i < size; i++)
15. {
16. scanf("%d", &list[i]);
17. }
18. partition(list, 0, size - 1);
19. printf("After merge sort:\n");
20. for(i = 0;i < size; i++)
21. {
22. printf("%d ",list[i]);
23. }
24.
25. return 0;
26. }
27.
28. void partition(int list[],int low,int high)
29. {
30. int mid;
31.
32. if(low < high)
33. {
34. mid = (low + high) / 2;
35. partition(list, low, mid);
36. partition(list, mid + 1, high);
37. mergeSort(list, low, mid, high);
38. }
39. }
40.
41. void mergeSort(int list[],int low,int mid,int high)
42. {
43. int i, mi, k, lo, temp[50];
44.
45. lo = low;
46. i = low;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
47. mi = mid + 1;
48. while ((lo <= mid) && (mi <= high))
49. {
50. if (list[lo] <= list[mi])
51. {
52. temp[i] = list[lo];
53. lo++;
54. }
55. else
56. {
57. temp[i] = list[mi];
58. mi++;
59. }
60. i++;
61. }
62. if (lo > mid)
63. {
64. for (k = mi; k <= high; k++)
65. {
66. temp[i] = list[k];
67. i++;
68. }
69. }
70. else
71. {
72. for (k = lo; k <= mid; k++)
73. {
74. temp[i] = list[k];
75. i++;
76. }
77. }
78.
79. for (k = low; k <= high; k++)
80. {
81. list[k] = temp[k];
82. }
83. }
$ cc pgm28.c
$ a.out
Enter total number of elements:5
Enter the elements:
12
36
22
76
54
After merge sort:
12 22 36 54 76
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
UNIT III
FUNCTIONS
A function is a block of statements that performs a specific task. Suppose you are building an
application in C language and in one of your program, you need to perform a same task more than
once. In such case you have two options –
a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need to perform that task.
Using option (b) is a good practice and a good programmer always uses functions while writing
codes in C.
Types of functions
1) Predefined standard library functions – such as puts(), gets(), printf(), scanf() etc –
These are the functions which already have a definition in header files (.h files like stdio.h), so we
just call them whenever there is a need to use them.
2) User Defined functions – The functions that we create in a program are known as user defined
functions.
In this guide, we will learn how to create user defined functions and how to use them in C
Programming
Syntax of a function
return_type function_name (argument list)
{
Set of statements – Block of code
}
return_type: Return type can be of any data type such as int, double, char, void, short etc. Don’t
worry you will understand these terms better once you go through the examples below.
function_name: It can be anything, however it is advised to have a meaningful name for the
functions so that it would be easy to understand the purpose of function just by seeing it’s name.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
argument list: Argument list contains variables names along with their data types. These
arguments are kind of inputs for the function. For example – A function which is used to add two
integer variables, will be having two integer argument.
Block of code: Set of C statements, which will be executed whenever a call will be made to the
function.
Do you find above terms confusing? – Do not worry I’m not gonna end this guide until you
learn all of them :)
Lets take an example – Suppose you want to create a function to add two integer variables.
This function addition adds two integer variables, which means I need two integer variable as input,
lets provide two integer parameters in the function signature. The function signature would be –
The result of the sum of two integers would be integer only. Hence function should return an
integer value – I got my return type – It would be integer –
So you got your function prototype or signature. Now you can implement the logic in C program
like this:
int main()
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);
return 0;
}
Output:
Example2: Creating a void user defined function that doesn’t return anything
#include <stdio.h>
/* function return type is void and it doesn't have parameters*/
void introduction()
{
printf("Hi\n");
printf("My name is Chaitanya\n");
printf("How are you?");
/* There is no return statement inside this function, since its
* return type is void
*/
}
int main()
{
/*calling function*/
introduction();
return 0;
}
Output:
Hi
My name is Chaitanya
How are you?
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
3) There is no limit on number of functions; A C program can have any number of functions.
4) A function can call itself and it is known as “Recursion“. I have written a separate guide for it.
Note: for example, if function return type is char, then function should return a value of char type
and while calling this function the main() function should have a variable of char data type to store
the returned value.
int main()
{
…
char c1 = abc('a', 'x');
…
}
1) Function – Call by value method – In the call by value method the actual arguments are copied
to the formal arguments, hence any operation performed by function on arguments doesn’t affect
actual parameters.
2) Function – Call by reference method – Unlike call by value, in this method, address of actual
arguments (or parameters) is passed to the formal parameters, which means any operation
performed on formal parameters affects the value of actual parameters.
There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.
Let's understand call by value and call by reference in c language one by one.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Call by value in C
In call by value method, the value of the actual parameters is copied into the formal parameters. In
other words, we can say that the value of the variable is used in the function call in the call by value
method.
In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
In call by value, different memory is allocated for actual and formal parameters since the value of
the actual parameter is copied into the formal parameter.
The actual parameter is the argument which is used in the function call whereas formal parameter
is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
14. Output
15. Before function call x=100
16. Before adding value inside function num=100
17. After adding value inside function num=200
18. After function call x=100
19. Call by Value Example: Swapping the values of the two variables
#include <stdio.h>
int main()
int a = 10;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in m
ain
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not
change by changing the formal parameters in call by value, a = 10, b = 20
int temp;
temp = a;
a=b;
b=temp;
Output
Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual parameter.
The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual parameters.
All the operations in the function are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Consider the following example for the call by reference.
#include<stdio.h>
(*num) += 100;
int main() {
int x=100;
return 0;
Output
#include <stdio.h>
int main()
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in m
ain
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do ch
ange in call by reference, a = 10, b = 20
int temp;
temp = *a;
*a=*b;
*b=temp;
Output
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Difference between call by value and call by reference in c
No. Call by value Call by reference
1 A copy of the value is passed into the function An address of value is passed into the function
Actual and formal arguments are created at the Actual and formal arguments are created at the
3
different memory location same memory location
When a function gets executed in the program, the execution control is transferred from calling
function to called function and executes function definition, and finally comes back to the calling
function. In this process, both calling and called functions have to communicate each other to
exchange information. The process of exchanging information between calling and called functions
is called as inter function communication.
Downward Communication
Upward Communication
Bi-directional Communication
Downward Communication
In this type of inter function communication, the data is transferred from calling function to called
function but not from called function to calling function. The functions with parameters and without
return value are considered under downward communication. In the case of downward
communication, the execution control jumps from calling function to called function along with
parameters and executes the function definition,and finally comes back to the calling function
without any return value. For example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
Output:
Upward Communication
In this type of inter function communication, the data is transferred from called function to calling
function but not from calling function to called function. The functions without parameters and with
return value are considered under upward communication. In the case of upward communication,
the execution control jumps from calling function to called function without parameters and
executes the function definition, and finally comes back to the calling function along with a return
value. For example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
result = addition() ; // calling function
Output:
Bi - Directional Communication
In this type of inter function communication, the data is transferred from calling function to called
function and also from called function to calling function. The functions with parameters and with
return value are considered under bi-directional communication. In the case of bi-drectional
communication, the execution control jumps from calling function to called function along with
parameters and executes the function definition, and finally comes back to the calling function
along with a return value. For example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
num1 = 10 ;
num2 = 20 ;
Output:
STANDARD FUNCTIONS
The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.
All the functions accepts int as a parameter, whose value must be EOF or representable as an
unsigned char.
All the functions return non-zero (true) if the argument c satisfies the condition described, and
zero(false) if not.
Library Functions
1 int isalnum(int c) This function checks whether the passed character is alphanumeric.
2 int isalpha(int c) This function checks whether the passed character is alphabetic.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
3 int iscntrl(int c) This function checks whether the passed character is control character.
4 int isdigit(int c) This function checks whether the passed character is decimal digit.
int isgraph(int c) This function checks whether the passed character has graphical
5
representation using locale.
6 int islower(int c) This function checks whether the passed character is lowercase letter.
7 int isprint(int c) This function checks whether the passed character is printable.
8 int ispunct(int c) This function checks whether the passed character is a punctuation character.
9 int isspace(int c) This function checks whether the passed character is white-space.
10 int isupper(int c) This function checks whether the passed character is an uppercase letter.
11 int isxdigit(int c) This function checks whether the passed character is a hexadecimal digit.
The library also contains two conversion functions that accepts and returns an "int".
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
7 double sin(double x) Returns the sine of a radian angle x.
STRING FUNCTIONS
#include <string.h>
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables can
be declared in C programming language −
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all
the variables a, b, and c are local to main() function.
Live Demo
#include <stdio.h>
int main () {
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.
Live Demo
#include <stdio.h>
int main () {
/* actual initialization */
a = 10;
b = 20;
g = a + b;
return 0;
}
A program can have same name for local and global variables but the value of local variable inside
a function will take preference. Here is an example −
Live Demo
#include <stdio.h>
int main () {
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence over
global variables. Following is an example −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must initialize it yourself.
Global variables are initialized automatically by the system when you define them as follows −
int 0
char '\0'
float 0
double 0
pointer NULL
It is a good programming practice to initialize variables properly, otherwise your program may
produce unexpected results, because uninitialized variables will take some garbage value already
available at their memory location.
Storage Classes in C
Storage Classes are used to describe about the features of a variable/function. These features
basically include the scope, visibility and life-time which help us to trace the existence of a
particular variable during the runtime of a program.
auto: This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can
be only accessed within the block/function they have been declared and not outside them (which
defines their scope). Of course, these can be accessed within nested blocks within the parent
block/function in which the auto variable was declared. However, they can be accessed outside their
scope as well using the concept of pointers given here by pointing to the very exact memory
location where the variables resides. They are assigned a garbage value by default whenever they
are declared.
extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this can be
overwritten/changed in a different block as well. So an extern variable is nothing but a global
variable initialized with a legal value where it is declared in order to be used elsewhere. It can be
accessed within any function/block. Also, a normal global variable can be made extern as well by
placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
signifies that we are not initializing a new variable but instead we are using/accessing the global
variable only. The main purpose of using extern variables is that they can be accessed between two
different files which are part of a large program. For more information on how extern variables
work, have a look at this link.
static: This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have a property of preserving their value even after they
are out of their scope! Hence, static variables preserve the value of their last use in their scope. So
we can say that they are initialized only once and exist till the termination of the program. Thus, no
new memory is allocated because they are not re-declared. Their scope is local to the function to
which they were defined. Global static variables can be accessed anywhere in the program. By
default, they are assigned the value 0 by the compiler.
register: This storage class declares register variables which have the same functionality as that of
the auto variables. The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available. This makes the use of register variables
to be much faster than that of the variables stored in the memory during the runtime of the program.
If a free register is not available, these are then stored in the memory only. Usually few variables
which are to be accessed very frequently in a program are declared with the register keyword which
improves the running time of the program. An important and interesting point to be noted here is
that we cannot obtain the address of a register variable using pointers.
To specify the storage class for a variable, the following syntax is to be followed:
Syntax:
Functions follow the same syntax as given above for variables. Have a look at the following C
example for further clarification:
// classes
#include <stdio.h>
extern int x = 9;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
int z = 10;
int main()
// function)
extern int z;
printf("Hello World!\n");
// and 'z'
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
// printing the register variable 'b'
x = 2;
z = 5;
while (x > 0)
static int y = 5;
y++;
x--;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
}
// exiting
return 0;
Output:
Hello World!
These are the values of the extern integers 'x' and 'z'
respectively: 9 and 10
TYPE QUALIFIERS
C – type qualifiers: The keywords which are used to modify the properties of a variable are called
type qualifiers.
1. const
2. volatile
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
1. const keyword:
Constants are also like normal variables. But, only difference is, their values can’t be
modified by the program once they are defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Please refer C – Constants topic in this tutorial for more details on const keyword.
2. volatile keyword:
When a variable is defined as volatile, the program may not change the value of the variable
explicitly.
But, these variable values might keep on changing without any explicit assignment by the
program. These types of qualifiers are called volatile.
For example, if global variable’s address is passed to clock routine of the operating system
to store the system time, the value in this address keep on changing without any assignment
by the program. These variables are named as volatile variable.
Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;
Recursion in C Programming
The process of calling a function by itself is called recursion and the function which calls itself is
called recursive function. Recursion is used to solve various mathematical problems by dividing it
into smaller problems. This method of solving a problem is called Divide and Conquer.
In programming, it is used to divide complex problem into simpler ones and solving them
individually.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Flowchart of Recursion
Note: In order to prevent infinite recursive call, we need to define proper exit condition in a recursive
function.
int main()
{
printf("Hello world");
main();
return 0;
}
In this program, we are calling main() from main() which is recursion. But we haven't defined any
condition for the program to exit. Hence this code will print "Hello world" infinitely in the output
screen.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
C program to calculate factorial of a number using recursion.
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return (factorial(n-1)*n);
}
int main()
{
int num,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
return 0;
}
Here, factorial is calculated using recursion. The formula for calculating factorial of a number n is,
n! = 1*2*...(n-1)*n
(n-1)! = 1*2*...(n-1)
n! = (n-1)! * n
Here,
Output
Enter a number: 7
Factorial of 7 = 5040
int main()
{
int i,n;
printf("Enter the required term: ");
scanf("%d",&n);
printf("First %d fibonacci numbers are\n",n);
for (i=1; i<=n; i++)
printf("%d\n",fibo(i));
return 0;
}
This program uses recursion to generate Fibonacci series. In a Fibonacci series, nth term can be
obtained by adding (n-1)th and (n-2)th term. Mathematically,
tn = tn-1 + tn-2
Here,
The number of fibonacci terms to be generated is taken from the user and stored in variable n.
A for loop is used to loop through the number to be generated which is sent to the function fibo.
This function is used to calculate and return fibonacci series.
Inside fibo, if the term-number is 1 or 2, it returns 1. This is because, the first two terms of fibonacci
series are both 1. The printed values are 1,1.
Then the next term-number 3 is passed onto fibo function, since it's not 1 or 2, the next term in the
series is calculated by taking fibo(n - 1) + fibo(n - 2), where n = 3. This calculates the last two terms
in the fibonacci series. This is equivalent to fibo(2) + fibo(1), which results in 1 + 1 = 2.
This recursive loop goes on finally printing the series as 1, 1, 2, 3, 5...
Output
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Advantages
Disadvantages of Recursion
Recursive programs are generally slower than non recursive programs because it needs to make a
function call so the program must save all its current state and retrieve them again later. This
consumes more time making recursive programs slower.
Recursive programs requires more memory to hold intermediate states in a stack. Non recursive
programs don't have any intermediate states, hence they don't require any extra memory.
Terminating Condition
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching,
and traversal problems.
A recursive function performs the tasks by dividing it into the subtasks. There is a termination
condition defined in the function which is satisfied by some specific subtask. After this, the
recursion stops and the final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances where the
function keeps calling itself to perform a subtask, is called the recursive case. All the recursive
functions can be written using this format.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
13. }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Quick Sort
The quick sort uses divide and conquer to gain the same advantages as the merge sort, while not
using additional storage. As a trade-off, however, it is possible that the list may not be divided in
half. When this happens, we will see that performance is diminished.
A quick sort first selects a value, which is called the pivot value. Although there are many different
ways to choose the pivot value, we will simply use the first item in the list. The role of the pivot
value is to assist with splitting the list. The actual position where the pivot value belongs in the final
sorted list, commonly called the split point, will be used to divide the list for subsequent calls to the
quick sort.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Figure 12 shows that 54 will serve as our first pivot value. Since we have looked at this example a
few times already, we know that 54 will eventually end up in the position currently holding 31. The
partition process will happen next. It will find the split point and at the same time move other
items to the appropriate side of the list, either less than or greater than the pivot value.
Partitioning begins by locating two position markers—let’s call them leftmark and rightmark—at
the beginning and end of the remaining items in the list (positions 1 and 8 in Figure 13). The goal of
the partition process is to move items that are on the wrong side with respect to the pivot value
while also converging on the split point. Figure 13 shows this process as we locate the position of
54.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
We begin by incrementing leftmark until we locate a value that is greater than the pivot value. We
then decrement rightmark until we find a value that is less than the pivot value. At this point we
have discovered two items that are out of place with respect to the eventual split point. For our
example, this occurs at 93 and 20. Now we can exchange these two items and then repeat the
process again.
At the point where rightmark becomes less than leftmark, we stop. The position of rightmark is
now the split point. The pivot value can be exchanged with the contents of the split point and the
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
pivot value is now in place (Figure 14). In addition, all the items to the left of the split point are less
than the pivot value, and all the items to the right of the split point are greater than the pivot value.
The list can now be divided at the split point and the quick sort can be invoked recursively on the
two halves.
The steps are: 1) Pick an element from the array, this element is called as pivot element.
2) Divide the unsorted array of elements in two arrays with values less than the pivot come in the
first sub array, while all elements with values greater than the pivot come in the second sub-array
(equal values can go either way). This step is called the partition operation.
3) Recursively repeat the step 2(until the sub-arrays are sorted) to the sub-array of elements with
smaller values and separately to the sub-array of elements with greater values. The same logic we
have implemented in the following C program.
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
quicksort(number,0,count-1);
return 0;
}
Output:
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Preprocessor Commands in C
In C programming language, preprocessor directive is a step performed before the actual source
code compilation. It is not the part of compilation. Preprocessor directives in C programming
language are used to define and replace tokens in the text and also used to insert the contents of
other files into the source file.
When we try to compile a program, preprocessor commands are executed first and then the program
gets compiled.
Every preprocessor command begins with # symbol. We can also create preprocessor commands
with parameters.
#define
#define is used to create symbolic constants (known as macros) in C programming language. This
preprocessor command can also be used with parameterized macros.
Example Program
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main(){
area = PI * SQR(radius) ;
printf("area = %ld",area);
getch();
}
Output:
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
#undef
#undef is used to destroy a macro that was already created using #define.
#ifdef
#ifdef returns TRUE if the macro is defined and returns FALSE if the macro is not defined.
#ifndef
#ifndef returns TRUE if the specified macro is not defined otherwise returns FALSE.
#if
#else
#elif
#endif
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
#include
#error
UNIT IV
POINTERS
A Pointer in C language is a variable which holds the address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language.
Address in C
Whenever a variable is defined in C language, a memory location is assigned for it, in which it's
value will be stored. We can easily check this memory address, using the & symbol.
If var is the name of the variable, then &var will give it's address.
Let's write a small program to see memory address of any variable that we define in our program.
#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is: %x\n", &var);
}
Value of the variable var is: 7 Memory address of the variable var is: bcc7a00
You must have also seen in the function scanf(), we mention &var to take user input for any
variable var.
scanf("%d", &var);
This is used to store the user inputted value to the address of the variable var.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Concept of Pointers
Whenever a variable is declared in a 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,
which we just saw above.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10;
We can access the value 10 either by using the variable name a or by using its address 80F.
The question is how we can access a variable using it's address? Since the memory addresses are
also just numbers, they can also be assigned to some other variable. The variables which are used to
hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some other
variable. And the value of a pointer variable gets stored in another memory location.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Benefits of using pointers
In this tutorial, we will learn how to declare, initialize and use a pointer. We will also learn what
NULL pointer are and where to use them. Let's start!
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer variable is
pointing. void type pointer works with all data types, but is not often used.
Pointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer
variable can only contain address of a variable of the same data type. In C language address
operator & is used to determine the address of a variable. The & (immediately preceding a variable
name) returns the address of the variable associated with it.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variablea always point to variables of same datatype. Let's have an example to showcase
this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer variable while declaration, it
is recommended to assign a NULL value to your pointer variable. A pointer which is assigned a NULL
value is called a NULL pointer.
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Using the pointer or Dereferencing of Pointer
Once a pointer has been assigned the address of a variable, to access the value of the variable,
pointer is dereferenced, using the indirection operator or dereferencing operator *.
#include <stdio.h>
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
return 0;
}
1. While declaring/initializing the pointer variable, * indicates that the variable is a pointer.
2. The address of any variable is given by preceding the variable name with Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a
is going to contain an integer value. It means that a is going to contain the address of a variable
storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can be
read as 'value at'.
#include <stdio.h>
int main()
{
int i = 10; // normal integer variable storing value 10
int *a; // since '*' is used, hence its a pointer variable
/*
'&' returns the address of the variable 'i'
which is stored in the pointer variable 'a'
*/
a = &i;
/*
below, address of variable 'i', which is stored
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
by a pointer variable 'a' is displayed
*/
printf("Address of variable i is %u\n", a);
/*
below, '*a' is read as 'value at a'
which is 10
*/
printf("Value at the address, which is stored by pointer variable a is
%d\n", *a);
return 0;
}
OUTPUT
Address of variable i is 2686728 (The address may vary) Value at an address, which is stored by pointer
variable a is 10
we can have pointers to other pointers. If we're used to thinking about simple pointers, and to
keeping clear in our minds the distinction between the pointer itself and what it points to, we should
be able to think about pointers to pointers, too, although we'll now have to distinguish between the
pointer, what it points to, and what the pointer that it points to points to. (And, of course, we might
also end up with pointers to pointers to pointers, or pointers to pointers to pointers to pointers,
although these rapidly become too esoteric to have any practical use.)
int **ipp;
where the two asterisks indicate that two levels of pointers are involved.
Starting off with the familiar, uninspiring, kindergarten-style examples, we can demonstrate the use
of ipp by declaring some pointers for it to point to and some ints for those pointers to point to:
int i = 5, j = 6; k = 7;
int *ip1 = &i, *ip2 = &j;
Now we can set
ipp = &ip1;
and ipp points to ip1 which points to i. *ipp is ip1, and **ipp is i, or 5. We can illustrate the
situation, with our familiar box-and-arrow notation, like this:
If we say
*ipp = ip2;
we've changed the pointer pointed to by ipp (that is, ip1) to contain a copy of ip2, so that it (ip1)
now points at j:
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
If we say
*ipp = &k;
we've changed the pointer pointed to by ipp (that is, ip1 again) to point to k:
What are pointers to pointers good for, in practice? One use is returning pointers from functions, via
pointer arguments rather than as the formal return value. To explain this, let's first step back and
consider the case of returning a simple type, such as int, from a function via a pointer argument. If
we write the function
f(int *ip)
{
*ip = 5;
}
and then call it like this:
int i;
f(&i);
then f will ``return'' the value 5 by writing it to the location specified by the pointer passed by the
caller; in this case, to the caller's variable i. A function might ``return'' values in this way if it had
multiple things to return, since a function can only have one formal return value (that is, it can only
return one value via the return statement.) The important thing to notice is that for the function to
return a value of type int, it used a parameter of type pointer-to-int.
POINTER TO AN ARRAY
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can
also declare a pointer that can point to whole array instead of only one element of the array. This
pointer is useful when talking about multidimensional arrays.
Syntax:
data_type (*var_name)[size_of_array];
Example:
int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence
than indirection, it is necessary to enclose the indirection operator and pointer name inside
parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the whole
array are totally different. The following program shows this:
filter_none
edit
play_arrow
brightness_4
int main()
{
// Pointer to an integer
int *p;
p++;
ptr++;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
printf("p = %p, ptr = %p\n", p, ptr);
return 0;
}
Output:
p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr.
The base type of p is int while base type of ptr is ‘an array of 5 integers’.
We know that the pointer arithmetic is performed relative to the base size, so if we write
ptr++, then the pointer ptr will be shifted forward by 20 bytes.
The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array.
On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer
to an array points to an array, so on dereferencing it, we should get the array, and the name of array
denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address
of the array to which it points.
filter_none
edit
play_arrow
brightness_4
int main()
{
int arr[] = { 3, 5, 6, 7, 9 };
int *p = arr;
int (*ptr)[5] = &arr;
Output:
1. Pointers and two dimensional Arrays: In a two dimensional array, we can access each
element by using two subscripts, where first subscript represents the row number and second
subscript represents the column number. The elements of 2-D array can be accessed with the
help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr[i][j]
of the array using the pointer expression *(*(arr + i) + j). Now we’ll see how this
expression can be derived.
Let us take a two dimensional array arr[3][4]:
int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
Since memory in computer is organized linearly it is not possible to store the 2-D array in
rows and columns. The concept of rows and columns is only theoretical, actually a 2-D
array is stored in row major order i.e rows are placed next to each other. The following
figure shows how the above 2-D array will be stored in memory.
Each row can be considered as a 1-D array, so a two-dimensional array can be considered as
a collection of one-dimensional arrays that are placed one after another. In other words we
can say that a 2-D dimensional arrays that are placed one after another. So here arr is an
array is an array of 3 elements where each element is a 1-D array of 4 integers.
We know that the name of an array is a constant pointer that points to 0th 1-D array and
contains address 5000. Since arr is a ‘pointer to an array of 4 integers’, according to pointer
arithmetic the expression arr + 1 will represent the address 5016 and expression arr + 2 will
represent address 5032.
So we can say that arr points to the 0th 1-D array, arr + 1 points to the 1st 1-D array and arr
+ 2 points to the 2nd 1-D array.
o Since arr + i points to ith element of arr, on dereferencing it will get ith element of arr
which is of course a 1-D array. Thus the expression *(arr + i) gives us the base
address of ith 1-D array.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
o We know, the pointer expression *(arr + i) is equivalent to the subscript expression
arr[i]. So *(arr + i) which is same as arr[i] gives us the base address of ith 1-D
array.
*(arr + i) - arr[i] - Base address of ith 1-D array -> Points to 0th
element of ith 1-D array
Note: Both the expressions (arr + i) and *(arr + i) are pointers, but their base type are
different. The base type of (arr + i) is ‘an array of 4 units’ while the base type of *(arr + i)
or arr[i] is int.
o To access an individual element of our 2-D array, we should be able to access any jth
element of ith 1-D array.
o Since the base type of *(arr + i) is int and it contains the address of 0th element of ith
1-D array, we can get the addresses of subsequent elements in the ith 1-D array by
adding integer values to *(arr + i).
o For example *(arr + i) + 1 will represent the address of 1st element of 1stelement of
ith 1-D array and *(arr+i)+2 will represent the address of 2nd element of ith 1-D
array.
o Similarly *(arr + i) + j will represent the address of jth element of ith 1-D array. On
dereferencing this expression we can get the jth element of the ith 1-D array.
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
filter_none
edit
play_arrow
brightness_4
int main()
{
int arr[3][4] = {
{ 10, 11, 12, 13 },
{ 20, 21, 22, 23 },
{ 30, 31, 32, 33 }
};
int i, j;
for (i = 0; i < 3; i++)
{
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
printf("Address of %dth array = %p %p\n",
i, arr[i], *(arr + i));
return 0;
}
Output:
int arr[2][3][2] = { {{5, 10}, {6, 11}, {7, 12}}, {{20, 30}, {21, 31},
{22, 32}} };
filter_none
edit
play_arrow
brightness_4
return 0;
}
Output:
5 10
6 11
7 12
20 30
21 31
22 32
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
While processing elements of an array (as you will see in the next chapter) C programmers often
mix indirection operator (*) and increment/decrement operator( ++ and -- ).
Always remember that the precedence of indirection operator (*) and increment/decrement operator
are same and they associate from right to left.
Suppose x is integer variable and p is a pointer to int. Now consider the following statements and
try to interpret them.
Example 1:
1 x = *p++;
Since * and ++ operators have the same precedence and associate from right to left ++ will be
applied to p not to *p. Because the increment operator is postfix, so first the value of p is used in the
expression then it will be incremented. Therefore first integer pointed by p will be dereferenced and
assigned to x, then the value of p will be incremented by 1.
Example 2:
1 x = ++*p;
Here * operator will be first applied to p then ++ will be applied to *p. Therefore first integer
pointer is dereferenced, the value obtained from dereferencing is incremented and eventually
assigned to x.
Example 3:
1 x = *++p;
++ operator is prefixed, so first, p will be incremented, then the value at the new address is
dereferenced and assigned to x.
Note: If you still have any confusion, you can always use () around expression which you want to
evaluate first.
Pointer Comparison
You can use relational operators ( <, <=, >, >= , == , !=) with pointers. The == and !=operators are
used to compare two pointers whether they contain the same address or not. Two pointers are equal
when they both are null, or contains the address of the same variable. Use of these (i.e == and !=)
operators are valid only when pointers are of the same base type, or between a null pointer and any
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad
other pointer, or void pointer(will be discussed later) and any other pointer. Use of other relational
operators (<, <=, >, >=) to compare two pointers is meaningful only when they both point to the
elements of the same array.
Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2 bytes
because int is also of 2 bytes.
float* i;
i++;
In this case, size of pointer is still 2 bytes initially. But now, when we increment it, it will increment
by 4 bytes because float datatype is of 4 bytes.
double* i;
i++;
Computer Programming and Problem Solving: Notes Compiled by Mrs. Azmath Mubeen Asst.Prof
Department of Computer Science, University College for Women, Koti,
Hyderabad