0% found this document useful (0 votes)
105 views66 pages

Programming For Problem Solving-4

This syllabus document outlines an introductory programming course in C language. The course aims to teach students how to formulate algorithms, translate them into programs using C, test and debug programs, implement conditional branching, loops, arrays, functions, pointers and structures. It covers 9 units - introduction to programming, arithmetic expressions, conditional branching, loops, arrays, algorithms, functions, recursion, structures and pointers. The course intends to help students decompose problems, write programs to solve matrix, searching, sorting and numerical problems.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
105 views66 pages

Programming For Problem Solving-4

This syllabus document outlines an introductory programming course in C language. The course aims to teach students how to formulate algorithms, translate them into programs using C, test and debug programs, implement conditional branching, loops, arrays, functions, pointers and structures. It covers 9 units - introduction to programming, arithmetic expressions, conditional branching, loops, arrays, algorithms, functions, recursion, structures and pointers. The course intends to help students decompose problems, write programs to solve matrix, searching, sorting and numerical problems.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 66

Syllabus in programming for problem solving

Course Outcomes
The student will learn
To formulate simple algorithms for arithmetic and logical problems.
 To translate the algorithms to programs (in C language).
 To test and execute the programs and correct syntax and logical errors.
 To implement conditional branching, iteration and recursion.
 To decompose a problem into functions and synthesize a complete program using divide and conquer
approach.
To use arrays, pointers and structures to formulate algorithms and programs.
 To apply programming to solve matrix addition and multiplication problems and searching and sorting
problems.
To apply programming to solve simple numerical method problems, namely rot finding of function,
differentiation of function and simple integration.
Unit 1
Introduction to Programming (4 lectures)
Introduction to components of a computer system (disks, memory, processor, where a program is stored
and executed, operating system, compilers etc.) - (1 lecture).
Idea of Algorithm: steps to solve logical and numerical problems. Representation of Algorithm:
Flowchart/Pseudocode with examples. (1 lecture)
From algorithms to programs; source code, variables (with data types) variables and memory locations,
Syntax and Logical Errors in compilation, object and executable code- (2 lectures)
Unit 2
Arithmetic expressions and precedence (2 lectures)
Conditional Branching and Loops (6 lectures)
Writing and evaluation of conditionals and consequent branching (3 lectures)
Iteration and loops (3 lectures)
Unit 3
Arrays (6 lectures) Arrays (1-D, 2-D), Character arrays and Strings
Unit 4
Basic Algorithms (6 lectures) Searching, Basic Sorting Algorithms (Bubble, Insertion and Selection),
Finding roots of equations, notion of order of complexity through example programs (no formal definition
required)
Unit 5
Function (5 lectures) Functions (including using built in libraries), Parameter passing in functions, call by
value, Passing arrays to functions: idea of call by reference
Unit 6
Recursion (4 -5 lectures) Recursion, as a different way of solving problems. Example programs, such as
Finding Factorial, Fibonacci series, Ackerman function etc. Quick sort or Merge sort.
Unit 7
Structure (4 lectures) Structures, Defining structures and Array of Structures
Unit 8
Pointers (2 lectures) Idea of pointers, Defining pointers, Use of Pointers in self-referential structures,
notion of linked list (no implementation)
Unit 9
File handling (only if time is available, otherwise should be done as part of the lab)

Introduction to Programming

 Programming is the mental process of thinking up instructions to give to a machine (like a computer).
 Coding is the process of transforming those ideas into a written language that a computer can
understand.

 A programming language is a set of rules that provides a way of telling a computer what
operations to perform.
 A programming language defines a set of instructions that are compiled together to perform a
specific task by the CPU (Central Processing Unit).
 A programming language is a set of rules for communicating an algorithm.
 It provides a linguistic framework for describing computations.

 A programming language describes computation in a machine-readable and human-readable


form.
 A programming language also acts as a tool for developing executable models for a class of
problem domains.
 It contains words, symbols and rules of grammar where grammatical rules are called syntax.
 Each programming language has a different set of syntax rules.
 The programming language mainly refers to high-level languages such as C, C++, Pascal, Ada,
COBOL (Common Business Oriented Language developed in 1959 and primarily designed to be
common to many different applications), etc.
Levels of Programming Languages
As we can observe from the below image that the machine language provides no abstraction, assembly
language provides less abstraction whereas high-level language provides a higher level of abstraction.

Low-level language
The low-level language is a programming language that provides no abstraction from the hardware, and it
is represented in 0 or 1 forms, which are the machine instructions. The languages that come under this
category are the Machine level language and Assembly language.

Machine-level language
The machine-level language is a language that consists of a set of instructions that are in the binary form
0 or 1. Operation code- such as addition or subtraction. Operands specifies the data to be processed.
Machine language is machine dependent as it is the only language the computer can understand. Very
efficient code but difficult to write. It is error-prone as it is not easy to understand, and its maintenance is
also very high. A machine-level language is not portable as each computer has its machine instructions,
so if we write a program in one computer will no longer be valid in another computer. The different
processor architectures use different machine codes, for example, a PowerPC processor contains RISC
architecture, which requires different code than intel x86 processor, which has a CISC architecture.

Assembly Language
The assembly language contains some human-readable commands such as mov, add, sub, etc. The
problems which we were facing in machine-level language are reduced to some extent by using an
extended form of machine-level language known as assembly language. Symbolic operation code
replaced binary operation codes. Each assembly language instruction is translated into one machine
language instruction. It is very efficient code and easier to write. As we know that computers can only
understand the machine-level instructions, so we require a translator that converts the assembly code into
machine code. The translator used for translating the code is known as an assembler. The assembly
language code is not portable because the data is stored in computer registers, and the computer has to
know the different sets of registers. The assembly code is not faster than machine code because the
assembly language comes above the machine language in the hierarchy, so it means that assembly
language has some abstraction from the hardware while machine language has zero abstraction.
High-Level Language
The high-level language is a programming language that allows a programmer to write the programs
which are independent of a particular type of computer. The high-level languages are considered as high-
level because they are closer to human languages than machine-level languages. When writing a
program in a high-level language, then the whole attention needs to be paid to the logic of the
problem. A compiler is required to translate a high-level language into a low-level language.

Advantages of a high-level language

o The high-level language is easy to read, write, and maintain as it is written in English like words.
o The high-level languages are designed to overcome the limitation of low-level language, i.e.,
portability. The high-level language is portable; i.e., these languages are machine-independent.
C Programming Language

The C Language is developed by Dennis Ritchie in early 1970s for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc. C programming is considered as
the base for other programming languages, that is why it is known as mother language. C provides control
and efficiency of assembly language. Eg. UNIX is written in C.

1. It can be defined by the following ways: Mother language


2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

C as a mother language
C language is considered as the mother language of all the modern programming languages because  most
of the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming
languages follow C syntax, for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are being used in
many languages like C++ (It is C language with additional features and widely used for developing
system and application software. With the help of C++, graphical user interfaces can be developed easily
with visual programming tools),
 Java (It is an object-oriented language similar to C++ which allows a web page developer to create
programs for applications, called applets that can be used through a browser)., C#, etc.

C as a system programming language


A system programming language is used to create system software. C language is a system programming
language because it can be used to do low-level programming (for example driver and kernel). It is
generally used to create hardware devices, OS, drivers, kernels, etc. For example, Linux kernel is written
in C.

It can't be used for internet programming like Java, .Net, PHP, etc.

C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural language  specifies a
series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared before being used.

C as a structured programming language


A structured programming language is a subset of the procedural language. Structure means to break a
program into parts or blocks so that it may be easy to understand.

n the C language, we break the program into parts using functions. It makes the program easier to
understand and modify.

C as a mid-level programming language


C is considered as a middle-level language because it supports the feature of both low-level and high-
level languages. C language program is converted into assembly code, it supports pointer arithmetic
(low-level), but it is machine independent (a feature of high-level).

A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast
to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is easy to understand

Factors to determining a “good” language

Formerly: Run-time performance (when computers were more expensive than programmers).
Now: Life-cycle (human) cost is more important

Ease of designing, coding, debugging, maintenance and reusability is important.


Criteria in a good language design

Writability: It specifies the quality of a language that enables a programmer to use it ot express a
computational clearly, correctly, concisely and quickly.

Readability: The quality of a language that enables a programmer to understand and comprehend the
nature of a computation easily and accurately.

Orthogonality: This parameter specifies the features provided have as few restrictions as possible and be
combinable in any meaningful way.

Reliability: The quality of a language that assures a program will not behave in unexpected of disastrous
ways during execution.

Maintainability: The quality of a language which eases of error finding and correction and new features
support.

Generality: This quality avoids special cases in the availability or use of constructs and by combining
closely related constructs into a single more general one.

Uniformity: This quality specifies that similar features should look similar and behave similar.

Extensibility: It provides some general mechanism for the user to add new constructs to a language.

Standardability: Quality that allows program written to be transported from one computer to another
without significant change in a language structure.

Implementability: Quality of a language that provides a translator or interpreter can be written. This can
address to complexity of the language definition.

Computer

A computer is an electronic device that accepts data from the user, processes it, produces results,
displays them to the users, and stores the results for future usage.
Data is a collection of unorganized facts (unstructured) & figures and does not provide any further
information regarding patterns, context, etc. Hence data means "unstructured facts and figures".
Information is a structured data i.e. organized meaningful and processed data. To process the data and
convert into information, a computer is used.
Components of Computer System
Computer systems consist of three components as shown in below image: Central Processing Unit,
Input devices and Output devices.
1. Central Processing Unit

