0% found this document useful (0 votes)
7 views64 pages

C Programming

The document outlines the syllabus for the CS1141: Introduction to Programming course at Muslim Association College of Arts and Science, covering computer fundamentals and programming in C. It includes modules on computer components, C programming basics, control structures, functions, pointers, and advanced features like dynamic memory allocation and file handling. The document also details the architecture of computer systems, including input/output units, CPU components, memory types, and storage units.

Uploaded by

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

C Programming

The document outlines the syllabus for the CS1141: Introduction to Programming course at Muslim Association College of Arts and Science, covering computer fundamentals and programming in C. It includes modules on computer components, C programming basics, control structures, functions, pointers, and advanced features like dynamic memory allocation and file handling. The document also details the architecture of computer systems, including input/output units, CPU components, memory types, and storage units.

Uploaded by

sairarasool024
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

S1 B.

Sc Computer Science CS1141: Introduction to Programming

MUSLIM ASSOCIATION COLLEGE OF ARTS AND SCIENCE

Panavoor,Thiruvananthapuram,Kerala

(Affiliated to the University of Kerala)

Department of Computer Science

CS1121 :COMPUTER FUNDAMENTALS AND PROGRAMMING IN C

Name : ……………………………………………………………………………………………

Candidate Code: ……………………………………………………………………………..

Muslim Association college of Arts and Science Page 1


S1 [Link] Computer Science CS1141: Introduction to Programming

CS1141: INTRODUCTION TO PROGRAMMING

SYLLABUS

COURSE CONTENT

Module I: Components & Characteristics of Computer: CPU, ALU,


Registers, Control Unit, System Bus, Main memory unit, Cache memory Inside
a computer: Power supply (SMPS), Motherboard, BIOS, CMOS, Ports and
Interfaces, expansion cards, memory chips, storage devices, processors, CPU
Registers, Cache Memory, Operations in Cache memory, hit ratio, Virtual
memory.

Module II: Introduction to C programming: Algorithm & Flow charts:


Definitions, Symbols used to draw flowcharts, Program Writing – Structure of
the Program, Source code, Object code, Executable file, Variables and
Constants, Rules for naming the Variables/Identifiers; Basic data types of C, int,
char, float, double; storage capacity – range of all the data types; Basic
Elements: Operators and Expressions: Expression Evaluation (Precedence of
Operators); simple I/O statements.

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 IV: Advanced features: Concept dynamic memory allocation. Storage


classes, Array & pointer relationship, pointer to arrays, array of pointers. Strings: String
handling functions; Structures and unions; File handling: text and binary files, file
operations, Functions for file handling, Modes of files.

Muslim Association college of Arts and Science Page 2


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Muslim Association college of Arts and Science Page 3


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

2. Central Processing Unit


The Central Processing Unit, commonly referred to as the CPU, is generally used for
fetching input data or instructions from input units and converting the unprocessed input
data into a machine-readable format, making it easy for the computer to carry out the
processing activities. It is made of three different units: the Memory Unit, the Control Unit,
and the Arithmetic & Logical Unit.

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.

Muslim Association college of Arts and Science Page 4


S1 [Link] Computer Science CS1141: Introduction to Programming

• 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.

The operations performed by ALU are:

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.

Muslim Association college of Arts and Science Page 5


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Here are the few commonly used output devices,

• 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.

Muslim Association college of Arts and Science Page 6


S1 [Link] Computer Science CS1141: Introduction to Programming

These are classified as given below.

• Accumulator:
This is the most frequently used register used to store data taken from memory. It is in
different numbers in different microprocessors.

• Memory Address Registers (MAR):


It holds the address of the location to be accessed from memory. MAR and MDR
(Memory Data Register) together facilitate the communication of the CPU and the main
memory.

• Memory Data Registers (MDR):


It contains data to be written into or to be read out from the addressed location.

• General Purpose Registers:


These are numbered as R0, R1, R2….Rn-1, and used to store temporary data during
any ongoing operation. Its content can be accessed by assembly programming. Modern
CPU architectures tends to use more GPR so that register-to-register addressing can
be used more, which is comparatively faster than other addressing modes.

• Program Counter (PC):


