C Programming
C Programming
Panavoor,Thiruvananthapuram,Kerala
Name : ……………………………………………………………………………………………
SYLLABUS
COURSE CONTENT
Module III: Control structures: if, if else, switch-case, for, while, do-while,
break, continue. Arrays: Defining simple arrays, Multi-dimensional arrays,
declaration, initialization and processing. Functions & Pointers: User defined
functions, declaration, definition & scope, recursion, Pointers: The & and *
Operators, pointer declaration, visualizing pointers, call by value; call by
reference.
MODULE 1
Components & Characteristics of Computer
Components of Computers can be defined as the vital elements of the computer system
that makes the device fully functional and run without procedural troubles. It is typically
the basic hardware units that complete the structural architecture of the computer
system.
The main components of a Computer System’s Architecture and their functional flow are
as below,
• Input unit
• Processing unit
• Output unit
Though these components can work independently, to make the computer system give
accurate outcomes, it is important for these components to function in harmony with one
another. Many devices are qualified as input and output units for computer systems.
1. Input Unit
The input unit begins the computation process where the user interaction is involved. This
component is responsible for capturing the input from the user to command or instruct the
other components of the computer. This process gives a lead to the computer and lets the
next component decide how to brew up results for the input. There are multiple input devices
available for this activity, depending on the type of input required for specific tasks.
The following are some of the commonly used input devices for carrying out the activities of
the input unit are,
• Keyboard: Keyboard device, as the name says, comprises a bunch of keys that are
used to type the instructions and input commands on the computer system. This
device acts as an entity that lets the system to record the input provided by the user,
and the typical format used to build this type of device is the QWERTY format, along
with other functional keys like F1 to F12 ALT, CTRL, Shift, etc. keys.
• Mouse: The mouse is another commonly used input device for pointing and clicking,
which comes with a scroll wheel for scrolling through the display and a couple of
buttons for selection purposes.
• Joystick: Joystick is an input device used to send out commands for the gaming
processes carried out in the computer system. It is made up of multiple control
buttons and at least one lever control, hence, given the name ‘Joystick’.
• Touch Screen: Touch Screens are the latest advancement for sending input to
computing devices, where the user just has to use sensible touch screens to instruct
the computer. The touch-action can be performed by a dedicated pen-like device
called ‘Stylus’ or even by using the user’s fingertips.
Memory Unit: This Unit is used for numerous purposes like storing the data received from
diverse input devices, providing the necessary space for handling the computational
activities, caching the previous calculations, reserving space for upcoming activities,
buffering the temporary information, etc.
Control Unit:
The control unit is a part of the Central Processing Unit (CPU). The CPU is divided into the
arithmetic logic unit and the control unit. The control unit generates the appropriate timing
and control signals to all the operations involved with a computer. The flow of data between
the processor, memory, and other peripherals is controlled using the timing signals of the
control unit.
The main function of a control unit is to fetch the data from the main memory, determine the
devices and the operations involved with it, and produce control signals to execute the
operations.
The functions of the control unit are as follows −
• It helps the computer system in the process of carrying out the stored program instructions.
• It interacts with both the main memory and arithmetic logic unit.
• It performs arithmetic or logical operations.
• It coordinates with all the activities related to the other units and the peripherals.
Arithmetic & Logical Unit (ALU)
In the computer system, ALU is a main component of the central processing unit,
which stands for arithmetic logic unit and performs arithmetic and logic operations. It
is also known as an integer unit (IU) , which is the last component to perform
calculations in the processor.
It has the ability to perform all processes related to arithmetic and logic operations
such as addition, subtraction, and shifting operations, including Boolean comparisons
(XOR, OR, AND, and NOT operations).
Also, binary numbers can accomplish mathematical and bitwise operations. The
arithmetic logic unit is split into AU (arithmetic unit) and LU (logic unit). The operands
and code used by the ALU tell it which operations have to perform according to input
data. When the ALU completes the processing of input, the information is sent to the
computer's memory.
o Logical Operations: The logical operations consist of NOR, NOT, AND, NAND, OR,
XOR, and more.
o Bit-Shifting Operations: It is responsible for displacement in the locations of the bits
to the by right or left by a certain number of places that are known as a multiplication
operation.
o Arithmetic Operations: Although it performs multiplication and division, this refers to
bit addition and subtraction. But multiplication and division operations are more costly
to make. In the place of multiplication, addition can be used as a substitute and
subtraction for division.
3. Output Unit
The Output Unit, similar to the input unit, is designed only for the sole purpose of interacting
with the computer system user. It is usually used to give the processed results to the user
based on the input provided. The devices that handle the output processing should be
capable of delivering any type of data or a combination of data types on their display units,
including text, numbers, images, audio, video, gifs, etc.
• Monitors: The computer monitors are responsible for displaying the results received
after processing and completing all the operations in the central processing unit. The
technology in designing the display devices has evolved from monochrome monitors
to colored monitors to the latest LED/LCDs.
• Printers: Printers are another output device, similar to monitors, but the difference is
that the output data received are produced into hard copies. The performance
standards of the printer device are qualified based on the processing speed, the
printing resolution, the processing memory capacity, printing color feature, etc.
• Speaker: Speakers are used for obtaining the audio formatted output data, which
comes with various extensions like.MP3, MPEG, .WMA, etc. This device aids in
sending out audible alerts to the user, accessing the data with music or audio,
communication systems, etc.
Registers
Registers are a type of computer memory used to quickly accept, store, and transfer data
and instructions that are being used immediately by the CPU. The registers used by the CPU
are often termed as Processor registers.
A processor register may hold an instruction, a storage address, or any data (such as bit sequence or
individual characters).
The sole purpose of having register is fast retrieval of data for processing by CPU. Though
accessing instructions from RAM is comparatively faster with hard drive, it still isn’t enough
for CPU. For even better processing, there are memories in CPU which can get data from
RAM which are about to be executed beforehand. After registers we have cache memory,
which are faster but less faster than registers.
• Accumulator:
This is the most frequently used register used to store data taken from memory. It is in
different numbers in different microprocessors.
Memory unit is the amount of data that can be stored in the storage unit. This storage capacity
is expressed in terms of Bytes.
The following table explains the main memory storage units −
[Link]. Unit & Description
Nibble
2
A group of 4 bits is called nibble.
Byte
3 A group of 8 bits is called byte. A byte is the smallest unit, which can represent a
data item or a character.
4 Word
Kilobyte (KB)
1
1 KB = 1024 Bytes
Megabyte (MB)
2
1 MB = 1024 KB
GigaByte (GB)
3
1 GB = 1024 MB
TeraByte (TB)
4
1 TB = 1024 GB
PetaByte (PB)
5
1 PB = 1024 TB
MAIN MEMORY
The main memory in a computer is called Random Access Memory. It is also known as
RAM. This is the part of the computer that stores operating system software, software
applications and other information for the central processing unit (CPU) to have fast and
direct access when needed to perform tasks. It is called "random access" because the CPU
can go directly to any section of main memory, and does not have go about the process in a
sequential order.
RAM is one of the faster types of memory, and has the capacity to allow data to be read
and written. When the computer is shut down, all of the content held in RAM is purged.
Main memory is available in two types: Dynamic Random Access Memory (DRAM) and
Static Random Access Memory (SRAM).
DRAM
Dynamic random access memory (DRAM) is the most common kind of main memory in a
computer. It is a prevalent memory source in PCs, as well as workstations. Dynamic
random access memory is constantly restoring whatever information is being held in
memory. It refreshes the data by sending millions of pulses per second to the memory
storage cell.
SRAM
Static Random Access Memory (SRAM) is the second type of main memory in a computer.
It is commonly used as a source of memory in embedded devices. Data held in SRAM does
not have to be continually refreshed; information in this main memory remains as a "static
image" until it is overwritten or is deleted when the power is switched off. Since SRAM is
less dense and more power-efficient when it is not in use; therefore, it is a better choice
than DRAM for certain uses like memory caches located in CPUs. Conversely, DRAM's
density makes it a better choice for main memory.
CACHE MEMORY
Cache memory is used to reduce the average time to access data from the Main memory.
The cache is a smaller and faster memory that stores copies of the data from frequently
used main memory locations. There are various different independent caches in a CPU,
which store instructions and data.
The basic operation of a cache memory is as follows:
o When the CPU needs to access memory, the cache is examined. If the word is found in
the cache, it is read from the fast memory. o If the word addressed by the CPU is not
found in the cache, the main memory is accessed to read the word.
o A block of words one just accessed is then transferred from main memory to cache
memory. The block size may vary from one word (the one just accessed) to about 16
words adjacent to the one just accessed.
o The performance of the cache memory is frequently measured in terms of a quantity
called hit ratio.
o When the CPU refers to memory and finds the word in cache, it is said to produce a hit.
o If the word is not found in the cache, it is in main memory and it counts as a miss.
o The ratio of the number of hits divided by the total CPU references to memory (hits plus
misses) is the hit ratio.
Levels of memory:
• Level 1 or Register – It is a type of memory in which data is stored and accepted that
are immediately stored in CPU. Most commonly used register is accumulator, Program
counter, address register etc.
• Level 2 or Cache memory – It is the fastest memory which has faster access time
where data is temporarily stored for faster access.
• Level 3 or Main Memory – It is memory on which computer works currently. It is small
in size and once power is off data no longer stays in this memory.
• Level 4 or Secondary Memory – It is external memory which is not as fast as main
memory but data stays permanently in this memory.
SYSTEM BUS
A bus is a set of wires. The elements of the computer are linked to the buses. It can
transfer data from one element to another, the source element outputs data onto
the bus. The destination element then inputs this information from the bus.
Data is shared via the data bus. When the CPU fetches information from memory, it first
outputs the memory address on its address bus. Therefore memory outputs the data onto
the data bus, the CPU can read the information from the data bus. When writing data to
memory, the CPU first outputs the address onto the address bus, therefore outputs the data
onto the data bus.
The control bus is different from the other two buses. The address bus includes n lines,
which associate to transit one n-bit address value. The lines of the data bus work
simultaneously to send a single, multi-bit value.
SMPS stands for Switched-Mode Power Supply. It is an electronic power supply that uses a
switching regulator to convert electrical power efficiently. It is also known as Switching Mode
Power Supply. It is power supply unit (PSU) generally used in computers to convert the
voltage into the computer acceptable range.
This device has the power handling electronic components that converts electrical power
efficiently. Switched Mode Power Supply uses a great power conversion technique to reduce
overall power loss.
Advantages
• The switch mode power supply encompasses a smaller in size.
• The switch mode power supply has light weight.
• It includes a way better power effectiveness ordinarily 60 to 70 percent.
• It features a solid against interference.
• SMPS has wide yield range.
Disadvantages
• The switch mode power supply is complex.
• The SMPS has higher yield swell and its control is worse.
• It can be utilized as it were as a step down regulator.
• It has as it were one output voltage.
• SMPS moreover cause harmonic distortion.
• The main use of BIOS is to act as a middleman between OSes and the
hardware they run on. BIOS is theoretically always the intermediary between
the microprocessor and I/O device control information and data flow.
• The main function of BIOS is to set up hardware and start an OS, and it contains
generic code that is needed to control display screens, the keyboard, and other
functions.
• The BIOS is built-in software that manages the hard drives and cannot live on
one. It cannot reside in the RAM (Random Access Memory) as it is accessible
before the computer system boots up.
• Actually, it lives on the ROM of the computer system, and mainly it is located
on EPROM (erasable programmable read-only memory) chip.
CMOS is an integrated circuit designed on a printed circuit board (PCB), widely used type of
semiconductor used in transistors.
It is a battery powered memory chip that simply stores the startup information and BIOS uses this
information to turn on your computer i.e. during the boot up process.
Complementary term refers to the charged used which is either positive (PMOS) or negative (NMOS).
CMOS uses only one charge at a time. Due to this, CMOS consumes less power because
charges can stay in one state for a longer period of time and hence consume energy only
when needed.
CMOS based transistors do not heat up and gives a high speed. CMOS batteries are made up
of Lithium material that can last upto 10 years
Usage o
Microprocessors, o
A storage device is a kind of hardware, which is also known as storage, storage medium,
digital storage, or storage media that has the ability to store information either temporarily or
permanently
Two types of storage devices, primary and secondary are available there to store data.
Primary storage devices: They are fit internally to the computer and very fast in terms of
accessing data files. The RAM and cache memory are the examples of the primary storage
devices.
(i) RAM: It stands for Random Access Memory. It is used to store information that
is used immediately or we can say that it is a temporary memory. Computers
bring the software installed on a hard disk to RAM to process it and to be
used by the user. Once, the computer is turned off, the data is deleted.
• SRAM: It stands for Static Random Access Memory. It consists of circuits that retain
stored information as long as the power supply is on. It is also known as volatile
memory. It is used to build Cache memory. The access time of SRAM is lower and it
is much faster as compared to DRAM but in terms of cost, it is costly as compared to
DRAM.
• DRAM: It stands for Dynamic Random Access Memory. It is used to stores binary bits
in the form of electrical charges that are applied to capacitors. The access time of
DRAM is slower as compare to SRAM but it is cheaper than SRAM and has a high
packaging density.
• SDRAM: It stands for Synchronous Dynamic Random Access Memory. It is faster
than DRAM. It is widely used in computers and others
(ii) ROM: It stands for Read-Only Memory. The data written or stored in these devices are
non-volatile, i.e, once the data is stored in the memory cannot be modified or deleted. The
memory from which will only read but cannot write it. This type of memory is non-volatile. The
information is stored permanently during manufacture only once. ROM stores instructions
that are used to start a computer. There are two types of ROM:
• PROM: PROM is Programmable Read-Only Memory. These are ROMs that can be
programmed. A special PROM programmer is employed to enter the program on the
PROM. Once the chip has been programmed, information on the PROM can’t be altered.
PROM is non-volatile, that is data is not lost when power is switched off.
• EPROM: Another sort of memory is that the Erasable Programmable Read-Only Memory.
It is possible to erase the info which has been previously stored on an EPROM and write
new data onto the chip.
The hard disk, USB storage devices and optical disk drive are examples of secondary storage
devices, which are designed to store data permanently. They include a large storage capacity
while comparing with primary storage devices.
o Floppy diskette: A floppy disk drive (FDD) offers users the benefit of saving data to
removable diskettes. FDDs have been replaced with other storage devices like
network file transfer and USB.
o Hard drive: A hard disk drive (HDD) is used to store data permanently as it is a
nonvolatile computer storage device, and directly connected to the disk controller of
the computer's motherboard. Usually, it is installed internally in a computer, known as
secondary storage device.
o Magnetic Card: A magnetic card is a card that may have information about an
individual, such as passcodes to enter secure buildings or available recognition on a
credit card.
o SuperDisk: Imation Corporation developed the disk storage technology. SuperDisk is
also known as a LS-240 and LS-120.
o Tape cassette: A tape is a rectangular and flat container that is capable of storing
data. As compared to other storage media, it is less expensive and commonly used
for backing up a huge amount of data.
o Zip diskette: A Zip drive is a hardware data storage device that is an advanced
version of the floppy disk.
o Blu-ray disc o CD-ROM disc o CD-R and CD-RW disc. o DVD-R, DVD+RW, DVD+R,
and DVD-RW disc.
o Flash drive: A USB flash drive is a portable storage device used for data storage that
is also known as pen drive, thumb drive, data stick, keychain drive. They are
connected to a computer via a USB port and often the size of a human thumb.
o Memory card: A memory card is commonly used in digital cameras, printers, MP3
players, PDAs, digital camcorders, game consoles, and handheld computers. The
most common memory card format was CompactFlash for many years, but today are
CFexpress, SD, MicroSD, and XQD.
o Compact Flash (CF): Compact Flash is a type of flash memory that is commonly
found in digital cameras, PDAs and other portable devices. It is a 50-pin connection
storage device that is capable of storing data ranging from 2 MB to 128 GB.
VIRTUAL MEMORY
Virtual Memory is a storage scheme that provides user an illusion of having a very big main memory.
This is done by treating a part of secondary memory as the main memory.
In this scheme, User can load the bigger size processes than the available main memory by having
the illusion that the memory is available to load the process.
Instead of loading one big process in the main memory, the Operating System loads the different parts
of more than one process in the main memory.
By doing this, the degree of multiprogramming will be increased and therefore, the CPU utilization will
also be increased.
MODULE 2
Program
Programming
• Programming is a way to “instruct the computer to perform various tasks”. • “Instruct the
computer” means that you provide the computer a set of instructions that are written in a
language that the computer can understand. The instructions could be of various types.
• There are many programming languages -- C, C++, Pascal, BASIC, FORTRAN, COBOL,
and LISP are just a few.
Definition of Algorithm
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum=num1+num2
Step 6: Stop
Definition of Flowchart
C Programming
Source Code
• Source code is the set of instructions and statements written by a programmer using a
computer programming language.
• This code is later translated into machine language by a compiler. The translated code
is referred to as object code
• Programmers can use a text editor, a visual programming tool or an integrated
development environment to create source code.
Example:
#include <stdio.h>
#include<conio.h>
void main()
{
printf("Hello, World! \n");
getch();
}
Output:
Hello, World!
Object Code
• Object code is usually produced by a compiler that reads some higher level
computer language source instructions and translates them into equivalent machine
language instructions
• A compiler translates source code into object code, which is stored in object files.
Object files contain object code that includes instructions to be executed by the
computer.
Executable File
• Executable file is the result of object file, saved with .exe file extension in case of C
.It is the machine code that actually interacts with the machine.
• In case of a normal C program with a single file, save the program with any name
but, with .c extension and press (Compile ) F9. It will generate and save an
executable file in the output folder
Compilers
A compiler takes the entire source code at once for compiling (generates errors if any), and
then generates the machine language code.
Interpreters
An interpreter decodes each line of source code to machine language. If any errors occur while
interpreting the code, immediately the error is thrown
Compiler Interpreter
[Link] code is given as input. Instruction by instruction is given as input.
[Link] the object code. Does not generate the object code.
Variables
• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout
of the variable. They are also known as identifiers
• The name of a variable can be composed of letters, digits, and the underscore
character.
Variable declarations
This is the process of allocating sufficient memory space for the data in term of variable.
Constant
It is an identifier whose value can not be changed at the execution time of program. In
general constant can be used to represent as fixed values in a C program. Constants are
classified into following types.
Data types in C
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.
These data types have different storage
capacities. C language supports 2 different type of
data types:
[Link] Data Types
2. Derived Data Types
• Integers are whole numbers that can have both zero, positive and negative values
but no decimal values. For example, 0, -5, 10
• We can use int for declaring an integer variable. int id;
Here, id is a variable of type integer.
• You can declare multiple variables at once in C programming. For example, int id,
age;
2. float
• float and double are used to hold real numbers. • The size of float data types id 4
Bytes float salary;
[Link]
• It is used to manage character type values such as 0-9 and a-z . • Keyword char
is used for declaring character type variables
• The size of the character variable is 1 byte.
• void is an incomplete type. It means "nothing" or "no type". You can think of void
as absent.
• For example, if a function is not returning anything, its return type should be void.
• Note that, you cannot create variables of void type.
Operators
• Operators are the foundation of any programming language.
• Thus the functionality of C programming language is incomplete without the use of
operators.
• We can define operators as symbols that helps us to perform specific mathematical
and logical computations on operands.
For example, consider the below statement:
c = a + b;
Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands.
1. Arithmetic Operators 2.
Logical Operators
3. Relational Operators
4. Assignment Operators
5. Misc operator
6. Comma Operator 7. Conditional Operator
[Link] Operators:
These are the operators used to perform arithmetic/mathematical operations on
operands.
Examples: (+, -, *, /, %,++,--).
Operator Example
Description
% B%A=0
Modulus Operator and remainder of after an integer
division.
-- A-- = 9
Decrement operator decreases the integer value by
one.
&& Called Logical AND operator. If both the operands are (A && B) is
non-zero, then the condition becomes true. false.
! !(A && B) is
Called Logical NOT Operator. It is used to reverse the
true.
logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.
Operator Description
Example
!= (A != B) is true.
Checks if the values of two operands are equal or not. If
the values are not equal, then the condition becomes
true.
> (A > B) is not
Checks if the value of left operand is greater than the value true.
of right operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand. If yes, then the condition becomes true.
+= C += A is equivalent to C = C
Add AND assignment operator. It adds the
+A
right operand to the left operand and assign
the result to the left operand.
-= C -= A is equivalent to C = C
Subtract AND assignment operator. It -A
subtracts the right operand from the left
operand and assigns the result to the left
operand.
*= C *= A is equivalent to C = C
Multiply AND assignment operator. It *A
multiplies the right operand with the left
operand and assigns the result to the left
operand.
/= Divide AND assignment operator. It divides C /= A is equivalent to C = C /
the left operand with the right operand and A
assigns the result to the left operand.
%= C %= A is equivalent to C = C
Modulus AND assignment operator. It takes
%A
modulus using two operands and assigns
the result to the left operand.
[Link] Operators:
Returns the size of a variable.
Example:
Int a;
sizeof(a); where a is
integer, will return 4.
[Link] Operator
It is used to separate two or more variables and statements Example
:
[Link] Operator:
It check a condition and perform the action based on the validity of the condition Syntax:
Condition ? statement1 : statement2; Example
Operators Precedence in C
• Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has a higher
precedence than the addition operator.
• For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
a higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.
i) printf()
This function is used for displaying the output on the screen i.e the data is moved from
the computer memory to the output device.
Syntax1:
printf(“format string”, arg1, arg2, …..);
• In the above syntax, 'format string' specify the type od data inarg1,arg2
• arg1, arg2 are variables.
Syntax2:
printf(“Message”);
• this printf will print the message inside the double inverted comma ii)
scanf works totally opposite to printf. The input is read, interpret using the
conversion specifier and stores it in the given variable. The conversion specifier
for scanf is the same as printf.
scanf reads the characters from the input as long as the characters match or it will
terminate. The order of the characters that are entered are not important. It
requires an enter key in order to accept an input.
iii) getch
This function is used to input a single character. The character is read instantly and
it does not require an enter key to be pressed. The character type is returned but
it does not echo on the screen.
iv) putch this function is a counterpart of getch. Which means that it will display a
single character on the screen. The character that is displayed is returned.
Syntax: int
putch(int);
putch(ch);
v) getche
This function is used to input a single character. The main difference between
getch and getche is that getche displays the (echoes) the character that we type
on the screen.
Syntax: int
getch(void); ch=getche();
vi) getchar
This function is used to input a single character. The enter key is pressed which is
followed by the character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar;
vii) putchar
This function is the other side of getchar. A single character is displayed on the
screen.
Syntax:
putchar(ch);
Example:
#include
<stdio.h> void
main()
{
char line[30];
gets (line);
puts (line);
}
MODULE 3
Control structures in C
Control structures form the basic entities of a “structured programming language“. Control
structures are used to alter the flow of execution of the program. There are three types
of control structures available in C
1. Switch
2. If
3. If Else
4. While
5. Do While
6. For
1. If statement
if(expression)
{
statement
}
The expression given inside the brackets after if is evaluated first. If the expression is
true, then statements inside the curly braces that follow if(expression) will be executed. If
the expression is false, the statements inside curly braces will not be executed and
program control goes directly to statements after curly braces.
Example program to demo “If” statement
Int num;
if(num==1)
{
printf("ONE");
}
if(expression)
{
Statement1;
}
else
{
Statement2;
}
The execution begins by evaluation expression. If it is TRUE, then statement1 inside the
immediate curly braces is evaluated. If it is FALSE, program control is transferred directly
to immediate else block and statement2 is executed.
#include void
main()
{
int num;
printf("Hello user, Enter a number");
scanf("%d",&num);
if(num>0)
{
printf("The number is Positive");
}
else
{
printf("The Number is negative");
}
getch();
}
[Link] statement
Switch is a multi branching control statement. Syntax for switch statement is shown
below. Switch(expression)
{
Case value1:
Statement1;
Break Case
value2:
Statement2;
Break
…..
Case value n: Statement
n;
Break Default:
Statement;
break
}
Execution of switch statement begins by evaluating the expression inside the switch
keyword brackets. The expression should be an integer (1, 2, 100, 57 etc ) or a character
constant like ‘a’, ‘b’ etc.
This expression’s value is then matched with each case values. There can be any number
of case values inside a switch statements block. If first case value is not matched with the
expression value, program control moves to next case value and so on. When a case
value matches with expression value, the statements that belong to a particular
case value are executed.
#include
void main()
{
int num;
printf("Hello user, Enter a number");
scanf("%d",&num); switch(num)
{
case 1:
printf("OME")
; break; case
2:
printf("TWO")
; break; case
3:
printf("THRE
E");
default:
printf("WRONG ENTRY");
}
}
II .Loop structures
• A loop structure is used to execute a certain set of actions for a predefined number
of times or until a particular condition is satisfied.
[Link] statement
{
statement 1; statement
2;
statement 3;
}
The condition is checked for TRUE first. If it is TRUE then all statements inside curly
braces are [Link] program control comes back to check the condition has
Muslim Association college of Arts and Science Page 36
S1 [Link] Computer Science CS1141: Introduction to Programming
changed or to check if it is still TRUE. The statements inside braces are executed
repeatedly, as long as the condition is TRUE. When the condition turns FALSE, program
control exits from while loop.
An example program to collect a number from user and then print all numbers from zero
to that particular collected number is shown below. That is, if user enters 10 as input, then
numbers from 0 to 10 will be printed on screen.
Note:- The same problem is used to develop programs for do while and for loops
i=0;
while(i<=10)
{
Printf(“%d”,i)
}
i=0; do
{
Printf(“%d”,i)
}
while(i<=10);
[Link] statement
for(initialization;condition;iteration)
{
statement statement
statement
}
The for statement is an entry controlled loop. The difference between while and for is in
the number of repetitions. The for loop is used when an action is to be executed for a
predefined number of times. The while loop is used when the number of repetitions is not
predefined.
The program control enters the for loop. At first it execute the statements given as
initialization statements. Then the condition statement is evaluated. If conditions are
TRUE, then the block of statements inside curly braces is executed. After executing
curly brace statements fully, the control moves to the "iteration" statements. After
executing iteration statements, control comes back to condition statements. Condition
statements are evaluated again for TRUE or FALSE. If TRUE the curly brace statements
are executed. This process continues until the condition turns FALSE.
for(i=0;i<=10;i++)
{
printf(“%d”,i)
}
Arrays
• Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type.
• An array is used to store a collection of data
• All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Declaring Arrays
• To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
• This is called a single-dimensional array. The arraySize must be an integer
constant greater than zero and type can be any valid C data type.
• For example, to declare a 10-element array called a of type int, use this statement
− int a[10];
• Here a is a variable array which is sufficient to hold up to 10 intiger numbers.
Initializing Arrays
• You can initialize an array in C either one by one or using a single statement as
follows
• int balance[5] = {6, 2, 3, 7, 50};
• The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
• An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For
example −
• int x = a[9];
• The above statement will take the 10th element from the array and assign the value
to the variable a
Input elements to the array
for(i=0;i<size;i++)
{
scanf(“%d”,&a[i]);
}
Two-dimensional Arrays
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.
Input elements to the 2D array
for(i=0;i<row;i++)
{
for(i=0;i<Colum ;i++)
{
scanf(“%d”,&a[i][j]);
}
}
Print elements from the array for(i=0;i<row;i++)
{
for(i=0;i<Colum ;i++)
{
printf(“%d”,a[i][j]);
}
}
Functions
• A function is a group of statements that together perform a task.
• Every C program has at least one function, which is main(), and all the most
programs can define additional functions.
• A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
• The C standard library provides numerous built-in functions that your program can
call. For example-getch(),printf(),scanf()
Function Declarations
• A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately. • A
function declaration has the following parts − return_type function_name(
parameter list );
• For the above defined function sum(), the function declaration is as follows int
sum(int , int );
Defining a Function
without returning a value. In this case, the return_type is the keyword void. •
Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function.
Parameters are optional; that is, a function may contain no parameters. •
Function Body − The function body contains a collection of statements that define
what the function does.
Example of function
Given below is the source code for a function called sum(). This function takes two
parameters a and b and print sum
void sum(int a, int b)
{ int
s;
s=a+b; printf(“Sum
is %d”,s);
}
Calling a Function
To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value or print it
Sum(10,20);
Sum(3,8);
#include <stdio.h>
int main () {
int a = 100;
int b = 200;
swap(a, b);
return 0;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y; y
= temp;
Output
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
2. Call by Reference
The call by reference method of passing arguments to a function copies the address of
an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in the call. It
means the changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any
other value. So accordingly you need to declare the function parameters as pointer types
as in the following function swap(), which exchanges the values of the two integer
variables pointed to, by their arguments.
#include <stdio.h>
void main () {
int a = 100;
int b = 200;
swap(&a, &b);
int temp;
temp = *x;
*x = *y;
*y = temp;
Output
Pointers
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. Like any variable or constant, you must declare a pointer before
using it to store any variable address. The general form of a pointer variable declaration
is −
type *var-name; example: int *p;
#include <stdio.h>
void main () {
int a = 20;
int *p;
p=&a;
printf("Address of a: %x\n", &a );
getch();
}
Output:
Address of a: 1010111
Address stored in p: 1010111
Value of *p: 20
MODULE 4
ADVANCED FEATURES
Dynamic Memory Allocation
Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
There are 4 library functions provided by C defined under <stdlib.h> header file to
facilitate dynamic memory allocation in C programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
[Link]()
For Example:
[Link]()
For Example:
[Link]()
“free” method is used to dynamically de-allocate the memory. The memory allocated
using functions malloc() and calloc() are not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to
reduce wastage of memory by freeing it.
Syntax:
free(ptr);
[Link]()
Storage Class
• Storage class in C decides the part of storage to allocate memory for a variable, it
also determines the scope of a variable.
• The storage class of a variable in C determines the life time of the variable if this
is 'global' or 'local'. There are four storage class specifiers in C as follows, typedef
specifier does not reserve storage and is called a storage class specifier only for
syntactic convenience. It is not a storage class specifier in the common meaning.
1. auto
2. register
3. extern
4. static
5. typedef
•
Static int i=20;
• Extern stands for external storage class. Extern storage class is used when we
have global functions or variables which are shared between two or more files.
• Keyword extern is used to declaring a global variable or function in another file to
provide the reference of variable or function which have been already defined in the
original file.
• The variables defined using an extern keyword are called as global variables.
These variables are accessible throughout the program. Notice that the extern
variable cannot be initialized it has already been defined in the original file
Example,
extern int s;
Int sum2(int a,int b)
{
S=a+b;
}
Int sum3(int a,int b,int c)
{
s=a+b+c;
}
Here the variable s is used by two functions sum2() and sum3() with different purposes
typedef keyword is used to assign a new name to a type. This is used just to prevent us
from writing more.
For example, if we want to declare some variables of type macas, we have to write
“int macas” in a program. So, we can assign a new name of our choice for int using
In C programming, array exhibits a special behaviour. Whenever you refer an array name
directly, is behaves a pointer pointing at zeroth array element. Which means both of the
below statements are equivalent.
Array elements are stored sequentially in memory. Below is the memory representation
of array int arr[] = {10, 20, 30, 40, 50};
In the above image first array element i.e. arr[0] is allocated at memory 0x1000. For the above
case I have assumed integer size as 4 bytes. Hence, next array element i.e. arr[1] will get
memory at 0x1004 and so on fifth array element is allocated at 0x1016.
Since array elements are stored sequentially, hence you can easily apply pointer
arithmetic to iterate though elements. You can use following pointer arithmetic operations
to access array elements.
Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make
one integer array of pointers that can point to all the values.
“Array of pointers” is a colloction of the pointer variables and it stores memory address of
another array. It is also known as pointer arrays.
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try
to print the above mentioned string −
Live Demo
#include <stdio.h>
int main () {
When the above code is compiled and executed, it produces the following result −
Greeting message:
Hello
[Link].
strcpy(s1, s2);
Copies string s2 into string s1.
Example :s1=”hai” s2=”Welcome”
Strcpy(s1,s2) will change value of s1 as Welcome
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
Example :s1=”hai” s2=”Welcome”
Strcat(s1,s2) will return the string as “Hai Welcome”
3
strlen(s1);
Returns the length of string s1.
Example: s1=”hai”;
int l=strlen(s1) return the value 3
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
Example:
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
Example:
S1=”I love India”
S2=”love”;
Strtchr(s1,s2); returns the value 8
C Structures
Structure is a user-defined datatype in C language which allows us to combine data of
different types together.
It is somewhat similar to an Array, but an array holds data of similar type only. But structure
on the other hand, can store data of any type,
For example: If I have to write a program to store Student information, which will have
Student's name, age, branch, permanent address, father's name etc, which included
string values, integer values etc, how can I use arrays for this problem,
Defining a structure struct keyword is used to define a structure. struct defines a new
data type which is a collection of primary and derived datatypes.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional
to provide your structure a name, we suggest you to give it a name, then inside the
curly braces, we have to mention all the member variables, which are nothing but
normal C language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is
optional.
Note: The closing curly brace in the structure type declaration must be followed by a
semicolon(;).
struct Student
{ char name[25]; int age;
char branch[10]; //F for
female and M for male char
gender;
};
int main()
{
struct Student s1;
Student
*/
[Link] = 18;
/*
using string function to add name
*/
strcpy([Link], "Viraaj");
/* displaying the stored
values
*/
printf("Name of Student 1: %s\n", [Link]); printf("Age
of Student 1: %d\n", [Link]);
return 0;
}
Array of Structure
We can also declare an array of structure variables. in which each element of the array
will represent a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of
type Employee.
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
Nested Structures
Nesting of structures, is also permitted in C language. Nested structures means, that one
structure has another stucture as member variable.
Example: struct
Student
{
char[30] name;
int age;
/* here Address is a structure
*/ struct Address
{ char[50]
locality; char[50]
city; int pincode;
}addr;
};
Union in C
Like Structures, union is a user defined data type. In union, all members share the same
3. char
4. name[50];
5. } int
6. price;
7. ;
8. {
9. int
10. main()
11.
} union car car1, car2,
*car3;
return
0;
File Input/Output in C
A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data.
C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following
are the functions,
Function description
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
printf("Enter data...");
while( (ch = getchar()) !=
EOF) { putc(ch, fp);
}
fclose(fp); op
fp = fopen("[Link]", "r");
• fseek(): It is used to move the reading control to different positions using fseek
function.
• ftell(): It tells the byte location of current position of cursor in file pointer.
• rewind(): It moves the control to beginning of the file.