The Central Processing Unit (CPU) is called "the brain of computer" as it controls operation of all parts
of computer. It consists of two components: Arithmetic Logic Unit (ALU), and Control Unit.

(a)Arithmetic Logic Unit (ALU) - Data entered into computer is sent to RAM, from where it is then sent
to ALU, where rest of data processing takes place. All types of processing, such as comparisons,
decision-making and processing of non-numeric information takes place here and once again data is
moved to RAM.

(b) Control Unit - As name indicates, this part of CPU extracts instructions, performs execution,
maintains and directs operations of entire system. Control unit performs following functions:

 It controls all activities of computer


 Supervises flow of data within CPU
 Directs flow of data within CPU
 Transfers data to Arithmetic and Logic Unit
 Transfers results to memory
 Fetches results from memory to output devices

2. Input devices

It provides data input to processor, which processes data and generates useful information that’s displayed
to the user through output devices. This is stored in computer’s memory. Eg. Keyboard, Mouse &
microphone etc.

3. Output Devices

These devices include printed documents, on-screen data and sound. An output device allows data to be
transmitted by the computer in a human-friendly form, for example, sound being played through a
speaker.

 Monitor - The main output device of a computer. It forms images by converting electrical energy into
light in the form of tiny dots on the screen called pixels. The sharpness of the image depends upon the
number of pixels.
 Printer - Used to print information on paper. Commonly uses either lasers or inkjets to precisely place
ink onto the page to recreate text and high-quality images.
 Speaker - Converts digital signals into audible sound waves.
 Projector - A device that is used to project video output from the computer onto a wall or screen.

Memory Unit

This is unit in which data and instructions given to computer as well as results given by computer are
stored. Unit of memory is "Byte". 1 Byte = 8 Bits

Primary Memory : Primary memory is the main memory of computer present in motherboard. Primary
memory is of two types as shown in the image below.

Random Access Memory


RAM is referred as temporary memory, in which, information stored is lost once computer is turned off.
It is a volatile memory. Instructions written in this memory can be modified; hence it is also known as
programmable memory.

Functions of RAM are as follows −


 It stores data till it gets processed.
 It stores instructions for data processing.
 It acts as a working space where data processing takes place and intermediate results are stored.
 It stores processed data/results before it is sent to output devices.

Read Only Memory


ROM is referred as permanent memory, in which information stored is available even if computer is
turned off. Instructions stored in this memory can only be read and cannot be modified. Mostly ROM
has a start-up instruction which is executed every time when computer is switched on. Types of ROM
are PROM (Programmable Read Only Memory), EPROM (Erasable PROM), EEPROM (Electrically
Erasable PROM) and flash memory.
The below table jots down the major differences between RAM and ROM −

Sr.N RAM ROM


o

1 It is volatile memory. It is non-volatile memory.

2 The contents are temporary; data is lost The contents are permanent; data is not lost
when electricity supply is lost. even when power is switched off.

3 Available in small storage capacity. Available in high storage capacity.

4 Processing speed is high. Processing speed is low.

5 User-defined programs can be stored. Generally, operating system supporting


programs can be stored.

6 Cost is very high. Cost effective.

7 It is of two types, SRAM and DRAM. It comes in different types such as PROM,
EPROM, EEPROM and flash memory.

Secondary Memory

Sometimes when data to be processed is large, it cannot fit in primary memory as it is limited, in such
cases, we use supplement memory or secondary memory. Secondary memory helps to store information
permanently and is non-volatile. Examples of secondary storage memory are compact disk, floppy disk,
pen drive, external hard drive, etc.
Computer Disks
a computer data storage device such as a hard drive or floppy disk that contains a computer disk
containing sensitive information. Disk may be floppy disk or hard Disk.
Floppy Disk: A floppy disk is a type of storage media that reads data storage information, also known as
a floppy diskette, floppy, or floppy disk that is used to store electronic data, like a computer file.

This disk was only able to store 80KB of


data, but later versions became capable of storing as much as 800KB. The floppy disks were replaced by
the devices like USB and network file transfer; however, these disks are now outdated. As the technology
advanced, a floppy disk that is becoming smaller and came in three sizes, 8 inches, 5.5 inches, 5.25 inches
(capable of holding 360 Kb data) and 3.5 inches High Density (1.44MB). As compared to previous
models of floppy, the newer version can store more data than used more cutting-edge technology.

Advantages of Floppy Disks

o Portability: They are relatively small and portable, which is one of the main advantages of
floppy disks. As compared to CDs, 3.5-inch floppy disks are smaller in size. Also, in the case of
transport, they do not require to place. The floppy disk is designed with a plastic casing that
makes it stronger and protects the disk from inside. Comparing with CDs and DVDs, the chance
of scratching the disk is lower as it is always enclosed by the casing.

o Compatibility: It is also an important advantage in terms of data storage devices with older
computers. As older computers may not accept other data storage devices; they are often
compatible with floppy disks. For example, in the early 1990s, computers might not include
a CD or DVD drive at all. Floppy disks were only the option to transfer files off the computer.
Although many newer PCs have floppy drives, these drives are not included in modern PCs and
being phased out. When computer manufacturers were building a custom-made PC, they may
provide floppy drives as an option.

Disadvantages of Floppy Disks


o Speed: The rate of data transferring is very slow in a floppy disk. When data is transferring to the computer
from the floppy disk or computer to the floppy disk, considerably, it can take much time for transferring
data.

o Storage Space: Floppy disk drives contain limited space for holding information. It provides very low
storage capacity as compared to modern storage mediums.

o File Corruption: File corruption is one of the main disadvantages of the floppy disk. The FDDs are affected
by external factors like heat and magnetic fields. Thus, the stored file could be corrupted on it.
Furthermore, comparing any other storage mediums, floppy disks do not provide more security as they are
more vulnerable to viruses that can be a reason for file damage.

o Reliability Over time:, the use of floppy disks has decreased or stopped till the 2000s. Therefore, many
computer manufacturers had been stopped, including a floppy disk with computers. After this period, it
becomes an unreliable source of storage.

o Physical Damages: The plastic casing was used to make the floppy disk that is very delicate and flexible. It
may get easily break if anyone catches it without proper care.

hard disk

A hard disk is also known as a hard drive or fixed disk. It is said to be rigid magnetic disc that stores data.
It is located within a drive unit. Hard disk is a non-volatile storage device that contains platters and
magnetic disks rotating at high speeds. Non-volatile means the data retains when the computer shuts
down. It is installed internally in our computer systems. Hard disk is located within a drive unit on the
computer's motherboard and comprises one or more platters packed in an air-sealed casing.

The hard disk is a secondary storage


device, which is designed to store data permanently. The secondary storage devices include a large
storage capacity as compared to the primary storage devices. The data stored in a hard disk is retained
when our computer system shuts down. The data stored in the hard disk can be of many types such as the
operating system, installed software, documents, and other files of computer. Every computer contains at
least one hard drive to store data and software. In Windows operating system, the hard drive is known to
be the C drive, and in MAC, it is simply called as the hard drive. The desktop computers which have
external hard drives are used for backup purposes or additional storage. The size of hard drives is
measured in gigabytes and terabytes. Usually, 500GB hard disks are common in modern computers. As
an instance, a song of length four-minute is approx. 4MB in size, and in 1 gigabyte, there are 1,000
megabytes, it means that a 500GB hard drive can store approx. 250,000 songs.

Advantages of the hard disk


o One of the significant advantages of a Hard Disk drive is that its cost is low.
o Another advantage of a Hard Disk is that it is readily available in the market.
o Hard Disk is faster than optical disks.
o The capacity for storing the data in HDDs is large.

Disadvantages of the hard disk


o The speed of reading and writing in HDD is slower than the RAM.
o HDDs are noisy.
o Another disadvantage of HDD is energy inefficiency.
o HDDs consume more power.
o The form factor of HDDs is heavier than the SSDs.

The hard disks are robust and can be used for a long time. But hard disks can be crashed, and the main
reason is head crash. If the hard drive is crashed, we may lose all our documents, photos, etc., stored in it.

Compilers
compiler, is a computer software that translates (compiles) source code written in a high-level
language (e.g., C++) into a set of machine-language instructions that can be understood by a digital
computer’s CPU. Compilers are very large programs, with error-checking and other abilities. Some
compilers translate high-level language into an intermediate assembly language, which is then translated
(assembled) into machine code by an assembly program or assembler. Other compilers generate machine
language directly.  When executing (running), the compiler first parses (or analyzes) all of the language
statements syntactically one after the other and then, in one or more successive stages or "passes", builds
the output code, making sure that statements that refer to other statements are referred to correctly in the
final code. Traditionally, the output of the compilation has been called object code or sometimes an object
module . (Note that the term "object" here is not related to object-oriented programming.) The object code
is machine code that the processor can execute one instruction at a time.
The Java programming language, a language used in object-oriented programming, introduced the
possibility of compiling output (called bytecode ) that can run on any computer system platform for
which a Java virtual machine or bytecode interpreter is provided to convert the bytecode into instructions
that can be executed by the actual hardware processor. Using this virtual machine, the bytecode can
optionally be recompiled at the execution platform by a just-in-time compiler. A compiler works with
what are sometimes called 3GL and higher-level languages. An assembler works on programs written
using a processor's assembler language.
Operating system

An operating system is the most important software that runs on a computer. It manages the


computer's memory and processes, as well as all of its software and hardware. It also allows you
to communicate with the computer without knowing how to speak the computer's language. Without an
operating system, a computer is useless.

Types of operating systems