Program Counter (PC) is used to keep the track of execution of the program. It contains
the memory address of the next instruction to be fetched. PC points to the address of
the next instruction to be fetched from the main memory when the previous instruction
has been successfully completed. Program Counter (PC) also functions to count the
number of instructions. The incrementation of PC depends on the type of architecture
being used. If we are using 32-bit architecture, the PC gets incremented by 4 every time
to fetch the next instruction.

Muslim Association college of Arts and Science Page 7


S1 [Link] Computer Science CS1141: Introduction to Programming

• Instruction Register (IR):


The IR holds the instruction which is just about to be executed. The instruction from PC
is fetched and stored in IR. As soon as the instruction in placed in IR, the CPU starts
executing the instruction and the PC points to the next instruction to be executed.

• Condition code register ( CCR ) :


Condition code registers contain different flags that indicate the status of any
[Link] instance lets suppose an operation caused creation of a negative result or
zero, then these flags are set high [Link] the flags are
1. Carry C: Set to 1 if an add operation produces a carry or a subtract operation produces
a borrow; otherwise cleared to 0.
2. Overflow V: Useful only during operations on signed integers.
3. Zero Z: Set to 1 if the result is 0, otherwise cleared to 0.
4. Negate N: Meaningful only in signed number operations. Set to 1 if a negative result is
produced.
5. Extend X: Functions as a carry for multiple precision arithmetic operations.

Main memory unit

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

Bit (Binary Digit)


1 A binary digit is logical 0 and 1 representing a passive or an active state of a
component in an electric circuit.

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.

Muslim Association college of Arts and Science Page 8


S1 [Link] Computer Science CS1141: Introduction to Programming

4 Word

A computer word, like a byte, is a group of fixed number of bits processed as a


unit, which varies from computer to computer but is fixed for each computer.
The length of a computer word is called word-size or word length. It may be as
small as 8 bits or may be as long as 96 bits. A computer stores the information in
the form of computer words.

The following table lists some higher storage units −


[Link]. Unit & Description

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

Muslim Association college of Arts and Science Page 9


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Muslim Association college of Arts and Science Page 10


S1 [Link] Computer Science CS1141: Introduction to Programming

CACHE MEMORY

Cache Memory is a special very high-speed memory. It is used to speed up and


synchronize with high-speed CPU. Cache memory is costlier than main memory or
disk memory but more economical than CPU registers. Cache memory is an
extremely fast memory type that acts as a buffer between RAM and the CPU

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.

Muslim Association college of Arts and Science Page 11


S1 [Link] Computer Science CS1141: Introduction to Programming

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: Switched-Mode Power Supply/ Switching Mode Power Supply

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.

Muslim Association college of Arts and Science Page 12


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

It is an electronic gadget or module that comprises a combination of inductors, capacitors


and semiconductor gadgets like diodes and MOSFETs(metal–oxide–semiconductor field-
effect transistor). It is utilized to change over a specific DC voltage to another DC voltage
level.

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.

BIOS (basic input/output system)


• BIOS (basic input/output system) is the program a
computer's microprocessor uses to start the computer system after it is
powered on.
• It also manages data flow between the computer's operating system (OS) and
attached devices, such as the hard disk, video adapter, keyboard, mouse and
printer.

• 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.

Muslim Association college of Arts and Science Page 13


S1 [Link] Computer Science CS1141: Introduction to Programming

The major functions of a Basic input/output system (BIOS)


• BIOS Power on Self-Test (POST); This tests the hardware of the computer
before loading the OS.
• BIOS drivers: This locates the software and drivers that interface with the OS
once running.
• Bootstrap Loader: This locates the OS
• BIOS Setup Utility Program

CMOS: Complementary Metal Oxide Semiconductor

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

Image sensors, o Static


RAM, o Microcontroller, o
Digital logic circuit etc

What is a storage device?

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.

Muslim Association college of Arts and Science Page 14


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Secondary storage devices:

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.

Muslim Association college of Arts and Science Page 15


S1 [Link] Computer Science CS1141: Introduction to Programming

Magnetic 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.

Optical storage devices

Another type of storage devices are given below:

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.

Flash memory devices

Flash memory is cheaper as well as portable.

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

Muslim Association college of Arts and Science Page 16


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Muslim Association college of Arts and Science Page 17