Operating systems usually come pre-loaded on any computer you buy. Most people use the operating
system that comes with their computer, but it's possible to upgrade or even change operating systems. The
three most common operating systems for personal computers are Microsoft Windows, macOS,
and Linux.

Modern operating systems use a graphical user interface, or GUI (pronounced gooey). A GUI lets you
use your mouse to click icons, buttons, and menus, and everything is clearly displayed on the screen
using a combination of graphics and text. Each operating system's GUI has a different look and feel, so if
you switch to a different operating system it may seem unfamiliar at first. However, modern operating
systems are designed to be easy to use, and most of the basic principles are the same.

Problem Solving Techniques steps

As computer is the symbol-manipulating machine that follows the set of instructions called a program.
Any computing has to be performed independently without depending on the programming language and
computer. The problem solving techniques includes the following steps:

 Define the problem.


 Formulate the mathematical model.
 Develop an algorithm.
 Write the code for the problem.
 Test the program.

1 Define the Problem

 A clear and concise problem statement is provided.


 The problem definition should specify the input and output.
 Full knowledge about the problem is needed.

Example: To find the average of two numbers.

2. Formulate the Mathematical Problem

 Any technical problem provided can be solved mathematically.


 Full knowledge about the problem should be provided along with the underlying mathematical
concept.

Eg. ((data 1+data 2)/2)

3. Develop an algorithm

 An algorithm is the sequence of operation to be performed.


 It gives the precise plan of the problem.
 An algorithm can be of flowchart or pseudo code.

Eg. Problem Definition: To find the average of two numbers.


Algorithm: 1. Set the sum of data values to 0.

2. Set the count of the data values to zero.

3. As long as the data value exist, add the next data value to the sum and add another data value to the
count.

4. To compute the average, divide the sum by the count.

5. Print the average.

Task: To find the average 20 and 30 manually.

20+30=50; 50/2=25.

4. Write the code for the Problem

 The algorithm developed must be converted to any programming language.


 The compiler will convert the program code to the machine language which the computer can
understand.

5. Test the program

 Testing involves checking errors both systematically and semantically.


 The errors are called as “bugs”.
 When the compiler finds the bugs, it prevents compiling the code from programming language to
machine language.
 Check the program by providing a set of data for testing.

Program

A program consists of a series of instructions that a computer processes to perform, the required
operation. In addition, it also contains some fixed data, required to perform the instructions, and the
process of defining those instructions and data.

Set of computer programs that describe the program are called software.

The process of software development is called Programming and the person who develops the computer
programs is called Programmer. Thus, in order to design a program, a programmer must determine three
basic requirements:

 The instructions to be performed.


 The order in which those instructions are to be performed.
 The data required to perform those instructions.
Eg. Write a program to add two numbers.

 Input two numbers.


 Add these two numbers.
 Display the output.

To perform a task using a program, a programmer has to consider various inputs of the program along
with the process, which is required to convert input into desired output. Suppose we want to calculate the
sum of two numbers, A and B, and store the sum in C, here A and B are the inputs, addition is the
process, and C is the output of the program as shown below:

A,B C=A+B C
Input Processing Output
Characteristics of a program

Writability: It specifies the quality of a language that enables a programmer to use it ot express a
computational clearly, correctly, concisely and quickly.

Readability: The quality of a language that enables a programmer to understand and comprehend the
nature of a computation easily and accurately.

Orthogonality: This parameter specifies the features provided have as few restrictions as possible and be
combinable in any meaningful way.

Reliability: The quality of a language that assures a program will not behave in unexpected of disastrous
ways during execution.

Maintainability: The quality of a language which eases of error finding and correction and new features
support.

Generality: This quality avoids special cases in the availability or use of constructs and by combining
closely related constructs into a single more general one.

Uniformity: This quality specifies that similar features should look similar and behave similar.

Extensibility: It provides some general mechanism for the user to add new constructs to a language.

Standardability: Quality that allows program written to be transported from one computer to another
without significant change in a language structure.

Implementability: Quality of a language that provides a translator or interpreter can be written. This can
address to complexity of the language definition.

Program Development Cycle

 Any program has to be broken into a series of smaller steps.


 These series are independent of programming language.
 The programmer should have wider language about the problem and the way to solve it.
Generally any problem solving includes

 Define the problem.


 Understanding the problem.
 Providing the solution.
The program development cycle involves

 Problem Analysis
 Design Algorithm and Flowchart development
 Program coding
 Program compilation and execution.
 Program debugging and Testing
 Documentation

Problem Analysis

Design-Algorithm Flowchart

Problem Coding

Compilation & Execution

Debugging & Testing

Documentation

Fig. Problem Solving Skills


1. Problem Analysis

 Define the problem by identifying the input and output to it.


 Variable name is assigned for each item.
 After analyzing, the programmer has to develop various solutions for the given problem.
 Optimal solution is taken from the set of solutions obtained.
2. Design – Algorithms and Flowchart development

 Algorithm and flowchart are developed to provide a sequence of actions to be performed.


 Algorithm provides a basic logic is solving the problems by providing sequence of
instructions.
 Algorithms cane be of 1. Flow chart 2. Pseudo code
Program Design Language (PDL): It has no specific standard rules for defining the PDL statements. PDL
is independent of any programming language. It is also called as pseudo code.
3. Program Coding

 Code the algorithm in the selected programming language.


 The processes of translating the algorithm or the flowchart into an exact instruction that
will make up the programs are called as program coding.
4. Program Compilation and Execution

 After program coding, the program has to be compiled and executed.


 During compilation, if no error is produced, then the program is executed successfully.
 If errors are available, then the errors are displayed in the terminal, and corrected later
with correct syntax and then compiled.
5. Program Debugging and Testing

 Errors are called as “bugs”.


 Errors can be categorized as follows:
 Syntax Errors (during compilation) eg. Program does not compile, missing bracket, bad
punctuation.
 Run time (during execution) eg. Program crashes, check input data.
 Logical (incorrect or illogical answers) Eg. Program runs and give wrong output.
6. Documentation

 Once the programme is free from the errors, it is the duty of the programmer to document
all the necessary documents which is provided to the program users as manual.
 Helps the users to operate correctly.

Algorithm
 Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language. Different algorithms may accomplish the same task, with a different set of instructions,
in more or less same time, space and efforts.
Eg. To determine the largest number out of three numbers A,B and C.
Step 1: Start
Step 2: Read three numbers A,B,C
Step 3: Find the larger number between A and B and store is in MAX AB.
Step 4: Find the larger number between MAX AB and C and store it in MAX.
Step 5: Display MAX.
Step 6: Stop.
The above-mentioned algorithm terminates after six steps. This explains the feature of finiteness.
Every action of the algorithm is precisely defined, hence, there is no scope for ambiguity. Once the
solution is properly designed, the only job left is to code that logic into a programming language.
Characteristics of Algorithm

 It should have finite number of inputs.


 Terminates after a finite number of steps.
 Instructions are precise and unambiguous.
 Operations are done exactly in a finite amount of time.
 Outputs are derived from the input by applying the algorithm.
Quality of Algorithm

 An algorithm should be relatively fast.


 Any algorithm should require minimum computer memory to produce the desired output in
an acceptable amount of time.

Flowchart

 It is a diagrammatic representation of an algorithm that illustrates the sequence of


operations to be performed to get a solution.
 The different boxes are interconnected with the help of arrows.
 The boxes represent operations and the arrows represent the sequence in which the
operations are implemented.
 The primary purpose of the flowchart is to help the programmer in understanding the
logic of the program.
Flowchart Symbols
Symbol Symbol Name Description
Flow Lines Flow lines are used to connect symbols. These lines indicate
the sequence of steps and the direction of flow of control.
Terminals This symbol is used to represent the beginning (start), the
terminal (end), or halt (pause) in the programming logic.
Input / Output It represents information entering or leaving the system, such
as customer order (input) and servicing (output).
Processing Process symbol is used for representing arithmetic and data
movement instructions. It can represent a single step or an
entire process within a larger process.
Decision Decision symbols denote a decision to be made. The program
should continue along one of the two routes (IF/ELSE). This
system has one entry and two exit paths. The path chosen
depends on whether the answer to a question is yes or no.
Connector Connector symbol is used to join different flow lines.
Off-page Connector This symbol is used to indicate that the flowchart
continues on the next page.
Document Document is used to represent a paper document
produced during the flowchart process.
Manual Input Manual input symbol represents inputs to be given by
developer/programmer.
Manual Operation Manual operation symbol represents that the process has
to be done by a developer/programmer.
Online Storage This symbol represents the online data storage such as
hard disks, magnetic drums or other storage devices.
Communication link Communication link symbol is used to represent data
received to be transmitted from an external system.
Magnetic Disk This symbol is used to represent data input or output from
and to a magnetic disk.

Guidelines for preparing flowcharts

 The flowchart should be clear, neat and easy to follow.


 The flowchart must have a logical start and finish.
 In drawing a proper flowchart, all necessary requirements should be listed in logical order.
 Only one flow line should come out from a process symbol.
 Only one flow line should enter a decision symbol. However, two or three flow lines may leave
the decision symbol.
 Only one flow line is used with a terminal symbol.
 In case of complex flowcharts, connector symbols are used to reduce the number of flow lines.
Advantages of Flowcharts
As flowchart helps to clarify how things are currently working and how they could-be improved due
to
1. Makes logic clear: the main advantage of using a flowchart to plan a task is that it provides a
pictorial representation of the task, which makes the logic easier to follow. Even less experienced
personnel can trace the actions represented by a flowchart, that is, flowcharts are ideal for visualizing
fundamental control structures employed in computer programming.
2. Communication: Being a graphical representation of a problem solving logic, flowcharts are better
way of communicating the logic of a system to all concerned. The diagrammatical representation of
logic is easier to communicate to all the interested parties as compared to actual program code as the
users may not be aware of all the programming techniques.
3. Effective Analysis: With the help of a flowchart, the problems can be analyzed in an effective way
due to the analyzing duties of programmers can be delegated to other persons., who may or may not
know the programming techniques, but they have a broad idea about the logic.
4. Useful in coding: The flowcharts acts as a guide or blueprint during the analysis and program
development phase. Once the flowcharts are ready, the programmers can plan the coding process
effectively as they know where to begin and where to end, making sure that no steps are omitted. As a
result, error free programs are developed in high level language and that too at a faster rate.
5. Proper Testing and Debugging: By nature, a flowchart helps in detecting the errors in a program,
as the developers know exactly what the logic should be.
6. Appropriate documentation: Flowcharts serve as a good program documentation tool since
normally the programs are developed for users, they can take the help of the program documentation
to know what the program actually does and how to use the program.
Limitations of Flowcharts
1 complex: The major drawback that defines when a program is very large, the flowcharts may
continue for many pages, making them hard to follow.
2. Costly: Drawing flowcharts are viable only if the problem-solving logic is straightforward and not
very lengthy. However, if flowcharts are to be drawn for a hug application, the time and cost factor of
program development may get out of proportion, making it costly.
3. Difficult to modify: Due to its symbolic nature, any changes or modifications to a flowchart usually
requires redrawing the entire logic again, and redrawing a complex flowchart is not a simple task.
4. No update: Usually programs are updated regularly. However, the corresponding update of
flowcharts may not take place, especially in the case of large programs. As a result, the logic used in
the flowchart may not match with the actual program’s logic.

Pseudocode

 Pseudocode is made of two words: pseudo and code. Pseudo means imitation and code refers
to instructions, written in programming language. As the name suggests, it is not a real
programming code, but it models and may even look like programming code.
 It uses plain English statements rather than symbols to represent the processes of a computer
program. It is also known as PDL and main emphasizes on design aspect of a computer
program or structured. English, because usually pseudo code instructions are written in
normal English, but in a structured way.
 If an algorithm is written in English, the description may be at such a high level that it may
prove difficult to analyze the algorithm and then to transform it into actual code.
 Therefore, the goal of writing pseudo code is to provide a high-level description of an
algorithm, which facilitates analysis and eventual coding, but at the same time suppresses
many of the details that are insignificant.
Eg. The pseudocode given below calculates the area of a rectangle.

PROMPT the user to enter the height of the rectangle

PROMPT the user to enter the width of the rectangle

COMPUTE the area by multiplying the height with width

DISPLAY the area

STOP

Pseudocode uses some keywords to denote programming processes which are as follows:
 Input: READ, OBTAIN, GET and PROMPT
 Output: PRINT, DISPLAY and SHOW
 Compute: COMPUTE, CALCULATE and DETERMINE
 Initialize: SET and INITIALISE
 Add one: INCREMENT

Guidelines of Pseudo code

 Statements should be written in simple English and should be programming language


independent. Since pseudocodes only describe the logic plan to develop a program, it is
not programming.
 Steps must be understandable, and when the steps are followed, they must produce a
solution to the specified problem.
 It should be concise.
 Each instruction should be written in a separate line and each statement in pseudocode
should express just one action for the computer.
 Capitalize keywords such as READ, PRINT, and so on.
 Each set of instructions is written from top to bottom, with only one entry and one exit.
 It should allow for easy translation from design to coding in programming language.

Advantages of pesudocode

 Language independent, it can be used by most programmers.


 Easier to develop a program from a pseudocode than with a flowchart.
 Often, it is easy to translate pseudocode into a programming language, a step which can
be accomplished by less experienced programmers.
 Unlike flowcharts, pseudocode is compact and does not tend to run over many pages. It’s
simple structure and readability makes is easier to modify.
Limitations of pseudocode

 It does not provide visual representation of the program’s logic.


 There are no accepted standards for writing pseudocodes.
 Pseudocode cannot be compiled and executed, and there is no real formatting or syntax rules.

Algorithm for calculate factorial value of


a number:
step 1. Start
step 2. Read the number n
step 3. [Initialize]
        i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
[process finish of calculate the factorial value of a number]

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with arrows. This diagrammatic representation can give
a step-by-step solution to a given problem.

Example2 : Determine and Output Whether Number N is Even or Odd


Algorithm: Step 1: Read number N,

 Step 2: Set remainder as N modulo 2,

 Step 3: If remainder is equal to 0 then number N is even, else number N is odd,

 Step 4: Print output.


Assignment -1 : Write pseudocode for above two examples.
1. Write a pseudo code for finding factorial of a number?
2. Wirte a pseudo code for finding number is even or not?
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.

Based on this structure,


we can sketch a C program.
Example:
/* This program accepts a number & displays it to the user*/
#include<stdio.h>
void main(void)
{
int number;
printf( "Please enter a number: " );
scanf( "%d", &number );
printf( "You entered %d", number );
return 0;
}
Stepwise explanation: #include The part of the compiler which actually gets your program from the
source file is called the preprocessor. #include #include is a pre-processor directive. It is not really part of
our program, but instead it is an instruction to the compiler to make it do something. It tells the C
compiler to include the contents of a file (in this case the system file called stdio.h). The compiler knows
it is a system file, and therefore must be looked for in a special place, by the fact that the filename is
enclosed in <> characters stdio.h is the name of the standard library definition file for all Standard Input
and Output functions. Your program will almost certainly want to send information to the screen and read
things from the keyboard, and stdio.h is the name of the file in which the functions that we want to use are
defined.
The function we want to use is called printf. The actual code of printf will be tied in later by the linker.
The ".h" portion of the filename is the language extension, which denotes an include file. void This
literally means that this means nothing. In this case, it is referring to the function whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error. Main In this particular
example, the only function in the program is called main. A C program is typically made up of large
number of functions. Each of these is given a name by the programmer and they refer to each other as the
program runs.C regards the name main as a special case and will run this function first i.e. the program
execution starts from main. A parameter to a function gives the function something to work on.
{ (Brace) This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every
open brace there must be a matching close one. Braces allow us to group pieces of program together,
often called a block. A block can contain the declaration of variable used within it, followed by a
sequence of program statements. In this case the braces enclose the working parts of the function main.
;( semicolon) The semicolon marks the end of the list of variable names, and also the end of that
declaration statement. All statements in C programs are separated by ";" (semicolon) characters. The ";"
character is actually very important. It tells the compiler where a given statement ends. If the compiler
does not find one of these characters where it expects to see one, then it will produce an error.
scanf In other programming languages, the printing and reading functions are a part of the language. In C
this is not the case; instead they are defined as standard functions which are part of the language
specification, but are not a part of the language itself. The standard input/output library contains a number
of functions for formatted data transfer; the two we are going to use are scanf (scan formatted) and printf
(print formatted).
printf The printf function is the opposite of scanf. It takes text and values from within the program and
sends it out onto the screen. Just like scanf, it is common to all versions of C and just like scanf, it is
described in the system file stdio.h.The first parameter to a printf is the format string, which contains text,
value descriptions and formatting instructions.
FILES USED IN A C PROGRAM
Source File- This file contains the source code of the program. The file extension of any c file is .c. The
file contains C source code that defines the main function & maybe other functions.
Header File- A header file is a file with extension .h which contains the C function declarations and
macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o, meaning relocatable
format machine code that is usually not directly executable. Object files are produced by an assembler,
compiler, or other language translator, and used as input to the linker, which in turn typically generates an
executable or library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker links the various object
files to produce a binary file that can be directly executed.
Types of error
a) Syntax Errors: Errors in syntax (grammar) of the program. Errors that occur when you violate the
rules of writing C/C++ syntax are known as syntax errors. This compiler error indicates something that
must be fixed before the code can be compiled. All these errors are detected by compiler and thus are
known as compile-time errors. i) parse error ii)implicit declaration iii) no matching function
iv)Unsatisfied symbols v)incomplete type vi)cannot call member function vii)bad argument viii)cannot
allocate an object.
 
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it

1. b) Semantic Errors: Errors in the meaning of the program. This error occurs when the statements
written in the program are not meaningful to the compiler.

2. c) Logical Errors: Errors in logic of the program. Compiler cannot diagnose these kinds of errors. On
compilation and execution of a program, desired output is not obtained when certain input values
are given. These types of errors which provide incorrect output but appears to be error free are
called logical errors. These are one of the most common errors done by beginners of programming.  
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.  

d) Runtime Errors: i) Insufficient memory ii)Floating exception Errors which occur during program
execution(run-time) after successful compilation are called run-time errors. One of the most common
run-time error is division by zero also known as Division error. These types of error are hard to find as
the compiler doesn’t point to the line at which the error occurs. In the given example, there is Division
by zero error. This is an example of run-time error i.e errors occurring while running the program.

ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with programming, we
should be acquainted with the basic elements that build the language. Character Set Communicating with
a computer involves speaking the language the computer understands. In C, various characters have been
given to communicate. Character set in C consists of;
Keywords: Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to
the keyword, which is not allowed by the computer. There are only 32 keywords available in C. Below
figure gives a list of these keywords for your ready reference.

Identifier In the programming language C, an identifier is a combination of alphanumeric characters, the