S1 [Link] Computer Science CS1141: Introduction to Programming

MODULE 2

Program

• A program is an organized list of instructions that tells the computer to behave in a


predetermined manner. Without programs, computers are useless.
• A program is like a recipe. It contains a list of ingredients (called variables) and a list of
directions (called statements) that tell the computer what to do with the variables.
• The variables can represent numeric data, text, or graphical images

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.

For example: Adding 2 numbers,

• There are many programming languages -- C, C++, Pascal, BASIC, FORTRAN, COBOL,
and LISP are just a few.

Definition of Algorithm

• Algorithm is logical step-by-step statements to solve the problem


• In other words, an algorithm is a procedure for solving problems. In order to solve a
mathematical or computer problem, this is the first step of the procedure.
• An algorithm includes calculations, reasoning and data processing. Algorithms can be
presented by natural languages, pseudo code and flowcharts, etc.
Example :

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Input values to num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum=num1+num2

Step 5: Display sum

Step 6: Stop

Muslim Association college of Arts and Science Page 18


S1 [Link] Computer Science CS1141: Introduction to Programming

Definition of Flowchart

• A flowchart is the graphical or pictorial representation of an algorithm with the help of

different symbols, shapes and arrows in order to demonstrate a process or a program.

• With flowchart, we can easily understand a program.

• The main purpose of a flowchart is to analyze different processes in aprogram

Several standard graphics are applied in a flowchart:

1. Terminal Box - Start / End

2. Input / Output : Used to represent input and output statements

3. Process / Instruction : Represents calculations and assignments

4. Decision : It check a condition and decide the flow of the program

5. Connector / Arrow : Used as a connector and show flow of control

C Programming

• C is a general-purpose programming language that is extremely popular, developed in


1972 by Dennis M. Ritchie at the Bell Telephone Laboratories

Muslim Association college of Arts and Science Page 19


S1 [Link] Computer Science CS1141: Introduction to Programming

• It is a structured programming language which is used extensively in various


applications.
• C was the basics language to write everything from operating systems (Windows and
many others) to complex programs like the Oracle database, Git, Python interpreter and
more
• It is said that 'C' is a god's programming language. If you know 'C,' you can easily grasp
the knowledge of the other programming languages that uses the concept of 'C'

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 produced when an interpreter or a compiler translates source code


into executable machine code.
• Object code is a set of instruction codes that is understood by a computer at the
lowest hardware level.

Muslim Association college of Arts and Science Page 20


S1 [Link] Computer Science CS1141: Introduction to Programming

• 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

Difference between compiler and interpreter

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.

Muslim Association college of Arts and Science Page 21


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link] more memory. Requires less memory compared to compiler.

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.

Rules for naming the Variables/Identifiers

1. Every variable name should start with alphabets or underscore (_).


2. No spaces are allowed in variable declaration.
3. Except underscore (_) no other special symbol are allowed in the middle of the variable

declaration (like %,*($ etc).


4. Maximum length of variable is 8 characters depend on compiler and operation system.
5. No keyword should access variable name (like int,char,void,main etc).

Variable declarations

This is the process of allocating sufficient memory space for the data in term of variable.

Syntax : Datatype variable_name; Example


: int a;

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.

Muslim Association college of Arts and Science Page 22


S1 [Link] Computer Science CS1141: Introduction to Programming

Declare constant const keyword are used for


declare a constant.
Syntax : cont datatype variablename=value;

Example : const int height = 100;

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

Muslim Association college of Arts and Science Page 23


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link] Data Types:

These are fundamental data types in C namely integer(int), floating point(float),


character(char) and Double.

[Link] Data Types:


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.

Basic Data Types


[Link]

• 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;

• The size of int is usually 4 bytes (32 bits).


• The range of int data type is -2147483648 to 2147483647.

2. float

• float and double are used to hold real numbers. • The size of float data types id 4
Bytes float salary;

• The range of float datatype is -3.4E+38 to +3.4E+38


[Link]

• In C, floating-point numbers can also be represented in exponential ,it is done


through double datatypes.
• The size of float data types id 4 Bytes
double a = 2.4e23;

• The range of double datatype is -1.7E+308 to +1.7E+308 What's the difference