first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any
numeric digit, or the underline. Two rules must be kept in mind when naming identifiers. 1. The case of
alphabetic characters is significant. Using "INDEX" for a variable is not the same as using "index" and
neither of them is the same as using "InDeX" for a variable. All three refer to different variables. 2. As C
is defined, up to 32 significant characters can be used and will be considered significant by most
compilers. If more than 32 are used, they will be ignored by the compiler.
Data Type In the C programming language, data types refer to a domain of allowed values & the
operations that can be performed on those values. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. There are 4 fundamental data types in C,
which are- char, int, float &, double. Char is used to store any single character; int is used to store any
integer value, float is used to store any single precision floating point number & double is used to store
any double precision floating point number. We can use 2 qualifiers with these basic types to get more
types. There are 2 types of qualifiersSign qualifier- signed & unsigned Size qualifier- short & long The
data types in C can be classified as follows:
Rules for Constructing Real Constants:
Real constants are often called Floating Point constants. The real constants could be written

 in two forms—Fractional form and Exponential form. A real constant must have at least one digit.

 It must have a decimal point.

 It could be either positive or negative.

 Default sign is positive.

 No commas or blanks are allowed within a real constant. Ex. +325.34, 426.0, -32.76, -
 48.5792 Rules for constructing real constants expressed in exponential form: The mantissa part and the
exponential part should be separated by a letter e.

 The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative integer. Default sign is
positive. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

 Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5


Rules for Constructing Character Constants:
A character constant is a single alphabet, a single digit or a single special symbol enclosed within single
inverted commas.
The maximum length of a character constant can be 1 character.
Ex.: ‗M‘, ‗6‘, ‗+‘.

VARIABLES
Variables are names that are used to store values. It can take different values but one at a time. A data
type is associated with each variable & it decides what values the variable can take. Variable declaration
requires that you inform C of the variable's name and data type. Syntax – data type variable name; Eg:int
page_no; char grade; float salary; long y;
Declaring Variables: There are two places where you can declare a variable: After the opening brace of a
block of code (usually at the top of a function) Before a function name (such as before main() in the
program)
Consider various examples:
Initialization of Variables When a variable is declared, it contains undefined value commonly known as
garbage value. If we want we can assign some initial value to the variables during the declaration itself.
This is called initialization of the variable. Eg-int pageno=10;
Expressions An expression consists of a combination of operators, operands, variables & function calls.
An expression can be arithmetic, logical or relational. Here are some expressions: a+b
– arithmetic operation a>b- relational operation a == b
- logical operation func (a,b) – function call Statements Statements are the primary building blocks of a
program. A program is a series of statements with some necessary punctuation. A statement is a complete
instruction to the computer. In C, statements are indicated by a semicolon at the end. a semicolon is
needed to identify instructions that truly are statements.
Object and executable files

Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension. Which is  un-
compiled (when written for the first time or whenever a change is made in it and saved).
Object code is the output of a compiler after it processes the source code. The object code is usually
a machine code, also called a machine language, which can be understood directly by a specific type
of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or PowerPC. However, some
compilers are designed to convert source code into an assembly language or some other another
programming language. An assembly language is a human-readable notation using
the mnemonics  symbolic name for a single executable machine language instruction called an opcode)
in the ISA ( Instruction Set Architecture) of that particular CPU .

Executable (also called the Binary) is the output of a linker after it processes the object code. A
machine code file can be immediately executable (i.e., runnable as a program), or it might
require linking with other object code files (e.g. libraries) to produce a complete executable program.
Linker also contain other object files and libraries.
A linker is special program that combines the object files, generated by compiler/assembler, and other
pieces of codes to originate an executable file have. exe extension. In the object file, linker searches
and append all libraries needed for execution of file. It regulates the memory space that will hold the
code from each module. It also merges two or more separate object programs and establishes link.

The loader is special program that takes input of object code from linker, loads it to main memory, and
prepares this code for execution by computer. Loader allocates memory space to program. Even it
settles down symbolic reference between objects. It is in charge of loading programs and libraries in
operating system. The embedded computer systems don’t have loaders. In them, code is executed
through ROM.

LINKER LOADER
Whereas main objective of
The main function of Linker is to generate Loader is to load executable files
1 executable files. to main memory.
And the loader takes input of
The linker takes input of object code executable files generated by
2 generated by compiler/assembler. linker.
Loading can be defined as
Linking can be defined as process of process of loading executable
combining various pieces of codes and codes to main memory for further
3 source code to obtain executable code. execution.
Loaders are of 4 types: Absolute,
Linkers are of 2 types: Linkage Editor and Relocating, Direct Linking,
4 Dynamic Linker. Bootstrap.
Another use of linker is to combine all object It helps in allocating the address
5 modules. to executable codes/files.

Unit 2
Arithmetic expressions and precedence (2 lectures)
Conditional Branching and Loops (6 lectures)
Writing and evaluation of conditionals and consequent branching (3 lectures)
Iteration and loops (3 lectures)
Arithmetic expressions and precedence (part of syllabus)
C has a wide range of operators. An arithmetic expression is composed of operators and operands.
Operators act on operands to yield a result. Commonly used arithmetic operators are +, -, *, / and %. The
plus sign (+) is used to add two values, the minus sign (-) to subtract one value from another, the
asterisk(*) to multiply two values, the division (/) to divide a value and the modulus (%) to obtain the
reminder of integer division. These are known as binary operators since they operate on two values or
variables.

When an expression contains only integral operands, then it is known as pure integer expression when it
contains only real operands, it is known as pure real expression, and when it contains both integral and
real operands, it is known as mixed mode expression.

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence and associativity of
operators decide the order of the evaluation of individual operations.

o When both the operands (a,b) are of type integer, then arithmetic will be performed, and the result
of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional
part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of the
operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic
will be performed. In this case, the first operand is converted into a real operand, and then
arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first
value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.

Following are examples of arithmetic expressions :


result = x - y;
total = principle + interest;
numsquare = x * x;
celcius = (fahrenheit - 32) / 1.8
Notice the equal sign (=) in the above expressions, it is known as the assignment operator. It assigns the
value on the right hand side of the equal sign to the variable on the left hand side. In the last expression,
parentheses are used to perform a certain operation first. This is because in C, operators follow a
precedence rule. *, / and % have a higher precedence over + and -. Hence to override the precedence,
parentheses should be used. Expressions having operators of the same precedence are generally evaluated
from left to right. Another point to note is that in an expression which involves division, care should be
taken to avoid a division by zero, since this results in infinity or an abnormal value.
#include main()
{
int var1 = 10;
int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;
printf("Sum of var1 and var2 is %d\n", result);
result = var3 * var3;
printf("Square of var3 is %d\n", result);
result = var2 +var3 * var4;
/* precedence */ printf("var2 + var3 * var4 =%d\n", result);
}

Unary operator A unary operator is one which operates on one value or operand. The minus sign (-) plays
a dual role, it is used for subtraction as a binary operator and for negation as a unary operator. This
operator has a precedence higher than the rest of the arithmetic operators. result = -x * y; in the above
expression, if x has a value 20 and y has a value 2, then result will contain a negative value of 40 which is
-40.
In C, there are increment (++) and decrement (--) operators. These can be pre-fixed or post-fixed. When
these are pre-fixed to a variable in an expression, then the value is computed before the expression is
evaluated. When these are post-fixed, the value is computed after the expression is evaluated.
/* Usage of pre-fixing and post-fixing the increment operator */
#include
main()
{
int x = 10;
printf("Value of x after pre-fixing ++ is %d\n", ++x);
printf("Value of x after post-fixing ++ is %d\n",x++);
}
The above program will yield the following output: Value of x after pre-fixing ++ is 11 is 11 Notice that
even after we post-fix an increment operator to x, we still get the result as 11. This is because x is
evaluated before the increment operation occurs.
Comma operator Comma can be used in an expression. Each comma separated expression is evaluated
and the value of the rightmost expression will be returned. Consider the following example :
/* Comma seperated expressions */
#include
main()
{
int Total, Val, Count;
Total = 100;
Val = 10;
Count = 50;
Total =(Val++,Count-2);
printf("%d\n", Total);
}
The above program displays a value of 48, since the last expression Count-2 is considered last. If the
parentheses had been absent, then the value in Val before increment would have been returned to Total,
this is because the assignment operator has a higher precedence then the comma operator.

Relational Expressions (for study)

o A relational expression is an expression used to compare two operands.


o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string value.
o The result of the relational expression can be either zero or non-zero value. Here, the zero value is
equivalent to a false and non-zero value is equivalent to true.

x%2 = This condition is used to check whether the x is an even number or not. The relational expression
=0 results in value 1 if x is an even number otherwise results in value 0.

Here is the table of relational operators in C language

Operators Operator Name

== Equal to

> Greater than

< Less than


Operators Operator Name

!= Not equal to

>= Greater than or equal to

<= Less than or equal to

Logical Expressions

o A logical expression is an expression that computes either a zero or non-zero value.


o It is a complex test condition to take a decision.

x > 10 || y It is a test condition used to check whether x is greater than 10 or y is less than 11. The result of the
<11 test condition is true if either of the conditions holds true value.

Conditional Expressions

o A conditional expression is an expression that returns 1 if the condition is true otherwise 0.


o A conditional operator is also known as a ternary operator.

o The Syntax of Conditional operator

o Suppose exp1, exp2 and exp3 are three expressions.

o exp1 ? exp2 : exp3

o The above expression is a conditional expression which is evaluated on the basis of the value of
the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.