between float and double?
The size of float (single precision float data type) is 4 bytes. And the size of double (double
precision float data type) is 8 bytes.

Muslim Association college of Arts and Science Page 24


S1 [Link] Computer Science CS1141: Introduction to Programming

[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.

char test = 'h';

**** void data type

• 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.

• The following are types of Operators used in C

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: (+, -, *, /, %,++,--).

Muslim Association college of Arts and Science Page 25


S1 [Link] Computer Science CS1141: Introduction to Programming

Operator Example
Description

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% B%A=0
Modulus Operator and remainder of after an integer
division.

++ Increment operator increases the integer value by one. A++ = 11

-- A-- = 9
Decrement operator decreases the integer value by
one.

[Link] Operators: It is used to compare more than one logical statements.

Operator Description Example

&& Called Logical AND operator. If both the operands are (A && B) is
non-zero, then the condition becomes true. false.

Muslim Association college of Arts and Science Page 26


S1 [Link] Computer Science CS1141: Introduction to Programming

|| Called Logical OR Operator. If any of the two operands (A || B) is


is non-zero, then the condition becomes true. true.

! !(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.

[Link] Operators: It shows the relationship between two operands

Operator Description
Example

== Checks if the values of two operands are equal or not. If (A == B) is not


yes, then the condition becomes true. true.

!= (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.

>= (A >= B) is not


Checks if the value of left operand is greater than or equal
true.
to the value of right operand. If yes, then the condition
becomes true.
<= (A <= B) is true
Checks if the value of left operand is less than or equal to
the value of right operand. If yes, then the condition
becomes true.

Muslim Association college of Arts and Science Page 27


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link] Operators : It is used to assign a value or expression to an operand.


Assignment is always from right to left
Operator
Description Example

= C = A + B will assign the


Simple assignment operator. Assigns values value of A + B to C
from right side operands to left side operand

+= 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.

Muslim Association college of Arts and Science Page 28


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link] Operator
It is used to separate two or more variables and statements Example
:

int variable1 , Variable2;

[Link] Operator:
It check a condition and perform the action based on the validity of the condition Syntax:
Condition ? statement1 : statement2; Example

a>b ? a is large : b is large

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.

• In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational


operators(==, !=, >, <, >=, <=) and precedence of relational operator is higher than
logical operators(&&, || and !). Example of precedence
(1 > 2 + 3 && 4)
This expression is equivalent to:

((1 > (2 + 3)) && 4)


i.e, (2 + 3) executes first resulting into 5 then, first part of the expression
(1 > 5) executes resulting into 0 (false)
then, (0 && 4) executes resulting into 0 (false) Output
:0

Input And Output Statements In C

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.

Muslim Association college of Arts and Science Page 29


S1 [Link] Computer Science CS1141: Introduction to Programming

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() scanf is used when we enter data by


using an input device.

Syntax: scanf (“format string”, &arg1, &arg2,


…..);
Format string consists of the conversion specifier. Arguments can be variables or array
name and represent the address of the variable. Each variable must be preceded by an
ampersand (&). Array names should never begin with an ampersand.

Example: Demonstrating scanf int


avg; float per; char grade; scanf(“%d
%f %c”,&avg, &per, &grade):

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.

Syntax: int getch(void);


ch=getch();

where, ch - assigned the character that is


returned by getch.

Muslim Association college of Arts and Science Page 30


S1 [Link] Computer Science CS1141: Introduction to Programming

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);

where, ch - the character that is to


be printed.

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);

viii) gets and puts


They help in transferring the strings between the computer and the standard
inputoutput devices. Only single arguments are accepted. The arguments must be
such that it represents a string. It may include white space characters. If gets is
used enter key has to be pressed for ending the string. The gets and puts function
are used to offer simple alternatives of scanf and printf for reading and displaying.

Example:
#include
<stdio.h> void
main()

Muslim Association college of Arts and Science Page 31


S1 [Link] Computer Science CS1141: Introduction to Programming

{
char line[30];
gets (line);
puts (line);
}

Muslim Association college of Arts and Science Page 32


S1 [Link] Computer Science CS1141: Introduction to Programming

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

Control statements in C to implement control structures