Operators Precedence and associatively are two characteristics of operators that determine the
evaluation order of sub-expressions in absence of brackets
For example: Solve 100 + 200 / 10 - 3 * 10
1) Associativity is only used when there are two or more operators of same precedence.  
The point to note is associativity doesn’t define the order in which operands of a single operator are
evaluated. For example, consider the following program, associativity of the + operator is left to right,
but it doesn’t mean f1() is always called before f2(). The output of the following program is in-fact
compiler dependent.
2) All operators with the same precedence have same associativity 
This is necessary, otherwise, there won’t be any way for the compiler to decide evaluation order of
expressions which have two operators of same precedence and different associativity. For example +
and – have the same associativity.

3) Precedence and associativity of postfix ++ and prefix ++ are different 


Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of
postfix ++ is left to right and associativity of prefix ++ is right to left.

4) Comma has the least precedence among all operators and should be used carefully
5) There is no chaining of comparison operators in C 
In Python, expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining doesn’t
happen in C. The output of following program is “FALSE”. 

Description   
Operator  
Associativity
 
()  Parentheses (function call) (see Note 1) 
[]  Brackets (array subscript) 
.  Member selection via object name 
->  Member selection via pointer 
++ — Postfix increment/decrement (see Note 2) left-to-right
++
—  Prefix increment/decrement 
+ – Unary plus/minus 
! ~ Logical negation/bitwise complement 
(type)  Cast (convert value to temporary value of type) 
*  Dereference 
&  Address (of operand) 
sizeof Determine size in bytes on this implementation right-to-left
*  /  % Multiplication/division/modulus left-to-right
+  – Addition/subtraction left-to-right
<<  >> Bitwise shift left, Bitwise shift right left-to-right
<  <= Relational less than/less than or equal to 
>  >= Relational greater than/greater  than or equal to left-to-right
==  != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
=  Assignment 
+=  -= Addition/subtraction assignment 
*=  /= Multiplication/division assignment 
%=  &= Modulus/bitwise AND assignment 
^=  |= Bitwise exclusive/inclusive OR assignment 
<<=  >>= Bitwise shift left/right assignment right-to-left
, Comma (separate expressions) left-to-right

It is good to know precedence and associativity rules, but the best thing is to use brackets, especially
for less commonly used operators (operators other than +, -, *.. etc). Brackets increase the readability
of the code as the reader doesn’t have to see the table to find out the order.
A Bitwise And operator is represented as ‘&’ and a logical operator is represented as ‘&&’. The
following are some basic differences between the two operators.
a) The logical and operator ‘&&’ expects its operands to be boolean expressions (either 1 or 0) and
returns a boolean value. 
The bitwise and operator ‘&’ work on Integral (short, int, unsigned, char, bool, unsigned char, long)
values and return Integral value. 
 If an integral value is used as an operand for ‘&&’ which is supposed to work on boolean values, the
following rule is used in C. 
…..Zero is considered as false and non-zero is considered as true.
c) The ‘&&’ operator doesn’t evaluate the second operand if the first operand becomes false. Similarly
‘||’ doesn’t evaluate the second operand when first operand becomes true. The bitwise ‘&’ and ‘|’
operators always evaluate their operands.  

Inclusive OR allows both possibilities as well as either of them. So, if either A or B is True, or if both are True,
then the statement value is True whereas Exclusive OR only allows one possibility. So if either A or B is true,
then and only then is the value True. If both A and B are True, even then the statement's value will be False.
Example for Exclusive OR: At a restaurant, you are offered a coupon which entitles you to eat either a
Sandwich OR a Burger. This is an exclusive OR statement in English language. You can choose either one of
them, but not both.

**A program is nothing but the execution of sequence of one or more instructions. 
Quite often, it is desirable to alter the sequence of the statements in the program depending upon certain
circumstances. (i.e., we have a number of situations where we may have to change the order of execution
of statements based on certain conditions)  
Based on application, it is necessary / essential

(i) To alter the flow of a program 


(ii) Test the logical conditions 
(iii) Control the flow of execution as per the selection these conditions can be placed in the program using
decision-making statements.  

Conditional Branching and Loops (6 lectures)


“C” SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS. 
Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform tasks
repeatedly or to jump from one section of code to another.

1. Decision making statements


a) Simple if Statement
b) if – else Statement 
c) Nested if-else statement
d) else – if Ladder 
e) switch statement  

2. Loop control statements


a) for Loop
b) while Loop
c) do-while Loop 
 
3. Unconditional control statements
a) goto Statement 
b) break Statement 
c) continue Statement  
d) return statement

Conditional Branching:
It includes the statements which work on checking the condition of a given expression to execute the
code. They are:

1. Decision Making Statements

Decision making statements allow you to decide the order of execution of specific statements in your
program. You can set up a condition and tell the compiler to take a particular action if the condition is
met. In case the condition is not met, you can instruct the compiler to execute a different block of code.
Used to execute or skip some set of instructions based on given condition.
Number of decision making statements are supported in C language are as follows:

1. If
2. If-else
3. Nested if
4. Switch
5. Else-if ladder (used to test set of conditions in sequence).

1.1) Simple “if” statement :

“if” statement is a powerful decision making statement, and is used to control the flow of execution of
statements.
  Syntax :
if (Condition or test expression)
Statement;
Rest of the program

(OR)

if (Condition or test expression)


{
Statement;
}

Rest of the program;


It is basically a “Two-way” decision statement (one for TRUE and other for FALSE)
It has only one option. The statement as executed only when the condition is true. In case the condition is
false the compiler skips the lines within the “if Block”. The condition is always enclosed within a pair of
parenthesis i.e. ( ) , The conditional statement should not terminated with Semi-colons (ie ;) The
Statements following the “if”-statement are normally enclosed in Curly Braces {}. The Curly Braces
indicates the scope of “if” statement. The default scope is one statement. But it is good practice to use
curly braces even with a single statement. The statement block may be a single statement or a group of
statements. If the Test Expression / Conditions are TRUE, the Statement Block will be executed and
executes rest of the program. If the Test Expression / Condition are FALSE, the Statement Block will be
skipped and rest of the program executes next.

Example : Program: Write a program to check equivalence of two numbers. Use “if” statement.
# include<stdio.h>
# include<conio.h>
void main( )
{
int m,n;
clrscr( );
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &m, &n);
if((m-n)==0)
printf(“\n two numbers are equal”);
getch();
}

Output :
Enter two numbers: 5 5
Two numbers are equal.

1. (2) “if-else” Statement :

It is observed that the “if” statement executes only when the condition following if is true. It does nothing
when the condition is false. In if-else either True-Block or False – Block will be executed and not both.
The “else” Statement cannot be used without “if”.
  Syntax :
if ( Test Expression or Condition )
{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}

It is observed that the “if” statement executes only when the condition following if is true. It does nothing
when the condition is false. In if-else either True-Block or False – Block will be executed and not both.
The “else” Statement cannot be used without “if”.
Flow chart :

Eg. Program: Write a program to print the given number is even or odd.


# include<stdio.h>
# include<conio.h>
main( )
{
int n;
clrscr( );
printf(“Enter a number :”);
scanf(“%d”, &n);
if( (n%2)==0 )
printf(“\n The given number is EVEN ”);
else
printf(“\n The given number is ODD ”);
getch( );
}
Output :
Run 1 :
Enter a number : 24
The given number is EVEN
Run 2: /* that means one more time we run the program */
Enter a number : 17
The given number is ODD
 
1. 3 Nested “if–else” Statement :