• “control structures are the basic entities of a structured programming language“.


• To implements these “control structures” in a C program, the language provides
‘control statements’

The control statements are:-

1. Switch
2. If
3. If Else
4. While
5. Do While
6. For

I. Selection structures are implemented using If , If Else and Switch


statements.L II. ooping structures are implemented using While, Do While
and For statements.

I. Selection structures • Selection structures are used to perform ‘decision making‘


and then branch the program flow based on the outcome of decision making.
• Selection structures are implemented in C with If, If Else and Switch statements. If
and If Else statements are 2 way branching statements where as Switch is a multi
branching statement.

1. If statement

The syntax format of a simple if statement is as shown below.

Muslim Association college of Arts and Science Page 33


S1 [Link] Computer Science CS1141: Introduction to Programming

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");
}

[Link] - else statement.

Syntax format for If Else statement is shown below.

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.

Example program to demo “If Else”

#include void
main()
{
int num;
printf("Hello user, Enter a number");

Muslim Association college of Arts and Science Page 34


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Example program to demo working of “switch”

#include

Muslim Association college of Arts and Science Page 35


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

• There are 3 control statements available in C/C++ to implement loop structures.


While, Do while and For statements.

[Link] statement

Syntax for while loop is shown

below: Initialization; while(condition)

{
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.

Example program to demo working of “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)
}

[Link] while statement


Syntax for do while loop is shown
below: Initialization; do
{
statement 1; statement
2;
statement 3;
}
while(condition);
Unlike while, do while is an exit controlled loop. Here the set of statements inside braces
are executed first. The condition inside while is checked only after finishing the first time
execution of statements inside braces. If the condition is TRUE, then statements are
executed again. This process continues as long as condition is TRUE. Program control
exits the loop once the condition turns FALSE.

Example program to demo working of "do while"

i=0; do
{
Printf(“%d”,i)
}
while(i<=10);

Muslim Association college of Arts and Science Page 37


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link] statement

Syntax of for statement is shown below:

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.

Working of for loop:

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.

Example program to demo working of "for loop"

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.

Muslim Association college of Arts and Science Page 38


S1 [Link] Computer Science CS1141: Introduction to Programming

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 [ ].

Accessing Array Elements

• 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]);
}

Muslim Association college of Arts and Science Page 39


S1 [Link] Computer Science CS1141: Introduction to Programming

Print elements from the array


for(i=0;i<size;i++)
{
print(“%d”,a[i]); }

Two-dimensional Arrays

• The simplest form of multidimensional array is the two-dimensional array. A


twodimensional array is, in essence, a list of one-dimensional arrays.
• To declare a two-dimensional integer array of size [x][y], you would write something
as follows type arrayName [ x ][ y ];
• Where type can be any valid C data type and arrayName will be a valid C identifier.
A two-dimensional array can be considered as a table which will have x number of
rows and y number of columns.
• A two-dimensional array a, which contains three rows and four columns can be
shown as follows −

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++)

Muslim Association college of Arts and Science Page 40


S1 [Link] Computer Science CS1141: Introduction to Programming

{
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

The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list )


{
body of the function
}

A function definition in C programming consists of a function header and a function body.


Here are all the parts of a function −
• Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations

Muslim Association college of Arts and Science Page 41


S1 [Link] Computer Science CS1141: Introduction to Programming

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);

Argument passing Methods in Functions


There are two parameter passing methods in C -.Call by Value and Call by Reference
[Link] by Value
The call by value method of passing arguments to a function copies the actual value of
an argument into the formal parameter of the function.
In this case, changes made to the parameter inside the function have no effect on the
argument.
By default, C programming uses call by value to pass arguments. In general, it means the
code within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.

Muslim Association college of Arts and Science Page 42


S1 [Link] Computer Science CS1141: Introduction to Programming

#include <stdio.h>

void swap(int x, int y);

int main () {
int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

swap(a, b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", 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.

Muslim Association college of Arts and Science Page 43


S1 [Link] Computer Science CS1141: Introduction to Programming

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 swap(int *x, int *y);

void main () {

int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );
getch();
}
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 :200
After swap, value of b :100

Muslim Association college of Arts and Science Page 44


S1 [Link] Computer Science CS1141: Introduction to Programming

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;

example program of pointer

#include <stdio.h>

void main () {

int a = 20;
int *p;
p=&a;
printf("Address of a: %x\n", &a );

printf("Address stored in p: %x\n", p );

printf("Value of *p: %d\n", *p );

getch();
}

Output:
Address of a: 1010111
Address stored in p: 1010111
Value of *p: 20

“&” and “*” operators in C


• The & is a unary operator in C which returns the memory address of the passed
operand. This is also known as address of operator.
&a Means address of a
• The * is a unary operator which returns the value of object pointed by a pointer
variable. It is known as value of operator. It is also used for declaring pointer
variable.
*p means p is a pointer variable and can store address of another variable
Muslim Association college of Arts and Science Page 45
S1 [Link] Computer Science CS1141: Introduction to Programming

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]()

“malloc” or “memory allocation” method is used to dynamically allocate a single


large block of memory with the specified size. It returns a pointer of type void which can
be cast into a pointer of any form. Syntax: ptr = (cast-type*) malloc(byte-size)

For Example:

ptr = (int*) malloc(100 * sizeof(int));

• Since the size of int is 4 bytes,


• this statement will allocate 400 bytes of memory.
• And, the pointer ptr holds the address
• of the first byte in the allocated memory.

[Link]()

“calloc” or “contiguous allocation” method is used to dynamically allocate the


specified number of blocks of memory of the specified type. It initializes each block with
a default value
‘0’.
Syntax: ptr = (cast-type*)calloc(n, elementsize);

For Example:

ptr = (float*) calloc(25, sizeof(float));


• This statement allocates contiguous space in memory • for 25 elements each with
the size of float.

Muslim Association college of Arts and Science Page 46


S1 [Link] Computer Science CS1141: Introduction to Programming

[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]()

• “realloc” or “re-allocation” method is used to dynamically change the memory


allocation of a previously allocated memory.
• In other words, if the memory previously allocated with the help of malloc or calloc
is insufficient, realloc can be used to dynamically re-allocate memory. Syntax: ptr
= realloc(ptr, newSize);

• where ptr is reallocated with new size 'newSize'.

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

Syntax for specifying storage class to the variable


storage_class_specifier data_type variable_name; Example:
extern int a;

Muslim Association college of Arts and Science Page 47


S1 [Link] Computer Science CS1141: Introduction to Programming

1. Automatic Storage Class


• A variable defined within a function or block with auto specifier belongs to
automatic storage class.
• All variables defined within a function or block by default belong to automatic
storage class if no storage class is mentioned.
• Variables having automatic storage class are local to the block which they are
defined in, and get destroyed on exit from the block.

Int sum(int a,int b)


{
auto int s;
s=a+b;
}
• Here s is auto variable that is available only inside the function body of sum()

2. Register Storage Class


• The register specifier declares a variable of register storage class.
• Variables belonging to register storage class are local to the block which they are
defined in, and get destroyed on exit from the block.
• A register declaration is equivalent to an auto declaration, but hints that the
declared variable will be accessed frequently; therefore they are placed in CPU
registers, not in memory.
register int i = 10;
[Link] Storage Class
• 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.
When specifier is applied to a local variable inside a function or block, the
static
compiler creates permanent storage for it,


Static int i=20;

Muslim Association college of Arts and Science Page 48


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link] storage class

• 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

[Link] Storage class

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

typedef typedef current_name new_name; typedef int macas; macas i, j;

Now, we can write macas in the whole program instead of int.


Relationship Between Pointers And Array
Consider the below array declaration, int
arr[5];
It declares an integer array with a capacity of five elements. To access any element of the
given
array we use array index notation. For example to access zeroth element we use arr[0] ,
similarly to access fifth element we use arr[4].

Muslim Association college of Arts and Science Page 49


S1 [Link] Computer Science CS1141: Introduction to Programming

int * ptr = &arr[0];


The above statement declares an integer pointer pointing at zeroth array element.

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.

int * ptr = &arr[0]; int * ptr = arr;

How to access single dimension array using pointer

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.

Muslim Association college of Arts and Science Page 50


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Strings are actually one-dimensional array of characters terminated by a null character