Using of one if-else statement in another if-else statement is called as nested if-else control statement.
When a series of decisions are involved, we may have to use more than one if-else statement in nested
form.
  Syntax :
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement-4;
}
} /* end of outer if-else *

 
Flow chart :
Eg. Program: Program to select and print the largest of the three float numbers using nested “if else”
statements.
# include<stdio.h>
# include<conio.h>
main( ) {
float a,b,c;
printf(“Enter Three Values:”);
scanf(“%f%f%f”, &a, &b, &c);
printf(“\n Largest Value is:”) ;

if(a>b) {
if(a>c)
printf(“ %f ”, a);
else
printf(“ %f ”, c);
}
else {
if (b>c)
printf(“ %f ”, b);
else
printf(“ %f ”, c);
}

getch();
}

Output :
Run 1: Enter three values: 9.12 5.34 3.87
    Largest Value is: 9.12
Run 2: Enter three values: 45.781 78.34 145.86
    Largest Value is: 145.86
1.(4) The “else – if” Ladder :

This is another way of putting if‘s together when multiple decisions are involved. A multipath decision is
a chain of if‘s in which the statement associated with each else is an if. Hence it forms a ladder called
else–if ladder. if else-if, statement is used to execute one code from multiple conditions.
  Syntax :
if (Test Condition -1)
{
Statement -1;
}
else if ( Test Condition -2)
{
Statement -2;
}
else if ( Test Condition -3)
{
Statement -3;
}
:
:
:
:
else if ( Test Condition –n)
{
Statement –n;
}

else
{
default statement;
}
Rest of the Program Statements-X;

The above construction is known as else if ladders. The conditions are evaluated from top to bottom. As
soon as a true condition is found, the statement associated with it is executed and The control is
transferred to the Rest of the Program Statement–X (skipping rest of the ladder). When all the “n”
conditions become false, then the final else containing the default statement will be executed.
Flow chart :
Eg. Program: Write a program to read three numbers and find the largest one by using “else-if” ladder.
# include<stdio.h>
# include<conio.h>
void main( )
{
int a, b, c
clrscr ( ) ;
printf(“Enter 1st number:”);
scanf(“%d”, &a);
printf(“Enter 2nd number:”);
scanf(“%d”, &b);
printf(“Enter 3rd number:”);
scanf(“%d”, &c);
if ((a>b) && (a>c))
printf(“Highest Number is: %d”, a);
else if ((b>a) && (b>c))
printf(“Highest Number is: %d”, b);
else
printf(“Highest Numbers is: %d”, c);
getch( );
}

Output :
Enter 1st number: 52
Enter 2nd number: 90
Enter 3rd number: 74
Highest Numbers is: 90
1.(5) The “switch-case” Statement :
Switch is another conditional control statement used to select one option from several options based on
given expression value; this is an alternative to the if-else-if ladder. The switch statement causes a
particular group of statements to be chosen from several available groups. The selection is based upon the
current value of an expression which is included with in the switch statement. The switch statement is a
multi-way branch statement. In a program if there is a possibility to make a choice from a number of
options, this structured selected is useful. The switch statement requires only one argument of int or char
data type, which is checked with number of case options. The switch statement evaluates expression and
then looks for its value among the case constants. If the value matches with case constant, then that
particular case statement is executed. If no one case constant not matched then default is executed. Here
switch, case and default are reserved words or keywords.
Every case statement terminates with colon “:”.
In switch each case block should end with break statement, i.e.
  Syntax :
Switch (variable or expression)
{
Case Constantvalue-1:Block -1;
(Or)
Statement-1;
break;

Case Constantvalue-2:Block -2;


(Or)
Statement-2;
break;
________
________

Case Constant value-n: Block -n;


(Or)
Statement-n;
break;

default: default – block;


}
Flow chart :
Eg. Program: Write a program to provide multiple functions such as 1.Addition, 2.Subtraction,
3.Multiplication, 4. Division, 5.Remainder, 6.Larger out of two, 7. Exit, using “switch” statement.
# include<stdio.h>
# include<conio.h>
main( )
{
int a, b, c, ch;
clrscr ( ) ;
printf(“\t = = = = = = = = = = = = = =”);
printf (“n\t MENU”);
printf(“\n\t= = = = = = = = = = =”);
printf(“\n \t [1] ADDITION” );
printf(“\n \t [2] SUBTRACTION” );
printf(“\n \t [3] MULTIPLICATION” );
printf(“\n \t [4] DIVISION” );
printf(“\n \t [5] REMAINDER” );
printf(“\n \t [6] LARGER OUT OF TWO” );
printf(“\n \t [7] EXIT” );
printf(“\n \t = = = = = = = = = =”);
printf(“ \n\n\t ENTER YOUR CHOICE:”);
scanf(“%d”, &ch);
if(ch <= 6 && ch >=1)
{
printf(“ENTER TWO NUMBERS:”);
scanf(“%d %d”, &a, &b);
}
switch(ch)
{
case 1: c = a+b ;
printf(“ \n Addition: %d”, c);
break;
case 2: c=a-b;
printf(“\n Subtraction: %d”, c);
break;
case 3: c = a* b ;
printf(“\n Multiplication: %d”, c);
break;
case 4: c = a / b;
printf(“\n Division: %d”, c);
break;
case 5: c = a % b;
printf(“ \n Remainder: %d”, c);
break;
case 6: if (a > b)
printf(“\n \t %d is larger than %d”, a, b);
else if (b > a)
printf(“ \n \t %d is larger than %d ”, b, a);
else
printf(“\n \t %d and %d are same”, a, b);
break;
case 7: printf( “ \ n Terminated by choice”);
exit( );
break;
default: printf(“ \ n invalid choice”);
}
getch ( );
}

Output :
=========
      MENU
=========
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[7] EXIT
===============
Enter your choice: 6
Enter two numbers: 8 9
9 is larger than 8
 Branching statements give us code which is optionally executable, depending on the outcome of certain
tests or you can say certain cases which we can define.

Looping statements are used to repetition of a section of code a number of times or until a condition has
been fulfilled.

2. Loop Control Statements In C Language


Loop : A loop is defined as a block of statements which are repeatedly executed for certain number of
times. In other words it iterates a code or group of code many times.

Why use loops in c language

Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s only one
time and repeat the execution 10 times using loop. For example: Suppose that you have to print table of 2
then you need to write 10 lines of code, by using loop statements you can do it by 2 or 3 lines of code
only. Different Loops exists in C programming language are as follows:

2. (1) for Loop :

The for loop works well where the number of iterations of the loop is known before the loop is entered.
The head of the loop consists of three parts separated by semicolons. The first is run before the loop is
entered. This is usually the initialization of the loop variable. The second is a test, the loop is exits when
this returns false. The third is a statement to be run every time the loop body is completed. This is usually
an increment of the loop counter. The 3 actions are
“Initialize expression”, “Test Condition expression” and “updation expression”
The expressions are separated by Semi-Colons (;).
  Syntax :
for (initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}
(i)The initialization sets a loop to an initial value. This statement is executed only once.
(ii) The test condition is a relational expression that determines the number of iterations desired or it
determines when to exit from the loop. For loop continues to execute as long as conditional test is
satisfied. When the condition becomes false the control of the program exits from the body of for loop
and executes next statements after the body of the loop.
(iii) The updation (increment or decrement operations) decides how to make changes in the loop. The
body of the loop may contain either a single statement or multiple statements.

Eg. Program : Print the first five numbers starting from one together with their squares.
#include<stdio.h>
#include<conio.h>
main( )
{
int i;
clrscr( ) ;
for(i = 1; i <6; i++)
printf(“\n Number: %d it’s Square: %d”, i, i*i);
getch( );
}
Output :
Number: 1 it’s Square: 1
Number: 2 it’s Square: 4
Number: 3 it’s Square: 9
Number: 4 it’s Square: 16
Number: 5 it’s Square: 25

Nested “for” loop :

We can also use loop within loops. i.e. one for statement within another for statement is allowed in C. In
nested for loops one or more for statements are included in the body of the loop. * ANSI C allows up to
15 levels of nesting. Some compilers permit even more.
  Syntax :
for( initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}
  Program : The following program is an example of nested for loop.
# include<stdio.h>
# include<conio.h>
main ( )
{
int x, i, j ;
printf(“How many lines stars (*) should be print f? :”);
scanf(“%d”, &x);
for(int i=1; i<=x; i++)
{
for (j=1; j < =i; j++)
{
printf( “*”);
}
printf( “ \n”);
}
getch( );
}

Output :
How many lines stars (*) should be print d ? : 5
*
**
***
**** *
 
2. (2) The “while” loop:

The while is an entry-controlled loop statement (i.e. a condition is checked before executing the body of a
loop). The test condition is evaluated and if the condition is true, then the body of the loop is executed.
The execution process is repeated until the test condition becomes false and the control is transferred out
of the loop. On exit, the program continues with the statement immediately after the body of the loop. The
body of the loop may have one or more statements. The braces are needed only if the body contains two
or more statements. It’s a good practice to use braces even if the body has only one statement. The
simplest of all the looping structures in C is.
  Syntax :
Initialization Expression;
while ( Test Condition)
{
Body of the loop
Updation Expression
}

Eg. Program : To add 10 consecutive numbers starting from 1. Use the while loop.
# include<stdio.h>
# include<conio.h>
main( )
{
int a=1, Sum=0;
while(a<=10)
{
Sum = Sum + a;
a++;

}
printf(“Sum of 1 to 10 numbers is: %d”, sum);
getch( );
}

Output :

Sum of 10 numbers is: 55


  Program : To calculate factorial of a given number use while loop.
# include<stdio.h>
# include<conio.h>
main ( )
{
long int n, fact =1;
clrscr( ) ;
printf( “\n Enter the Number:”);
scanf(“%ld”, &n);

while(n>=1)
{
fact = fact*n;
n--;
}
printf(“ \n factorial of given number is %d”, fact);
getch( );
}

Output :
Enter the Number: 5 /* logic 5 * 4 * 3 * 2 * 1 = 120 */
Factorial of given number is 120
Infinitive while loop

If you pass 1 as a expression in while loop, it will run infinite number of times.
  Syntax :
while(1){
//statements
}

2. (3) The “do-while“ loop :

To execute a part of program or code several times, we can use do-while loop of C language. The code
given between the do and while block will be executed until condition is true. The do-while is an exit-
controlled loop statement (i.e. A condition is checked after executing the body of a loop). Because, in do-
while, the condition is checked at the end of the loop. The do-while loop will execute at least one time
even if the condition is false initially. The do-while loop executes until the condition becomes false.
  Syntax :
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);

 Program : To check whether the given number is prime or not.


# include<stdio.h>
# include<conio.h>
main( )
{
int n, x=2;
clrscr( );
printf( “Enter the number for testing (prime or not”);
scanf(“%d”, &n);
do
{
if(n%x == 0)
{
printf(“ \n the number %d is not prime”, n);
exit(0);
}
x++;
} while ( x < n);
printf(“ \n the number %d is prime”, n);
getch( ) ;
}
Output :
Enter the number for testing (Prime or not): 5
The number 5 is prime.

Infinitive do while loop :

If you pass 1 as a expression in do while loop, it will run infinite number of times. The do-while is an
exit-controlled loop statement. Because, in do-while, the condition is checked at the end of the loop. The
do-while loop will execute at least one time even if the condition is false initially. The do-while loop
executes until the condition becomes false.
  Syntax :
do{
//statements
} while (1);
Ex. #include <stdio.h>

int main () {

/* local variable definition */


int a = 10;

/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

return 0;
}
Output: value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

(3) Unconditional branching is when the programmer forces the execution of a program to jump to
another part of the program. Theoretically, this can be done using a good combination of loops and if
statements. In fact, as a programmer, you should always try to avoid such unconditional branching and
use this technique only when it is very difficult to use a loop.
3. UNCONDITIONAL CONTROL STATEMENT
3. (1) The “break” Statement :
A break statement terminates the execution of the loop and the control is transferred to the statement
immediately following the loop.  i.e., the break statement is used to terminate loops or to exit from a
switch. 
• It can be used within for, while, do-while, or switch statement. 
• The break statement is written simply as break; 
• In case of inner loops, it terminates the control of inner loop only. 

  Syntax :
Jump-statement;
      break;
Jump Statement makes the control jump to another section of the program unconditionally when
encountered. It is usually used to terminate the loop or switch-case instantly. It is also used to escape the
execution of a section of the program.

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Program : The following program is an example of break statement


#include <stdio.h>
#include <conio.h>
void main(){
int i=1;//initializing a local variable
clrscr();
for(i=1;i<=10;i++){
printf("%d ",i);
if(i==5) //if value of i is equal to 5, it will break the loop
{
break;
}
}//end of for loop
getch();
}
Output :
1 2 3 4 5
3. (2) The “continue” Statement

The continue statement is used to bypass the remainder of the current pass through a loop. The loop does
not terminate when a continue statement is encountered. Instead, the remaining loop statements are
skipped and the computation proceeds directly to the next pass through the loop. The continue statement
can be included within a while, do-while, for statement. It is simply written as “continue”. The continue
statement tells the compiler “Skip the following Statements and continue with the next Iteration”. In
“while” and “do” loops continue causes the control to go directly to the test –condition and then to
continue the iteration process. In the case of “for” loop, the updation section of the loop is executed
before test-condition, is evaluated.
  Syntax :
Jump-statement;
      Continue;
The jump statement can be while, do while and for loop.

Program : The following program is an example of break statement.


# include<stdio.h>
void main( )
{
int i=1, num, sum =0;
for(i=0; i < 5; i ++)
{
printf(“ Enter an integer:”);
scanf( “%d”, &num);
if(num < 0)
{
printf(“\nyou have entered a negative number”);
continue ; /* skip the remaining part of loop */
}
sum += num;
}
printf(“The sum of the Positive Integers Entered = % d \ n”, sum);
}

Output :
Enter an integer: 7
Enter an integer: 3
Enter an integer: 10
Enter an integer: 15
Enter an integer: 30
The sum of the positive integers entered = 65

3. (3) The “goto” Statement

C supports the “goto” statement to branch unconditionally from one point to another in the program.
Although it may not be essential to use the “goto” statement in a highly structured language like “C”,
there may be occasions when the use of goto is necessary. The goto requires a label in order to identify
the place where the branch is to be made. A label is any valid variable name and must be followed by a
colon (: ). The label is placed immediately before the statement where the control is to be transferred. The
label can be anywhere in the program either before or after the goto label statement.

During running of a program, when a statement likes “goto begin;” is met, the flow of control will jump
to the statement immediately following the label “begin:” this happens unconditionally. “goto” breaks the
normal sequential execution of the program. If the “label:” is before the statement “goto label;” a loop
will be formed and some statements will be executed repeatedly. Such a jump is known as a “backward
jump”. If the “label:” is placed after the “goto label;” some statements will be skipped and the jump is
known as a “forward jump”.
  Program : Write a program to detect the entered number as to whether it is even or odd. Use goto
statement.
3. (4) Return Statement :

The return statement terminates the execution of a function and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return statement
can also return a value to the calling function.
  Syntax :
Jump-statement:
return expression
Notes: Conditional branch is happened based on some condition like if condition in C. Transfer of control
of the program will depend on the outcome of this condition.
Uncoonditional branching occurs without any condition like goto statement.
Loops like For, while use both of these branching techniques. It employs condition checking(For
conditional branching) and once one loop is complete, control is automatically transfered to the start of
the loop(Unconditional branching).

In the case of computer programming, a data type refers to a classification that specifies the
given interpreter or compiler which type of data must be used. There are typically two major
types of data:

 Derived Data Type


 Fundamental/ Primitive Data Type

What are Fundamental Data Types?


All the variables present in C++ and C have associated data types. Every data type needs a
different amount of memory. Also, each of them has specific operations that one can perform
over them.

What are Derived Data Types?


This type of data type is generally used by a user itself, for example, a structure or a class in the
C++ language. The Derived Data Types include Pointers, Enumeration, Union, Class, Structures,
Arrays, etc. These are just a few examples.

Difference Between Fundamental Data Types and Derived Data Types


Here are the differences present between Fundamental Data Types and Derived Data Types:
Parameters Fundamental Data Types Derived Data Types

Type of A fundamental data type is very basic. It A derived data type is basically an
Complication is also known as a primitive data type. aggregation of the fundamental
data type.

Examples Void, Float, Integer, and Character are Structures, Unions, Arrays, and
fundamental data types. Pointers are the derived data types.

Specification of It uses Character in the form of char, The Derived Data Types make use
Elements Unsigned char, Signed char, etc., for the of pointers for storing the address
characters present in the Fundamental of the available variables.
Data Type.

Storage of Data It uses integers for the integers with no It makes use of arrays to contain a
decimal digits. We can classify it as similar data type.
unsigned and signed. It is further
classified as the int, long int, and short
int.

Use We use void when we don’t require the It is just like a structure, but the
return value. difference is that all the members
present in a union share the very
same location of memory.

Grouping of We use floats for the decimal numbers. We use a structure for grouping all
Values The classification occurs as double, float, the different types of available
and long double. items into one single type.

C was developed as a language to write the UNIX operating system cleanly. The earlier version of UNIX that
Ken Thompson wrote was in a language called B which was in turn a simplified version of a language called
BCPL (which stood for Basic Combined Programming Language). When Dennis Ritchie joined the team, he
set on to develop a better language than B which will eventually be used as a successor of B. So he named the
language C.

Unit 3
Arrays, Arrays (1-D, 2-D), Character arrays and Strings (6 lectures)

C Array

An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Contiguous memory allocation is basically a method in which a single contiguous
section/part of memory is allocated to a process or file needing it. Because of this all the
available memory space resides at the same place together, which means that the freely/unused
available memory partitions are not distributed in a random fashion here and there across the
whole memory space. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc. It also has the capability to
store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its index
number. C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different variables for the
marks in the different subject. Instead of that, we can define an array which can store the marks
in each subject at the contiguous memory locations. By using the array, we can access the
elements easily. Only a few lines of code are required to access the elements of the array.

Properties of Array

The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element
is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantages of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantages of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array

We can declare an array in the c language in the following way.

1. data_type array_name[array_size];  

Now, let us see the example to declare the array.


1. int marks[5];  

Here, int is the data_type, marks are the array_name, and 5 is the array_size

Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.

1. marks[0]=80;//initialization of array  
2. marks[1]=60;  
3. marks[2]=70;  
4. marks[3]=85;  
5. marks[4]=75;  

C array example
1. #include<stdio.h>  
2. int main(){      
3. int i=0;    
4. int marks[5];//declaration of array       
5. marks[0]=80;//initialization of array    
6. marks[1]=60;    
7. marks[2]=70;    
8. marks[3]=85;    
9. marks[4]=75;    
10. //traversal of array    
11. for(i=0;i<5;i++){      
12. printf("%d \n",marks[i]);    
13. }//end of for loop     
14. return 0;  
15. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define the size. So it may also be written as the
following code.

1. int marks[]={20,30,40,50,60};  

Let's see the C program to declare and initialize the array in C.

1. #include<stdio.h>  
2. int main(){      
3. int i=0;    
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array    
5.  //traversal of array    
6. for(i=0;i<5;i++){      
7. printf("%d \n",marks[i]);    
8. }    
9. return 0;  
10. }    

Output

20
30
40
50
60

C Array Example: Sorting an array

In the following program, we are using bubble sort method to sort the array in ascending order.

1. #include<stdio.h>    
2. void main ()    
3. { 
4.     int i, j,temp;     
5.     int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};     
6.     for(i = 0; i<10; i++)    
7.     {    
8.         for(j = i+1; j<10; j++)    
9.         {    
10.             if(a[j] > a[i])    
11.             {    
12.                 temp = a[i];    
13.                 a[i] = a[j];    
14.                 a[j] = temp;     
15.             }     
16.         }     
17.     }     
18.     printf("Printing Sorted Element List ...\n");    
19.     for(i = 0; i<10; i++)    
20.     {    
21.         printf("%d\n",a[i]);    
22.     }    
23. }     

Program to print the largest and second largest element of the array.

1. #include<stdio.h>  
2. void main ()  
3. {  
4.     int arr[100],i,n,largest,sec_largest;  
5.     printf("Enter the size of the array?");  
6.     scanf("%d",&n);  
7.     printf("Enter the elements of the array?");  
8.     for(i = 0; i<n; i++)  
9.     {  
10.         scanf("%d",&arr[i]);  
11.     }  
12.     largest = arr[0];  
13.     sec_largest = arr[1];  
14.     for(i=0;i<n;i++)  
15.     {  
16.         if(arr[i]>largest)  
17.         {  
18.             sec_largest = largest;  
19.             largest = arr[i];  
20.         }  
21.         else if (arr[i]>sec_largest && arr[i]!=largest)  
22.         {  
23.             sec_largest=arr[i];  
24.         }  
25.     }  
26.     printf("largest = %d, second largest = %d",largest,sec_largest);  
27.       
28. }  

You might also like