'\0'.
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word "Hello." char a[6] = {'H',
'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as
follows − char a[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −

Muslim Association college of Arts and Science Page 51


S1 [Link] Computer Science CS1141: Introduction to Programming

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 () {

char a[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", a );
return 0;
}

When the above code is compiled and executed, it produces the following result −
Greeting message:
Hello

C supports a wide range of functions that manipulate null-terminated strings −

Muslim Association college of Arts and Science Page 52


S1 [Link] Computer Science CS1141: Introduction to Programming

[Link].

Function & Purpose

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:

Muslim Association college of Arts and Science Page 53


S1 [Link] Computer Science CS1141: Introduction to Programming

S1=”I love India”


Strtchr(s1,n); returns the value 8
6

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

Muslim Association college of Arts and Science Page 54


S1 [Link] Computer Science CS1141: Introduction to Programming

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(;).

Example of Structure struct


Student
{ char
name[25]; int
age; char
branch[10];
// F for female and M for male char
gender;
};
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition or
after the structure is defined. Structure variable declaration is similar to the declaration
of any normal variable of any other datatype. Structure variables can be declared in
following two ways:

1) Declaring Structure variables separately


struct Student
{ char
name[25]; int
age; char
branch[10];
//F for female and M for male char
gender;
};

struct Student S1, S2; //declaring variables of struct Student

Muslim Association college of Arts and Science Page 55


S1 [Link] Computer Science CS1141: Introduction to Programming

2) Declaring Structure variables with structure definition struct


Student
{ char
name[25]; int
age; char
branch[10];
//F for female and M for male char
gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.

Accessing Structure Members


Structure members can be accessed and assigned values in a number of ways.
Structure members have no meaning individually without the structure. In order to
assign a value to any structure member, the member name must be linked with the
structure variable using a dot . operator also called period or member access
operator.
For example:
#include<stdio.h>
#include<string.h>

struct Student
{ char name[25]; int age;
char branch[10]; //F for
female and M for male char
gender;
};

int main()
{
struct Student s1;

/* s1 is a variable of Student type


and age is a member of

Muslim Association college of Arts and Science Page 56


S1 [Link] Computer Science CS1141: Introduction to Programming

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;
}

Name of Student 1: Viraaj


Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", [Link]);
scanf(" %d ", &[Link]);

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.

Muslim Association college of Arts and Science Page 57


S1 [Link] Computer Science CS1141: Introduction to Programming

#include<stdio.h>

struct Employee
{
char ename[10];
int sal;
};

struct Employee emp[5];


int i, j;
void ask()
{ for(i =
0; i <
3;i++)
{
printf("\nEnter %dst Employee
record:\n",i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee
record:\n"); for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
void main()
{ ask();
getch(
);)

Muslim Association college of Arts and Science Page 58


S1 [Link] Computer Science CS1141: Introduction to Programming

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

When a union is defined, it creates a user-defined type. However, no memory is allocated.


To allocate memory for a given union type and work with it, we need to create variables.

Here's how we create union variables.


1. union
2. { car

Muslim Association college of Arts and Science Page 59


S1 [Link] Computer Science CS1141: Introduction to Programming

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.

Muslim Association college of Arts and Science Page 60


S1 [Link] Computer Science CS1141: Introduction to Programming

FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following
are the functions,
Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

Muslim Association college of Arts and Science Page 61


S1 [Link] Computer Science CS1141: Introduction to Programming

ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening
the file. Mode can be of following types,
mode description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

Muslim Association college of Arts and Science Page 62


S1 [Link] Computer Science CS1141: Introduction to Programming

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

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.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform
reading and writing on file. getc() and putc() are the simplest functions which can be
used to read and write individual characters to a file.
fp = fopen("[Link]", "w");

Muslim Association college of Arts and Science Page 63


S1 [Link] Computer Science CS1141: Introduction to Programming

printf("Enter data...");
while( (ch = getchar()) !=
EOF) { putc(ch, fp);
}
fclose(fp); op

fp = fopen("[Link]", "r");

while( (ch = getc(fp)! =


EOF) printf("%c",ch);

// closing the file pointer


fclose(fp);

fseek(), ftell() and rewind() functions

• 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.

Muslim Association college of Arts and Science Page 64

You might also like