0% found this document useful (0 votes)
2 views

Introduction to Problem Solving

The document is an introduction to the course CSC 102, focusing on problem-solving in computer science. It covers various topics including computer systems, computing environments, computer languages, algorithms, flowcharts, and the C programming language. Each study session includes learning outcomes, self-assessment questions, and references for further reading.

Uploaded by

klopienclaudia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Introduction to Problem Solving

The document is an introduction to the course CSC 102, focusing on problem-solving in computer science. It covers various topics including computer systems, computing environments, computer languages, algorithms, flowcharts, and the C programming language. Each study session includes learning outcomes, self-assessment questions, and references for further reading.

Uploaded by

klopienclaudia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 198

Introduction to Problem Solving CSC 102

Introduction to Problem Solving - CSC 102

Page 2 of 198
Introduction to Problem Solving - CSC 102

miva open university

Headquarters

Plot 1059 O.P. Fingesi Road,

Utako, Abuja

Page 3 of 198
Introduction to Problem Solving - CSC 102

Course Development Team

Content Editor: Jimin Wuese BSc (Edu) Mathematics/Statistics

Language Editor: Udochi Obiukwu MA English Language

Instructional Designer: Dr Yakub Saheed PhD

Page 4 of 198
Introduction to Problem Solving - CSC 102

Table of Contents

Table of Contents 5
List of Figures 14
List of Tables 14
Study Session 1: Computer Systems 16
Introduction 16
Learning Outcomes (LOs) 16
1.1 Computer Systems 16
1.2 Hardware 17
1.2.1 Primary memory 18
Cache memory: 18
1.2.2 Secondary Memory: 18
Magnetic Storage: 19
Optical Storage: 19
1.3 Computer Software 19
1.3.1 System Software 19
1.3.2 Application software 20
Conclusion 21
Summary 22
Self-Assessment Questions (SAQ) 22
Self-Assessment Answers (SAA) 22
Tutor-Marked Assignment 23
References/Further Reading 23
Study Session 2: Computing Environment 25
Introduction 25
Learning Outcomes (LOs) 25
2.1 Computing Environments 25
2.1.1 Personal Computing Environment 26

Page 5 of 198
Introduction to Problem Solving - CSC 102

2.1.2 Time-Sharing Environment 26


2.1.3 Client/Server Environment 27
2.1.4 Distributed Computing 28
Conclusion 29
Summary 29
Self-Assessment Questions (SAQ) 29
Self-Assessment Answers (SAA) 30
Tutor-Marked Assignment 31
References/Further Reading 31
Study Session 3:Computer Languages 33
Introduction 33
Learning Outcomes (LOs) 33
3.1 Computer Languages 33
3.1.1 Machine Language 34
Advantages of machine language 34
Disadvantages of machine languages 34
3.1.2 Symbolic Languages (or) Assembly Language 35
Advantages of Assembly Language 36
Disadvantages of Assembly Language 36
3.1.3 High-Level Languages 36
Advantages of High-level language 37
Disadvantages of High-Level Language 37
3.1.4 Difference between Machine, Assembly, High-Level Languages
38
3.2 Language Translators 38
3.2.1 Comparison between a Compiler and Interpreter 39
Conclusion 40
Summary 40
Self-Assessment Questions (SAQ) 40
Self-Assessment Answers (SAA) 41
Tutor-Marked Assignment 42
Page 6 of 198
Introduction to Problem Solving - CSC 102

References/Further Reading 42
Study Session 4: Procedure (Steps Involved in Problem Solving) 44
Introduction 44
Learning Outcomes (LOs) 45
4.1 Procedure (Steps involved in Problem Solving) 45
4.2 Algorithm 46
4.2.1 Steps involved in algorithm development 47
Example 49
4.2.2 Algorithms for Simple Problem 49
Conclusion 54
Summary 54
Self-Assessment Questions (SAQ) 55
Self-Assessment Answers (SAA) 55
Tutor-Marked Assignment 59
References/Further Reading 59
Study Session 5: Flowchart 61
Introduction 61
Learning Outcomes (LOs) 61
5.1 Flowchart 62
5.1.1 Advantages of Flowcharts 62
5.1.2 Differences between Algorithm and Flowchart 63
5.1.3 Symbols used in a flowchart 63
5.1.4 Simple Problems solved using FlowChart 66
Pseudocode 70
Conclusion 71
Summary 71
Self-Assessment Questions (SAQ) 71
Self-Assessment Answers (SAA) 72
Tutor-Marked Assignment 74
References/Further Reading 74
Study Session 6: Features of C 76
Page 7 of 198
Introduction to Problem Solving - CSC 102

Introduction 76
Learning Outcomes (LOs) 76
6.1 Features of C language 77
6.2 Character Set 77
6.3 Structure of a C-Program 79
6.4 Data types in C language. 81
6.4.1 Basic Data Types 82
6.5 Tokens in C 83
6.5.1 Constant/Literals: 84
Numeric Constants: 84
Integer Constants 84
A decimal integer constant is characterised by the
following properties: 85
An octal integer constant is characterised by the following
properties: 85
An hexadecimal integer constant is characterised by the
following properties: 86
Real Constants 87
Fractional Form 87
Exponential Form 88
Character Constants 90
String Constants 90
6.5.2 Reserved Words/Keywords 91
6.5.3 Delimiters 92
6.5.4 Variables / Identifiers 92
Rules for naming a variable:- 93
Declaration of variables: 93
6.6 Operators 93
6.6.1 Arithmetic Operators 94
Operator Meaning 94
6.6.2 Relational Operators 95

Page 8 of 198
Introduction to Problem Solving - CSC 102

Operator Meaning 95
Examples : 95
6.6.3 Logical Operators 96
Logical And (&&): 96
Example: 97
Logical OR: 97
Example: 97
Logical NOT: 98
Example: 98
6.6.4 Assignment Operator 98
Example: 99
Multiple assignment 99
Example: 99
Example: 100
6.6.5 Increment & Decrement Operator 100
Example 1: 101
Example 2: 101
6.6.6 Conditional operator (or) Ternary operator (? :) 101
Example: 102
6.6.7 Bit wise Operator 102
The logical Bitwise Operator 103
Example: 104
The Bitwise shift Operations: 104
Example: 105
Example: 105
Bit wise complement: 106
6.6.8 Comma Operator 106
Example : 106
Size of operator: 106
Example : 107
Conclusion 107
Page 9 of 198
Introduction to Problem Solving - CSC 102

Summary 107
Self-Assessment Questions (SAQ) 108
Self-Assessment Answers (SAA) 108
Tutor-Marked Assignment 111
References/Further Reading 112
Study Session 7: Expressions in C-Language 114
Introduction 114
Learning Outcomes (LOs) 114
7.1 Expression 114
Example: 114
7.2 Evaluation Procedure 115
7.3 Statements 115
7.3.1 Data Input & Output 115
getchar() 116
putchar() 117
gets() 117
puts() 117
printf() 118
Example: 118
Example: 119
scanf() 119
Example: 120
7.4 Assignment Statement 121
Conclusion 121
Summary 121
Self-Assessment Questions (SAQ) 122
Self-Assessment Answers (SAA) 122
Tutor-Marked Assignment 124
References/Further Reading 124
Study Session 8: Control Structure 126

Page 10 of 198
Introduction to Problem Solving - CSC 102

Introduction 126
Learning Outcomes (LOs) 126
8.1 Conditional Statements 127
8.1.1 if statement 127
8.1.2 if-else statements 128
8.1.3 Nested else-if statements 129
8.1.4 Nested if-else statement 130
8.1.5 Switch statement 132
Example 1: 133
Example 2: 134
Conclusion 134
Summary 135
Self-Assessment Questions (SAQ) 135
Self-Assessment Answers (SAA) 136
Tutor-Marked Assignment 138
References/Further Reading 139
Study Session 9: Looping Structures 141
Introduction 141
Learning Outcomes (LOs) 141
9.1 Loop Statement 141
9.1.1 While statement 142
Example: 142
9.1.2 do-while statement 143
Example: 143
9.1.3 for statement 144
Format - I 146
Example 1 146
Format - II 146
Example 2 146
Format - III 147

Page 11 of 198
Introduction to Problem Solving - CSC 102

Example 3 147
9.2 Nested Looping Statements 148
9.2.1 Definition of Nesting 148
9.3 Multi-Objective Loops 149
9.3.1 Break Statement 149
Example 149
9.3.2 The Continue Statement 150
Example 150
9.4 Differences between Break and Continue statements 151
9.5 Unconditional Branching (goto Statement) 153
Example 1 153
Practice Programs 155
Conclusion 157
Summary 157
Self-Assessment Questions (SAQ) 158
Self-Assessment Answers (SAA) 158
Tutor-Marked Assignment 163
References/Further Reading 163
Study Session 10: Functions in C 165
Introduction 165
Learning Outcomes (LOs) 166
10.1 Definition of Function 166
10.1.1 Return Type 167
Example 168
10.1.2 Function Name 168
Example 168
Formal arguments 169
Example 169
10.1.3 Function Body 169
Example 170
10.1.4 The Return Statement 171
Page 12 of 198
Introduction to Problem Solving - CSC 102

10.2 Programs using function Call Techniques 171


10.3 Differences between Functions and Procedures 174
10.4 Advantages of Function 175
10.5 Advanced Features of Functions 176
10.5.1 Function Prototypes 176
Functions with no arguments and no return value 177
Example: 177
Function with arguments and no return value 178
Example 178
Function with arguments and return value 179
Example: 179
Actual and Formal Parameters (or) Arguments 180
Example 181
Local and Global variables: 182
10.5.2 Calling functions by value or by reference 183
Call by value: 184
Example 184
Call by Reference: 186
Example 186
10.5.3 Recursion 188
Examples on Recursion 189
Conclusion 192
Summary 192
Self-Assessment Questions (SAQ) 192
Self-Assessment Answers (SAA) 193
Tutor-Marked Assignment 198
References/Further Reading 198

Page 13 of 198
Introduction to Problem Solving - CSC 102

List of Figures

Figure 1.1: Block diagram showing the classification of computer hardware

Figure 1.2 : Relationship between system and application software.

Figure 2.1: Diagram of a Desktop computer

Figure 2.2: Diagram showing a time sharing environment.

Figure 2.3 : Diagram of client-server processing.

Figure 2.4: Distributed computing.

Figure 3.1: Addition of numbers in machine language.

Figure 3.2: Addition of two numbers in Assembly language.

Figure 3.3: Examples of high-level programming language.

Figure 5.1: A flowchart to find the roots of a quadratic equation.

Figure 5.2: A flowchart for the biggest of three numbers.

Figure 5.3: A flowchart to add from 1-100.

Figure 5.4: A flowchart to find the factorial of a number.

Figure 5.5: A flowchart for a telephone call.

Figure 5.6: A flowchart to calculate the bonus of a staff.

List of Tables

Table 3.1: Difference between computer languages.

Table 3.2: Comparison of a compiler and interpreter.

Table 5.1: Differences between algorithm and flowchart.

Table 6.1: Showing characters with backslash.

Table 6.2: Mantissa and Exponent of two numbers.

Page 14 of 198
Introduction to Problem Solving - CSC 102

Table 7.1 : Input and Output statements in C.

Table 9.1: Differences between break and continue.

Table 10.1: Difference between procedures and functions.

Page 15 of 198
Introduction to Problem Solving - CSC 102

Study Session 1: Computer Systems

Introduction

A computer system is a basic, complete, and functional hardware and

software configuration that includes everything necessary to implement

computing functionality. This is the working definition of the computer

system as we know it, but it has undergone many formal modifications

over the past few decades.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

1.1 Explain the Computer System

1.2 Explain the Hardware of a system and its example

1.3 Differentiate between primary and cache memory.

1.4 Understand secondary memory and its examples

1.5 Differentiate between system software and application

software.

1.1 Computer Systems

A computer is an electronic device that stores, manipulates, and retrieves

data. We can also refer to a computer as a device that computes the

information supplied to it and generates data. A system is a group of

several objects connected by a process. For Example: the educational

system involves teachers, students, and objects. A teacher teaches a

subject to students, i.e., teaching is a process. Similarly, a computer

Page 16 of 198
Introduction to Problem Solving - CSC 102

system can have objects and processes. The following are the objects of

a computer system:

a) User (A person who uses the computer)

b) Hardware

c) Software

1.2 Hardware

The hardware of a computer system can be referred to as anything that

we can touch and feel. Example: keyboard and mouse. The hardware of a

computer system can be classified as Input Devices(I/P), Central

Processing Unit (CPU), Output Devices(O/P) as you will see in figure 1.1

below:

Figure 1.1: Block diagram showing the classification of computer hardware

ALU: It performs the Arithmetic and Logical Operations such as +,-,*,/

(Arithmetic Operators) &&, || ( Logical Operators)

CU: The control unit is in charge of overseeing every operation, including

storing, computing, and retrieving the data.

MU: The memory unit is used for storing the data. The memory unit is

Page 17 of 198
Introduction to Problem Solving - CSC 102

classified into two types. They are:

● Primary memory.

● Secondary memory.

1.2.1 Primary memory

The following are the types of memories that are treated as primary ROM:

It represents Read Only Memory that stores data and instructions even

when the computer is turned off. The contents of the ROM cannot be

modified once they are written. It is used to store BIOS information. RAM:

It represents Random Access Memory that stores data and instructions

when the computer is turned on. The contents of the RAM can be

modified any number of times by instructions. It is used to store the

programs under execution.

Cache memory:

Cache memory is a small, fast memory located between the CPU and main

memory. It stores frequently accessed data for faster retrieval. Using a

hierarchical structure with multiple levels (L1, L2, L3), the CPU checks the

cache for data before accessing the main memory. Cache management

aims to maximise hits and minimise misses. Overall, cache memory

reduces memory access latency and improves system performance.

1.2.2 Secondary Memory:

This is also known as auxiliary or external memory and refers to storage

devices that can store data even without a constant connection to the
Page 18 of 198
Introduction to Problem Solving - CSC 102

computer. The following are classified as types of secondary memory:

Magnetic Storage:

The magnetic storage devices store information that can be read, erased,

and rewritten a number of times. Example: Floppy Disks, Hard Disks,

Magnetic Tapes

Optical Storage:

Optical storage devices that use laser beams to read and write stored

data. Example: CD (Compact Disk), DVD (Digital Versatile Disk).

1.3 Computer Software

The software of a computer system refers to the programs, data, and

instructions that tell a computer what to do. Example: OS (Operating

Systems), web browsers, and media players. Computer software is divided

into two broad categories: System software and Application software.

System software manages the computer's resources. It provides the

interface between the hardware and the users. Application software, on

the other hand, is directly responsible for helping users solve their

problems.

1.3.1 System Software

System software consists of programs that manage the hardware

resources of a computer and perform required information processing

tasks. These programs are divided into three classes: the operating

system, system support, and system development.

Page 19 of 198
Introduction to Problem Solving - CSC 102

The operating system provides services such as a user interface, file and

database access, and interfaces to communication systems such as

Internet protocols. The primary purpose of this software is to keep the

system operating in an efficient manner while allowing users access to it.

System support software provides system utilities and other operating

services. Examples of system utilities are sort programs and disk format

programs. Operating services consist of programs that provide

performance statistics for the operational staff and security monitors to

protect the system and data. The last system software category, system

development software, includes language translators that convert

programs into machine language for execution, debugging tools to

ensure that the programs are error free and computer –assisted software

engineering (CASE) systems.

1.3.2 Application software

Application software is broken into two classes: general-purpose

software and application – specific software. General purpose software

is purchased from a software developer and can be used for more than

one application. Examples of general-purpose software include word

processors, database management systems, and computer aided design

systems. They are labelled general purpose because they can solve a

variety of user computing problems. Application –specific software can

be used only for its intended purpose. Examples of application-specific

software include a general ledger system that accountants use and a

Page 20 of 198
Introduction to Problem Solving - CSC 102

material requirement planning system that a manufacturing company

uses. They can be used only for the task for which they were designed;

they cannot be used for other generalised tasks. The relationship

between system and application software is shown in figure 1.2; below In

this figure, each circle represents an interface point. The inner core is

hardware. The user is represented by the outer layer. To work with the

system, the typical user uses some form of application software. The

application software in turn interacts with the operating system, which is

part of the system software layer. The system software provides direct

interaction with the hardware. The opening at the bottom of figure 1.2 is

the path followed by the user, who interacts directly with the operating

system when necessary.

Figure 1.2 : Relationship between system and application software.

Conclusion

This unit introduced the students to the computer system, the hardware

of a system, secondary storage management, the computer system, and

Page 21 of 198
Introduction to Problem Solving - CSC 102

primary memory. The application software and system software were also

examined in this unit.

Summary

In this session, you have learned to:

1. Explain the Computer System

2. Explain the Hardware of a system and its example

3. Differentiate between primary and cache memory.

4. Understand secondary memory and its examples.

5. Differentiate between system software and application software.

Self-Assessment Questions (SAQ)

SAQ 1.1. What do you understand to be the difference between

system software and application software? (Tests learning

outcome 1.5)

SAQ 1.2. Difference between primary and secondary memory with

examples (Tests learning outcomes 1.2 and 1.4)

SAQ 1.3. What is cache memory? (Tests learning outcome 1.3)

Self-Assessment Answers (SAA)

SAA 1.1. System software manages and controls computer

hardware, providing a platform for running applications and

facilitating interaction with the hardware. It includes operating

Page 22 of 198
Introduction to Problem Solving - CSC 102

systems, device drivers, and utility programs. Application software,

on the other hand, is designed for specific tasks or applications,

such as word processors or web browsers. It is user-focused and

allows users to accomplish specific tasks or solve particular

problems.

SAA 1.2. Primary memory, such as RAM, is volatile and provides

temporary storage for data and instructions during computer

operation. Examples include RAM modules in computers and

smartphones. Secondary memory, like hard disk drives (HDDs) and

solid-state drives (SSDs), is non-volatile and offers long-term

storage for programs and files even when the computer is turned

off.

SAA 1.3. Cache memory is a small, high-speed memory that stores

frequently accessed data and instructions to improve the overall

performance of a computer system.

Tutor-Marked Assignment

1. Differentiate between application software and system software

2. State three examples of secondary memory.

3. What is the advantage of cache memory?

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Page 23 of 198
Introduction to Problem Solving - CSC 102

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics.

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT press.

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 24 of 198
Introduction to Problem Solving - CSC 102

Study Session 2: Computing Environment

Introduction

A computer system uses many devices, arranged in different ways to

solve many problems. This constitutes a computing environment where

many computers are used to process and exchange information to

handle multiple issues. In computers, there are different types of

computing technologies, and all are different from each other. By using

this, we are finding output based on the input given by the user. In a

computing environment, the user can use a particular computing

technology, which is responsible for all the types of input and output

given by the computer.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

2.1. Explain the Computing environments

2.2. Describe the Personal Computing Environment

2.3. Understand Time-Sharing Environment

2.4. Explain the Client/Server Environment

2.5. Understand the Distributed Computing

2.1 Computing Environments

The word compute is used to refer to the process of converting

information into data. The advent of several new kinds of computers


Page 25 of 198
Introduction to Problem Solving - CSC 102

created a need for different computing environments. The following are

the different kinds of computing environments available:

1. Personal Computing Environment

2. Time Sharing Environment

3. Client/Server Environment

4. Distributed Computing Environment

2.1.1 Personal Computing Environment

In 1971, Mercian E. Hoff, working for INTEL, combined the basic elements of

the central processing unit into the microprocessor. If we are using a

personal computer, then all the computer hardware components are tied

together. This kind of computing is used to satisfy the needs of a single

user, who uses the computer for personal tasks. Ex: Personal Computer

as you can see in figure 2.1:

Figure 2.1: Diagram of a Desktop computer

2.1.2 Time-Sharing Environment

The concept of time-sharing computing is to share the processing of the

computer based on the criteria of time. In this environment, all the

Page 26 of 198
Introduction to Problem Solving - CSC 102

computing must be done by the central computer.

The central computer handles all of the processing. The computers that

ask for processing are only dumb terminals. Figure 2.2 below shows a time

sharing environment:

Figure 2.2: Diagram showing a time sharing environment

2.1.3 Client/Server Environment

Client/Server computing involves a relationship between two machines. A

client machine is the one that requests processing. The server machine is

the one that offers the processing. Hence, the client is capable enough to

do the processing. A portion of processing is done by the client, and the

core (important) processing is done by the server. Figure 2.3 shows a

sample of a client-server environment.

Page 27 of 198
Introduction to Problem Solving - CSC 102

Figure 2.3 : Diagram of client-server processing.

2.1.4 Distributed Computing

A distributed computing environment provides seamless integration of

computing functions between different servers and clients. A client is not

just a requestor for processing information from the server. The client

also has the capability to process information. All the machines,

Clients/Servers share the processing task. Figure 2.4 shows distributed

computing.

Page 28 of 198
Introduction to Problem Solving - CSC 102

Figure 2.4: Distributed computing

Example: Ebay on Internet

Conclusion

This session introduced the students to computing environments,

personal computing environments, and time-sharing environments. The

client server environment and distributed computing were also examined

in this session.

Summary

In this session, you have learned to:

1. Explain the Computing environments

2. Describe the Personal Computing Environment

3. Understand Time-Sharing Environment

4. Explain the Client/Server Environment

5. Understand the Distributed Computing

Self-Assessment Questions (SAQ)

SAQ 2.1. To the best of your understanding, explain a computing

environment. (Tests learning outcome 2.1)

SAQ 2.2. Define distributed computing with real-life examples.

(Tests learning outcome 2.5)

SAQ 2.3. Difference between personal computing environment and

time-sharing environment. (Tests learning outcomes 2.2 and 2.3)

Page 29 of 198
Introduction to Problem Solving - CSC 102

Self-Assessment Answers (SAA)

SAA 2.1. A computing environment is the infrastructure where

computing activities occur. It includes hardware, software,

networks, and peripherals. The environment can vary based on

personal, enterprise, or cloud computing needs. It encompasses

configuration, management, and security measures. The

computing environment enables data processing, communication,

and the delivery of computing services.

SAA 2.2. Distributed computing refers to the use of multiple

computers or devices connected over a network to work together

on a task or solve a problem. Rather than relying on a single

powerful machine, distributed computing leverages the collective

resources and processing power of multiple devices to achieve

computational goals. This approach allows for improved

performance, scalability, fault-tolerance, and resource utilisation.

Some real-life examples of distributed computing are Search

Engines and Content Delivery Networks.

SAA 2.3. Personal computing environments offer dedicated

resources and local processing, providing individual users with

autonomy and control over their computing experience.

Time-sharing environments, on the other hand, involve resource

sharing and remote access, enabling multiple users to share a

central system and perform tasks concurrently in a time-division

Page 30 of 198
Introduction to Problem Solving - CSC 102

manner.

Tutor-Marked Assignment

1. Discuss the computing system environment.

2. Explain the client/Server environment in a great detail

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

Page 31 of 198
Introduction to Problem Solving - CSC 102

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 32 of 198
Introduction to Problem Solving - CSC 102

Study Session 3:Computer Languages

Introduction

A computer language is a collection of instructions used to develop

computer programs. This is a summary of programming languages. The

primary objective is human-computer interaction. The purpose of

computer programming languages is to convey instructions to a

computer. Syntactic and semantic rules determine the meaning of each

programming language construct.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

3.1. Explain the computer languages

3.2. Understand the machine language and it advantages

3.3. Differentiate between the assembly language and high-level

language

3.4. Describe the merit and demerit of symbolic languages

3.5. Understand the Language translator

3.6. State the comparison between a Compiler and Interpreter

3.1 Computer Languages

A computer language is required to write a program (which tells the

computer what to do). Over the years, computer languages have evolved

Page 33 of 198
Introduction to Problem Solving - CSC 102

from machine languages to natural languages. The following is the

summary of computer languages

1940’s -- Machine

Languages

1950’s -- Symbolic

Languages

1960’s -- High Level

Languages

3.1.1 Machine Language

In the earliest days of computers, the only programming languages

available were machine languages. Each computer has its own machine

language, which is made up of streams of 0s and 1s. The instructions in

machine language must be in streams of 0s and 1s. These are known as

binary digits. These are so named as the machine can directly understand

the programs

Advantages of machine language

1. High speed execution

2. The computer can understand instruction immediately

3. No translation is needed.

Disadvantages of machine languages

1. Machine dependent

2. Programming is very difficult

Page 34 of 198
Introduction to Problem Solving - CSC 102

3. Difficult to understand

4. Difficult to write bug free programs

5. Difficult to isolate an error

Figure 3.1 shows an example of two numbers using machine language:

Figure 3.1: Addition of numbers in machine language

3.1.2 Symbolic Languages (or) Assembly Language

In the early 1950’s Admiral Grace Hopper, a mathematician and naval

officer, developed the concept of a special computer program that would

convert programs into machine language. These early programming

languages simply mirrored the machine languages, using symbols or

mnemonics to represent the various language instructions. These

languages were known as symbolic languages. Because a computer does

not understand symbolic language, it must be translated into machine

language. A special program called an Assembler translates symbolic

code into the machine language. Hence, they are called assembly

language.

Page 35 of 198
Introduction to Problem Solving - CSC 102

Advantages of Assembly Language

1. Easy to understand and use

2. Easy to modify and isolate error

3. High efficiency

4. More control on hardware

Disadvantages of Assembly Language

1. Machine Dependent Language

2. Requires translator

3. Difficult to learn and write programs

4. Slow development time

5. Less efficient

Figure 3.2 shows an example of the addition of two numbers using

assembly language.

Figure 3.2: Addition of two numbers in Assembly language

3.1.3 High-Level Languages

The symbolic languages greatly improved programming efficiency, but

they still required programmers to concentrate on the hardware that they


Page 36 of 198
Introduction to Problem Solving - CSC 102

were using. Working with symbolic languages was also very tedious

because each machine instruction had to be individually coded. The

desire to improve programmer efficiency and shift the focus from the

computer to the problems being solved led to the development of

high-level languages. High-level languages are portable to many different

computers, allowing the programmer to concentrate on the application

problem at hand rather than the intricacies of the computer.

Figure 3.3 below shows examples of high-level programming languages.

Figure 3.3: Examples of high-level programming language

Advantages of High-level language

1. Easy to write and understand

2. Easy to isolate an error

3. Machine independent language

4. Easy to maintain

5. Better readability

6. Low Development cost

7. Easier to document

8. Portable

Disadvantages of High-Level Language

1. Needs translator

Page 37 of 198
Introduction to Problem Solving - CSC 102

2. Requires high execution time

3. Poor control on hardware

4. Less efficient

Example: Sample of a code in C language

#include<stdio.h>

void main() {

int a, b, c; scanf("%d%d%",&a,&b); c=a+b; printf("%d",c); }

3.1.4 Difference between Machine, Assembly, High-Level Languages

Table 3.1 shows the difference between machine, assembly and high-level

languages

Table 3.1: Differences between Computer Languages

3.2 Language Translators

Page 38 of 198
Introduction to Problem Solving - CSC 102

These are the programs that are used for converting the programs in one

language into machine language, so that they can be executed by the

computer.

1) Compiler: It is a program which is used to convert the high-level

language programs into machine language

2) Assembler: It is a program which is used to convert the assembly level

language programs into machine language

3) Interpreter: It is a program, it takes one statement of a high-level

language program, translates it into machine language instruction and

then immediately executes the resulting machine language instruction

and soon.

3.2.1 Comparison between a Compiler and Interpreter

Table 3.2: Comparison of a compiler and interpreter.

Page 39 of 198
Introduction to Problem Solving - CSC 102

Conclusion

This session explained computer languages and it’s main types, it further

explained their advantages and disadvantages, so a programmer/student

will know which one best fits their needs. It ended the session talking

about a language translator's ability to change one type of language into

another.

Summary

In this session, you have learned to:

3.1.Explain the computer languages

3.2. Understand the machine language and it advantages

3.3. Differentiate between the assembly language and high-level

language

3.4. Describe the merit and demerit of symbolic languages

3.5. Understand the Language translator

3.6. State the comparison between a Compiler and Interpreter

Self-Assessment Questions (SAQ)

SAQ 3.1 Importance of a language translator (Tests learning outcome

3.5)

SAQ 3.2 What is high-level language and mention examples (Tests

learning outcome 3.3)

SAQ 3.3 Mention programming languages that use a compiler (Tests

Page 40 of 198
Introduction to Problem Solving - CSC 102

learning outcome 3.6)

SAQ 3.4 What is the difference between a compiler and interpreter

(Tests learning outcome 3.6)

Self-Assessment Answers (SAA)

SAA 3.1. Language translators are essential for executing

high-level programming code on computer hardware. They enable

platform independence, optimise code performance, detect errors,

provide advanced language features, and enhance software

portability and maintainability. Without language translators,

programming languages would remain abstract and inaccessible to

computer systems, hindering software development and execution.

SAA 3.2. A high-level language is a programming language that is

designed to be easily understood and written by humans. It

provides a level of abstraction from the underlying hardware,

allowing programmers to write code in a more intuitive and readable

manner compared to low-level languages. High-level languages are

closer to human languages and often have built-in functions and

libraries that simplify complex tasks. Examples of high-level

programming languages include: Python, Java,JavaScript, C#, and

Ruby.

SAA 3.3. The following are programming languages that use a

compiler: C, C++, C#, Java, Swift, and Go.

SAA 3.4. A compiler translates the entire code into machine code

Page 41 of 198
Introduction to Problem Solving - CSC 102

before execution, resulting in faster execution but requiring a

separate compilation step. An interpreter, on the other hand,

directly executes the code line by line, providing flexibility but

typically with slower execution.

Tutor-Marked Assignment

1. Discuss the differences between machine language and assembly

language

2. Describe four merits of symbolic language

3. What is the significance of computer language?

4. State the advantages and disadvantages of multiprogramming.

5. Differentiate between a compiler and interpreter

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics.

Page 42 of 198
Introduction to Problem Solving - CSC 102

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT press.

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 43 of 198
Introduction to Problem Solving - CSC 102

Study Session 4: Procedure (Steps Involved in Problem Solving)

Introduction

A computer is a very powerful and versatile machine capable of

performing a multitude of different tasks, yet it has no intelligence or

thinking power. The intelligence Quotient (I.Q) of a computer is zero. A

computer performs many tasks exactly in the same manner as it is told

to. This places responsibility on the user to instruct the computer in a

correct and precise manner, so that the machine is able to perform the

required job in a proper way. A wrong or ambiguous instruction may

sometimes prove disastrous. In order to instruct a computer correctly,

the user must have a clear understanding of the problem to be solved.

Apart from this, he should be able to develop a method, in the form of a

series of sequential steps, to solve it. Once the problem is well-defined

Page 44 of 198
Introduction to Problem Solving - CSC 102

and a method of solving it is developed, instructing the computer to

solve the problem becomes a relatively easier task. Thus, before

attempting to write a computer program to solve a given problem. It is

necessary to formulate or define the problem in a precise manner. Once

the problem is defined, the steps required to solve it, must be stated

clearly in the required order.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

4.1.Understand the concept of Problem solving

4.2. Understand steps involved in algorithm development

4.3. Understand the concept of Algorithm

4.4. Develop Algorithm for simple problem

4.1 Procedure (Steps involved in Problem Solving)

A computer cannot solve a problem on its own. One has to provide step

by step solutions of the problem to the computer. In fact, the task of

problem solving is not that of the computer. It is the programmer who

has to write down the solution to the problem in terms of simple

operations which the computer can understand and execute. In order

to solve a problem by the computer, one has to pass through certain

stages or steps. They are:

1. Understanding the problem: Here we try to understand the

Page 45 of 198
Introduction to Problem Solving - CSC 102

problem to be solved. Before the next stage or step, we

should be absolutely sure about the objectives of the given

problem.

2. Analysing the problem: After understanding thoroughly the

problem to be solved, we look at different ways of solving

the problem and evaluate each of these methods. The idea

here is to search for an appropriate solution to the problem

under consideration. The end result of this stage is a broad

overview of the sequence of operations that are to be

carried out to solve the given problem.

3. Developing the solution: Here the overview of the sequence

of operations that was the result of the analysis stage is

expanded to form a detailed step by step solution to the

problem under consideration.

4. Coding and implementation: The last stage of the problem

solving is the conversion of the detailed sequence of

operations into a language that the computer can

understand. Here each step is converted to its equivalent

instruction or instructions in the computer language that

has been chosen for the implantation.

4.2 Algorithm

A set of sequential steps usually written in ordinary language to solve

Page 46 of 198
Introduction to Problem Solving - CSC 102

a given problem is called Algorithm. It may be possible to solve the

problem in more than one way, resulting in more than one algorithm.

The choice of various algorithms depends on the factors like reliability,

accuracy and ease to modify. The most important factor in the choice

of algorithm is the time requirement to execute it, after writing code in

High-level language with the help of a computer. The algorithm which

will need the least time when executed is considered the best.

4.2.1 Steps involved in algorithm development

An algorithm can be defined as “a complete, unambiguous, finite

number of logical steps for solving a specific problem “

Step 1. Identification of input: For an algorithm, there

are quantities to be supplied called input and these are fed

externally. The input is to be identified first for any

specified problem.

Step 2: Identification of output: From an algorithm, at

least one quantity is produced, called for any specified

problem.

Step 3 : Identification the processing operations : All

the calculations to be performed in order to lead to output

from the input are to be identified in an orderly manner.

Page 47 of 198
Introduction to Problem Solving - CSC 102

Step 4 : Processing Definiteness : The instructions

composing the algorithm must be clear and there should

not be any ambiguity in them.

Step 5 : Processing Finiteness : If we go through the

algorithm, then for all cases, the algorithm should

terminate after a finite number of steps.

Step 6: Possessing Effectiveness : The instructions in

the algorithm must be sufficiently basic that they can be

easily carried out in practice.

An algorithm must possess the following properties:

1. Finiteness: An algorithm must terminate in a finite

number of steps

2. Definiteness: Each step of the algorithm must

be precisely and unambiguously stated

3. Effectiveness: Each step must be effective, in

the sense that it should be primitive easily convert

able into program statement) can be performed

exactly in a finite amount of time.

4. Generality: The algorithm must be complete in

itself so that it can be used to solve problems of a

Page 48 of 198
Introduction to Problem Solving - CSC 102

specific type for any input data.

5. Input/output: Each algorithm must take zero,

one or more quantities as input data produce one or

more output values. An algorithm can be written in

English like sentences or in any standard

representation sometimes, algorithm written in

English like languages are called Pseudo Code

Example

1. Suppose we want to find the average of three

numbers, the algorithm is as follows:

Step 1 Read the numbers a, b, c

Step 2 Compute the sum of a, b and c

Step 3 Divide the sum by 3

Step 4 Store the result in variable d

Step 5 Print the value of d

Step 6 End of the program

4.2.2 Algorithms for Simple Problem

Write an algorithm for the following:

1. Write an algorithm to calculate the simple interest

using the formula. Simple interest = P*N* R/100

Page 49 of 198
Introduction to Problem Solving - CSC 102

Where P is the principal amount, N is the number of years, and R is

the rate of interest:

Step 1: Read the three input

quantities, P, N, and R.

Step 2 : Calculate simple interest as

Simple interest = P* N*

R/100

Step 3: Print simple

interest.

Step 4: Stop.

2.Area of a Triangle: Write an algorithm to find the area of the

triangle.

Let b and c be the sides of the triangle ABC and A is the

included angle between the given sides.

Step 1: Input the given elements of the triangle, namely

sides b, c, and the angle between the sides A.

Step 2: Area = (1/2) *b*C* sin A

Step 3: Output the Area

Step 4: Stop.

Page 50 of 198
Introduction to Problem Solving - CSC 102

3. Write an algorithm to find the largest of

three numbers X, Y,Z.

Step 1: Read the numbers X, Y, and Z.

Step 2: if (X > Y)

Big = X

else BIG = Y

Step 3 : if (BIG < Z)

Step 4: Big = Z

Step 5: Print the largest number i.e. Big

Step 6: Stop

4. Write down an algorithm to find the largest data

value of a set of given data values

Algorithm for the largest of all data values:

Step 1: LARGE ← 0

Step 2: read NUM

Step 3: While NUM > = 0 do

3.1 if NUM > LARGE

3.1.1 then

3.1.1.1 LARGE ← NUM

Page 51 of 198
Introduction to Problem Solving - CSC 102

3.2. read NUM

Step 4: Write “largest data value is”, LARGE

Step 5: end.

5. Write an algorithm which will test whether a

given integer value is prime or not.

Algorithm for prime number testing:

Step 1: M ← 2

Step 2: read N

Step 3: MAX ← SQRT (N)

Step 4: While M < = MAX do

4.1 if (M* (N/M) = N

4.1.1 then

4.1.1.1 go to step 7

4.2. M ← M + 1

Step 5: Write “number is

prime”

Step 6: go to step 8

Step 7: Write “number is not a prime”

Step 8: end

Page 52 of 198
Introduction to Problem Solving - CSC 102

6. Write algorithm to find the factorial of a given number N

Step 1: PROD ← 1

Step 2: I ← 0

Step 3: read N

Step 4: While I < N do

4.1 I ← I + 1

4.2. PROD ← PROD* I

Step 5: Write “Factorial of”, N, “is”, PROD

Step 6: end.

7. Write an algorithm to find the sum of given data

values until a negative value is entered.

Algorithm Find – Sum

Step 1: SUM ← 0

Step 2: I ← 0

Step 3: read NEW VALUE

Step 4: While NEW VALUE < = 0 do

4.1 SUM ← SUM + NEW VALUE

4.2 1 ← I + 1

4.3 read NEW VALUE

Page 53 of 198
Introduction to Problem Solving - CSC 102

Step 5: Write “Sum of”, I, “data value is, “SUM

Step 6: END

8. Write an algorithm to calculate the perimeter and

area of a rectangle. Given its length and width.

Step 1: Read length of the rectangle.

Step 2: Read width of the rectangle.

Step 3: Calculate perimeter of the rectangle using the

formula perimeter = 2* (length + width)

Step 4: Calculate area of the rectangle using the formula area =

length*width

Step 5: Print perimeter.

Step 6: Print area.

Step 7: Stop.

Conclusion

This session introduced the students to the concept of problem solving,

the steps involved in algorithm development, and the concept of

algorithms. Several examples of algorithm for simple problems were also

examined in this session.

Summary

In this session, you have learned to:

Page 54 of 198
Introduction to Problem Solving - CSC 102

1. Understand the concept of Problem solving

2. Understand steps involved in algorithm development

3.Understand the concept of Algorithm

4.Develop Algorithm for simple problem

Self-Assessment Questions (SAQ)

SAQ4.1. What is the significance of understanding the steps

involved in algorithm development? (Tests learning outcome 4.2)

SAQ4.2. What are the advantages of algorithms? (Tests learning

outcome 4.3)

SAQ4.3. Write an algorithm to find the factorial of a given number.

(Tests learning outcome 4.4)

SAQ4.4. Write an algorithm to calculate the sum of numbers from 1

to N. (Tests learning outcome 4.4)

Self-Assessment Answers (SAA)

SAA4.1. Understanding the steps helps in structuring and

organising the problem-solving process, ensuring clarity and

effectiveness in finding solutions.

SAA4.2. The following are advantages of algorithm:

● Clarity and organisation: Algorithms provide a systematic and

structured approach to problem-solving, making it easier to

understand and communicate the solution.

● Efficiency: Well-designed algorithms can optimise the use of

Page 55 of 198
Introduction to Problem Solving - CSC 102

computational resources, such as time and memory, leading

to more efficient solutions.

● Reusability: Algorithms can be reused for similar problem

instances or adapted to solve related problems, saving time

and effort in the development process.

● Scalability: Algorithms can handle larger problem sizes or

datasets by efficiently scaling their execution, allowing them

to solve complex problems.

● Modifiability: Algorithms can be modified and improved based

on changing requirements or constraints, providing flexibility

in addressing evolving problem scenarios.

SAA4.3. Algorithm:

Step 1: Read the input number N.

Step 2: Initialise a variable PROD as 1.

Step 3: Initialise a variable I as 1.

Step 4: While I is less than or equal to N, do steps 4.1 and 4.2.

4.1: Multiply PROD by I.

4.2: Increment I by 1.

Step 5: Print the factorial value stored in PROD.

Step 6: End.

Example:

Let's say we want to find the factorial of 5.

Input: N = 5

Page 56 of 198
Introduction to Problem Solving - CSC 102

Algorithm execution:

Step 1: N = 5

Step 2: PROD = 1

Step 3: I = 1

Step 4:

Iteration 1: PROD = PROD * I = 1 * 1 = 1, I = 2

Iteration 2: PROD = PROD * I = 1 * 2 = 2, I = 3

Iteration 3: PROD = PROD * I = 2 * 3 = 6, I = 4

Iteration 4: PROD = PROD * I = 6 * 4 = 24, I = 5

Step 5: Print PROD = 24

Step 6: End

Therefore, the factorial of 5 is 24.

SAA4.4. Algorithm:

Step 1: Read the input number N.

Step 2: Initialise a variable SUM as 0.

Step 3: Initialise a variable I as 1.

Step 4: While I is less than or equal to N, do steps 4.1 and 4.2.

4.1: Add I to SUM.

4.2: Increment I by 1.

Step 5: Print the value of SUM.

Step 6: End.

Example:

Page 57 of 198
Introduction to Problem Solving - CSC 102

Let's calculate the sum of numbers from 1 to 10.

Input: N = 10

Algorithm execution:

Step 1: N = 10

Step 2: SUM = 0

Step 3: I = 1

Step 4:

Iteration 1: SUM = SUM + I = 0 + 1 = 1, I = 2

Iteration 2: SUM = SUM + I = 1 + 2 = 3, I = 3

Iteration 3: SUM = SUM + I = 3 + 3 = 6, I = 4

Iteration 4: SUM = SUM + I = 6 + 4 = 10, I = 5

Iteration 5: SUM = SUM + I = 10 + 5 = 15, I = 6

Iteration 6: SUM = SUM + I = 15 + 6 = 21, I = 7

Iteration 7: SUM = SUM + I = 21 + 7 = 28, I = 8

Iteration 8: SUM = SUM + I = 28 + 8 = 36, I = 9

Iteration 9: SUM = SUM + I = 36 + 9 = 45, I = 10

Iteration 10: SUM = SUM + I = 45 + 10 = 55, I = 11

Step 5: Print SUM = 55

Step 6: End

Therefore, the sum of numbers from 1 to 10 is 55.

Page 58 of 198
Introduction to Problem Solving - CSC 102

Tutor-Marked Assignment

1. Define an Algorithm

2. Write an algorithm to find the largest of three given numbers.

3. Write an algorithm to check whether a given integer value is a prime

number or not.

4. Write an Algorithm for perimeter of a Triangle

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics.

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

Page 59 of 198
Introduction to Problem Solving - CSC 102

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html

Page 60 of 198
Introduction to Problem Solving - CSC 102

Study Session 5: Flowchart

Introduction

Flowcharts are nothing but the graphical representation of the data or the

algorithm for a better understanding of the code visually. It displays

step-by-step solutions to a problem, algorithm, or process. It is a pictorial

way of representing steps that are preferred by most beginner-level

programmers to understand algorithms in computer science, thus

contributing to troubleshooting the issues in the algorithm. A flowchart is

a picture of boxes that indicates the process's flow in a sequential

manner. Since a flowchart is a pictorial representation of a process or

algorithm, it’s easy to interpret and understand the process. To draw a

flowchart, certain rules need to be followed, which are followed by all

professionals and are widely accepted all over the world.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

5.1. Explain the Computer System Structure

5.2. Develop Algorithm for simple problem

5.3. Understand the concept of Flowchart development

5.4. Draw the symbols used in Flowcharts

5.5. Understand what a pseudocode is and how to use it.

Page 61 of 198
Introduction to Problem Solving - CSC 102

5.1 Flowchart

A flow chart is a step by step diagrammatic representation of the

logic paths to solve a given problem. A flowchart is a visual or

graphical representation of an algorithm.

The flowcharts are pictorial representations of the methods to be

used to solve a given problem and help a great deal to analyse the

problem and plan its solution in a systematic and orderly manner. A

flowchart when translated into a proper computer language,

results in a complete program.

5.1.1 Advantages of Flowcharts

1. The flowchart shows the logic of a problem displayed in

pictorial fashion which facilitates easier checking of an

algorithm.

2.The Flowchart is a good means of communication to other

users. It is also a compact means of recording an algorithm

solution to a problem.

3.The flowchart allows the problem solver to break the

problem into parts. These parts can be connected to make

a master chart.

4.The flowchart is a permanent record of the solution that

can be consulted at a later time.


Page 62 of 198
Introduction to Problem Solving - CSC 102

5.1.2 Differences between Algorithm and Flowchart

Table 5.1: Differences between algorithm and flowchart

Algorithm Flowchart

A method of representing the A flowchart is a diagrammatic

step-by-step logical procedure for representation of an algorithm, it is

solving a problem. constructed using different types

of boxes and symbols.

It contains step-by-step English The flowchart employs a series of

descriptions, each step blocks and arrows, each of which

representing a particular operation represents a particular step in an

leading to the solution of a algorithm.

problem.

It is particularly useful for simple It is useful for the detailed

problems. representation of complicated

programs.

5.1.3 Symbols used in a flowchart

The symbols that we use while drawing flowcharts, as given below,

are as per conventions followed by the International Standard

Organisation (ISO):

Page 63 of 198
Introduction to Problem Solving - CSC 102

1. Oval: A rectangle with rounded sides is used to

indicate either START/ STOP of the program.

2. Input and output indicators: Parallelograms are

used to represent input and output operations.

Statements like INPUT, READ, and PRINT are represented in

these parallelograms.

3. Process Indicators: - Rectangle is used to

indicate any set of processing operations, such as storing

arithmetic operations.

4. Decision Makers: The diamond is used for

indicating the step of decision making and therefore

known as decision box. Decision boxes are used to test the

conditions or ask questions and depending upon the

answers, the appropriate actions are taken by the

computer. The decision box symbol is

Page 64 of 198
Introduction to Problem Solving - CSC 102

5. Flow Lines: Flow lines indicate the direction

being followed in the flowchart. In a Flowchart, every line

must have an arrow on it to indicate the direction. The

arrows may be in any direction

6. On- Page connectors: Circles are used to join

the different parts of a flowchart, and these circles are

called on-page connectors. The use of these connectors

gives a neat shape to the flowcharts. In complicated

problems, a flowchart may run several pages. The parts of

the flowchart on different pages are to be joined with each

other. The parts to be joined are indicated by the circle.

7. Off-page connectors: This connector

represents a break in the path of a flowchart that is too

large to fit on a single page. It is similar to an on-page

connector. The connector symbol marks where the

algorithm ends on the first page and where it continues on

the second.
Page 65 of 198
Introduction to Problem Solving - CSC 102

5.1.4 Simple Problems solved using FlowChart

1. Draw the Flowchart to find Roots of Quadratic equation ax2+

bx + c

= 0. The coefficients a, b, c are the input data

Figure 5.1: A flowchart to find the roots of a quadratic equation.

2.Draw a flowchart to find out the biggest of the three

unequal positive numbers.

Page 66 of 198
Introduction to Problem Solving - CSC 102

Figure 5.2: A flowchart for biggest of three numbers

3. Draw a flowchart for adding the integers from 1 to

100 and to print the sum.

Figure 5.3: A flowchart to add from 1-100

Page 67 of 198
Introduction to Problem Solving - CSC 102

4. Draw a flowchart to find the factorial of a positive integer N .

Figure 5.4: A flowchart to find the factorial of a number.

5. Develop a flowchart to illustrate how to make a

Landline telephone call

Page 68 of 198
Introduction to Problem Solving - CSC 102

Figure 5.5: A flowchart for a telephone call

Flowchart for Telephone call

6.6. ABC company plans to give a 6% year-end bonus

to each of its employees earning Rs 6,000 or more

per month , and a fixed Rs 250/- - bonus to the

remaining employees. Draw a flowchart for

calculating the bonus for an employee

Page 69 of 198
Introduction to Problem Solving - CSC 102

Figure 5.6: A flowchart to calculate the bonus of a staff

Pseudocode

The Pseudocode is neither an algorithm nor a program. It is an

abstract form of a program. It consists of English-like statements

which perform specific operations. It is defined for an algorithm. It

does not use any graphical representation. In pseudocode, the

program is represented in terms of words and phrases, but the

syntax of the program is not strictly followed.

Advantages: Easy to read, Easy to understand, and Easy to

modify.

Example:

Write a pseudo code to perform the basic arithmetic operations.


Page 70 of 198
Introduction to Problem Solving - CSC 102

Read n1, n2

Sum = n1 + n2

Diff = n1 – n2

Mult = n1 * n2

Quot = n1/n2

Print sum, diff, mult, quot

End.

Conclusion

This session introduced students to the purpose of a flowchart and the

symbols that make up a flowchart, so that students can be able to create

their own flowchart, given a particular problem, it also mentioned

pseudocode and the advantages it has. Through using the above problem

solving methods writing code for a problem becomes easier.

Summary

In this session, you have learned to:

1. Develop Algorithm for simple problem

2.Understand the concept of Flowchart development

3.Draw the symbols used in Flowcharts

Self-Assessment Questions (SAQ)

SAQ5.1. List and explain three symbols used in a flowchart. (Tests

Page 71 of 198
Introduction to Problem Solving - CSC 102

learning outcome 5.4)

SAQ5.2. Differentiate between pseudocode and flowchart (Tests

learning outcome 5.3)

SAQ5.3. Write a pseudocode to calculate the average of a list of

numbers.(Tests learning outcome 5.5)

SAQ5.4. Write a pseudocode to find the maximum number among

three given numbers.(Tests learning outcome 5.5)

SAQ5.5. Write a pseudocode to calculate the factorial of a given

number.(Tests learning outcome 5.5)

Self-Assessment Answers (SAA)

1. The following are symbols used in a flowchart:

● Oval: The oval symbol is used to represent the start and end

points of a flowchart. It indicates the beginning or termination

of a process. It is typically used at the top and bottom of the

flowchart.

● Rectangle: The rectangle symbol is used to represent a

process or operation in the flowchart. It represents a specific

action or task that needs to be performed. This can include

calculations, data manipulation, or any other action required

to solve the problem.

● Diamond: The diamond symbol is used to represent a decision

point in the flowchart. It is used when the flowchart needs to

branch out based on a condition or a choice. It represents a

question or a logical test, and the flow of the chart is

Page 72 of 198
Introduction to Problem Solving - CSC 102

determined based on the outcome of that test.

2. Pseudocode is a textual representation using natural language and

programming-like syntax, while flowcharts are visual

representations using standardised symbols and arrows.

Pseudocode focuses on the logic and algorithmic steps, while

flowcharts emphasise the visual representation of the process flow.

Both pseudocode and flowcharts serve as tools to plan, analyse,

and communicate algorithms and problem-solving approaches.

3. Read n (number of elements in the list)

Set sum = 0

Repeat n times:

Read num

Set sum = sum + num

Set average = sum / n

Display average

4. Read num1

Read num2

Read num3

Set maxNum = num1

If num2 is greater than maxNum:

Set maxNum = num2

If num3 is greater than maxNum:

Set maxNum = num3

Display maxNum

Page 73 of 198
Introduction to Problem Solving - CSC 102

5. Read number

Set factorial = 1

Set i = 1

Repeat until i is less than or equal to number:

Set factorial = factorial * i

Increment i by 1

Display factorial

Tutor-Marked Assignment

1. What is a Flowchart?

2. What is pseudocode?

3. What are the symbols in a flowchart?

4. Differentiate between algorithm and flowchart.

5. Draw the flowchart to find roots of Quadratic equation ax2+ bx + c =

6. What are the basic steps involved in problem solving?

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics.

Page 74 of 198
Introduction to Problem Solving - CSC 102

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 75 of 198
Introduction to Problem Solving - CSC 102

Study Session 6: Features of C

Introduction

C is a high level language and is the upgraded version of another

language (Basic Combined Program Language). C language was

designed at Bell Laboratories in the early 1970s by Dennis Ritchie.

C, being popular in the modern computer world, can be used in

mathematical, scientific, engineering, and commercial

applications.

The most popular operating system, UNIX, is written in C language.

This language also has the features of low -level languages and

hence called “System Programming Language.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

6.1. What is C Language and its importance?

6.2. Explain the features and structure of C language

6.3. Understand various data types and tokens in C language

6.4. Understand working function of input and output

statements in C

6.5. Understand working function of Branching statements in

6.6. Understanding the different operators in C.

Page 76 of 198
Introduction to Problem Solving - CSC 102

6.1 Features of C language

1. Simple, versatile, general purpose language

2. It has rich set of Operators

3. Program execution are fast and efficient

4. Can easily manipulate bits, bytes and addresses

5. A variety of data types are available

6. Separate compilation of functions is possible

and such functions can be called by any C program

7. Block- structured language

8. Can be applied in System programming areas

like operating systems, compilers &

Interpreters, Assemblers, Text Editors, Print

Spoolers, Network Drivers, Modern Programs,

Databases, Language Interpreters, Utilities etc

6.2 Character Set

The character set is the fundamental raw-material for any

language. Like natural languages, computer languages also have a

well defined character-set, which is useful for building programs.

The C language consists of two character sets, namely, the

source character set and the execution character set. Source


Page 77 of 198
Introduction to Problem Solving - CSC 102

character set is useful to construct the statements in the source

program. Execution character set is employed at the time of

execution of the program.

1. Source character set : This type of character

set includes three types of characters namely alphabets,

Decimals and special symbols.

i. Alphabets : A to Z, a to z and Underscore( _ )

ii. Decimal digits : 0 to 9

iii. Special symbols: + - * / ^ % = & ! ( ) { } [ ] “ etc

2. Execution character set : This set of characters

are also called as non-graphic characters because these

are invisible and cannot be printed or displayed directly.

These characters will have an effect only when the

program is being executed. These characters are

represented by a backslash (\) followed by a character.

Page 78 of 198
Introduction to Problem Solving - CSC 102

Table 6.1: Showing characters with backslash

Execution Meaning Result at the time of

character execution

\n End of a Transfers the active position

line of cursor to the initia

position of next line


\ 0 (zero) End of

string Null

\t Horizontal Transfers the active


Tab position of cursor to the

next Horizontal Tab


\v Vertical Tab
Transfers the active
\f Form feed
position of cursor to the
\r Carriage next Vertical Tab
return
Transfers the active

position of cursor to the next

logical page

Transfers the active

position of cursor to the

initial position of current line

6.3 Structure of a C-Program

The structure of a C program is:


Page 79 of 198
Introduction to Problem Solving - CSC 102

I. main()

II. pair of braces { }

III. declarations and statements

IV. user defined functions

Preprocessor Statements: These statements begin with #

symbol. They are called preprocessor directives. These

statements direct the C preprocessor to include header files and

also symbolic constants into the C program. Some of the

preprocessor statements are:

#include<stdio.h>: for the standard input/output

functions #include<test.h>: for file inclusion of header

file Test.

#define NULL 0: for defining symbolic constant NULL = 0 etc.

Global Declarations: Variables or functions whose existence is

known in the main() function and other user-defined functions are

called global variables (or functions) and their declaration is called

global declaration. This declaration should be made before main().

main(): As the name itself indicates, it is the main function of

every C program. Execution of a C program starts from main (). No

C program is executed without the main() function. It should be

written in lowercase letters and should not be terminated by a

semicolon. It calls other library functions user defined functions.

Page 80 of 198
Introduction to Problem Solving - CSC 102

There must be one and only one main() function in every C

program.

Braces: Every C program uses a pair of curly braces ({,}0. The left

brace indicates the beginning of main() function. On the other

hand, the right brace indicates the end of the main() function. The

braces can also be used to indicate the beginning and end of

user-defined functions and compound statements.

Declarations: It is part of the C program where all the variables,

arrays, functions etc., used in the C program are declared and may

be initialised with their basic data types.

Statements: These are instructions to the specific operations.

They may be input-output statements, arithmetic statements,

control statements and other statements. They also include

comments.

User-defined functions: These are subprograms. Generally, a

subprogram is a function that contains a set of statements to

perform a specific task. These are written by the user; hence the

name "user-defined functions”. They may be written before or

after the main() function.

6.4 Data types in C language.

The following are data types in C language:

1. Basic data types

Page 81 of 198
Introduction to Problem Solving - CSC 102

2. Derived data types

3. Enumerated data types

4. Void data type

5. Boolean data type

6.4.1 Basic Data Types

There are four basic data types in C language. They are integer

data, character data, floating point data, and double data types.

1. Character data: Any character of the ASCII

character set can be considered as a character

data type and its maximum size can be 1 byte or

8 bytes long. ‘Char’ is the keyword used to

represent character data type in C.

Char -a single byte size, capable of holding one

character.

2. Integer data: The keyword ‘int’ stands for the

integer data type in C and its size is either 16 or

32 bits. The integer data type can again be

classified as

1. Long int - long integer with more digits

2. Short int - short integer with fewer digits.

3. Unsigned int - Unsigned integer

4. Unsigned short int – Unsigned short integer

Page 82 of 198
Introduction to Problem Solving - CSC 102

5. Unsigned long int – Unsigned long integer

As above, qualifiers like short, long, signed, or unsigned

can be applied to basic data types to derive new data

types.

int - an integer with the natural size of the host machine.

3. Floating point data: - The numbers which are

stored in floating point representation with

mantissa and exponent are called floating point

(real) numbers. These numbers can be declared

as ‘float’ in C.

float - single precision floating point number

value.

4. Double data : - Double is a keyword in C to

represent double precision floating point

numbers.

double - Double – precision floating point number value.

6.5 Tokens in C

A token is the smallest unit used in a C program; The

following are tokens:

1. Constants/Literals

2. Reserved words/ Keywords


Page 83 of 198
Introduction to Problem Solving - CSC 102

3. Delimiters

4. Variables/Identifiers

6.5.1 Constant/Literals:

Constants are those that do not change during the execution of

the program. Constants may be categorised into:

1. Numeric Constants

2. Character Constants

3. String Constants

Numeric Constants:

Numeric constants, as the name itself indicates, are those that

consist of numerals, an optional sign, and an optional period. They

are further divided into two types:

(a) Integer Constants (b) Real Constants

Integer Constants

A whole number is an integer constant Integer constants do not

have a decimal point. These are further divided into three types

depending on the number systems they belong to. They are:

i. Decimal integer constants

ii. Octal integer constants

Page 84 of 198
Introduction to Problem Solving - CSC 102

iii. Hexadecimal integer constants

A decimal integer constant is characterised by the

following properties:

1. It is a sequence of one or more digits ([0…9], the

symbols of the decimal number system).

2. It may have an optional + or – sign. In the absence of

a sign, the constant is assumed to be positive.

3. Commas and blank spaces are not permitted.

4. It should not have a period as part of it.

Some examples of valid decimal integer

constants: 456

-123

Some examples of invalid decimal integer constants:

4.56 - Decimal point is not

permissible 1,23 - Commas are

not permitted

An octal integer constant is characterised by the

following properties:

1. It is a sequence of one or more digits ([0…7],

symbols of the octal number system).

2. It may have an optional + or – sign. In the absence of

a sign, the constant is assumed to be positive.


Page 85 of 198
Introduction to Problem Solving - CSC 102

3. It should start with the digit 0.

4. Commas and blank spaces are not permitted.

5. It should not have a period as

part of it. Some examples of valid

octal integer constants:

0456

-0123

+0123

Some examples of invalid octal integer constants:

04.56 - Decimal point is not

permissible 04,56 - Commas

are not permitted

x34 - x is not permissible

symbol 568 - 8 is not a

permissible symbol

An hexadecimal integer constant is characterised by

the following properties:

1. It is a sequence of one or more symbols

([0…9][A….Z], the symbols of the hexadecimal

number system).

2. It may have an optional + or - sign. In the absence of

a sign, the constant is assumed to be positive.


Page 86 of 198
Introduction to Problem Solving - CSC 102

3. It should start with the symbols 0X or 0x.

4. Commas and blank spaces are not permitted.

5. It should not have a period as part of it.

Some examples of valid hexadecimal integer constants:

0x456

-0x123 0x56A

0XB78

Some examples of invalid hexadecimal integer

constants: 0x4.56 - Decimal point is not permissible

0x4,56 - Commas are not permitted.

Real Constants

The real constants, also known as floating point constants are

written in two forms:

(i) Fractional form, (ii) Exponential form.

Fractional Form

The real constants in fractional form are characterised by the

following characteristics:

1. Must have at least one digit.

2. Must have a decimal point.

3. May be positive or negative and in the absence of a sign it

is taken as positive.

Page 87 of 198
Introduction to Problem Solving - CSC 102

4. Must not contain blanks or commas in between digits.

5. May be represented in exponential form, if the

value is too high or too low.

Some examples of valid real constants:

456.78

-123.56

Some examples of invalid real constants:

4.56 - Blank spaces are not permitted

4,56 - Commas are not permitted

456 - Decimal point missing

Exponential Form

The exponential form offers a convenient way for writing very large

and small real constants. For example, 56000000.00, which can

be written as 0.56

*, 108 is written as 0.56E8 or 0.56e8 in exponential form.

0.000000234, which can be written as 0.234 * 10-6 is written as

0.234E-6 or 0.234e-6 in exponential form. The letter E or e stands


for exponential form.

A real constant expressed in exponential form has two parts: (i)

Mantissa part, (ii) Exponent part. Mantissa is the part of the real

constant to the left of E or e, and the exponent of a real constant

Page 88 of 198
Introduction to Problem Solving - CSC 102

is to the right of E or e. The mantissa and exponent of the two

numbers above are shown below.

Table 6.2: Mantissa and Exponent of two numbers

Mantis Expon Mantis Expon

sa ent sa ent

0.5 E8 0.2 E

6 34 -6

In the above examples, 0.56 and 0.234 are the mantissa parts of

the first and second numbers, respectively, and 8 and -6 are the

exponent parts of the first and second numbers, respectively.

The real constants in exponential form and are characterised by

the following characteristics:

1. The mantissa must have at least one digit.

2. The mantissa is followed by the letter E or e and the

exponent.

3. The exponent must have at least one digit and must be an

integer.

4. A sign for the exponent is optional. Some examples of

valid real constants:

3E4

23e-6

Page 89 of 198
Introduction to Problem Solving - CSC 102

0.34E6

Some examples of invalid real constants:

23E - No digit specified for exponent

23e4.5 - Exponent should not be

a fraction 23,4e5 - Commas are not

allowed

256*e8- * not allowed

Character Constants

Any character enclosed within single quotes (‘) is called character

constant.

A character constant:

1. May be a single alphabet, single digit or single

special character placed within single quotes.

2. Has a maximum length of 1 character.

Here are some examples, ‘C’, ‘c’, ‘:’, ‘*’

String Constants

A string constant is a sequence of alphanumeric characters

enclosed in double quotes whose maximum length is 255

characters.

The following are examples of valid string constants:

“My name is Krishna”, “Bible”, “Salary is 18000.00”

Page 90 of 198
Introduction to Problem Solving - CSC 102

The following are examples of invalid string constants:

My name is Krishna - Characters are not enclosed in double

quotation marks.

“My name is Krishna - Closing double quotation mark is missing.

‘My name is Krishna’ - Characters are not enclosed in double

quotation marks

6.5.2 Reserved Words/Keywords

In C, some words are reserved to do specific tasks intended for

them and are called "keywords" or "reserved words”. The list

reserved words are:

Auto Do goto

Break Double if

Case Else int

Char Extern long

Continue Float register

Default For return

Short Sizeof static

Struct Switch typedef

Union Unsigned void

While Const entry

Page 91 of 198
Introduction to Problem Solving - CSC 102

Violate Enum noalias

6.5.3 Delimiters

This is a symbol that has syntactic meaning and significance.

These will not specify any operation to result in a value. C

language delimiters list is given below

Symbol Name Meaning

# Hash Pre-processor directive

, comma Variable delimiter to

separate variable

: Colon label delimiter

; Semicolon statement delimiter

() parenthesis used for expressions

{} curly braces used for blocking of

statements

[] square braces used along with arrays

6.5.4 Variables / Identifiers

These are the names of the objects, whose values can be

changed during the program execution. Variables are named with

a description that transmits the value they hold.

[A quantity of an item that can change its value during the

execution of a program is called a variable. It is also known as an

Page 92 of 198
Introduction to Problem Solving - CSC 102

Identifier].

Rules for naming a variable:-

1. It can be of letters, digits and underscore( _ )

2. First letter should be a letter or an underscore, but

it should not be a digit.

3. Reserve words cannot be used as

variable names. Example: basic, root,

rate, roll-no etc are valid names.

Declaration of variables:

Syntax Type Variable list

Int i, j i, j are declared as integers

Float Salary Salary is declared ad floating

point variable

Char Sex Sex is declared as character

variable

6.6 Operators

An Operator is a symbol that operates on a certain data type. The

data items that operators act upon are called operands. Some

operators require two operands, some operators act upon only

one operand. In C, operators can be classified into various

categories based on their utility and action.


Page 93 of 198
Introduction to Problem Solving - CSC 102

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and Decrement Operators

6. Conditional Operator

7. Bitwise Operator

8. Comma Operator

6.6.1 Arithmetic Operators

The arithmetic operator performs arithmetic operations. The

arithmetic operators can operate on any built in data type. A List of

arithmetic operators are

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo division

6.6.2 Relational Operators

Page 94 of 198
Introduction to Problem Solving - CSC 102

Relational Operators are used to compare arithmetic, logical and

character expressions. The Relational Operators compare their

left hand side expression with their right hand side expression.

Then evaluates to an integer. If the Expression is false it evaluate

to “zero”(0) if the expression is true it evaluate to “one”

Operator Meaning

< Less than

> Greater than

<= Less than or Equal to

>= Greater than or Equal to

== Equal to

!= Not Equal to

The relational operators are represented in the following

manner: Expression-1 (Relational Operator)

Expression-2

Expression-1 will be compared with Expression -2 and depending

on the relation, the result will be either “TRUE” OR “FALSE”.

Examples :

Expression Evaluate to

(5 <= 10) ———————— TRUE

(-35 > 10) ———————— FALSE

Page 95 of 198
Introduction to Problem Solving - CSC 102

(X < 10) ———————— If the value of x is less than 10, TRUE;

otherwise, FALSE.

(a + b) = = ( c + d ) If the sum of a and b equals the sum of c,

d is TRUE; otherwise, it is FALSE.

6.6.3 Logical Operators

A logical operator is used to evaluate logical and relational

expressions. The logical operators act on operands that are

themselves logical expressions. There are three logical operators.

Operators Expression

&& Logical AND

|| Logical OR

! Logical NOT

Logical And (&&):

A compound expression is true when two expressions are true.

The && is used in the following manner.

Exp1 && Exp2.

The result of a logical AND operation will be true only if both operands are

True

The results of logical operators are:

Page 96 of 198
Introduction to Problem Solving - CSC 102

Example:

a = 5; b = 10; c = 15;

Exp1 Exp2 Result

1. ( a< b ) && ( b < c ) => True

2. ( a> b ) && ( b < c ) => False

3. ( a< b ) && ( b > c ) => False

4. ( a> b ) && ( b > c ) => False

Logical OR:

A compound expression is false when all expressions are false;

otherwise, the compound expression is true. The operator “||” is

used as It evaluates to true if either exp-1 or exp-2 is true.

Example:

a = 5; b = 10; c = 15;

Exp1 Exp2 Result

1. ( a< b ) || ( b < c ) => True

2. ( a> b ) || ( b < c ) => True

3. ( a< b ) || ( b > c ) => True

4. ( a> b ) || ( b > c ) => False

Page 97 of 198
Introduction to Problem Solving - CSC 102

Logical NOT:

The NOT ( ! ) operator takes a single expression and evaluates to

true(1) if the expression is false (0) or it evaluates to false (0) if

expression is true (1). The general form of the expression.

! ( Relational Expression )

Example:

a = 5; b = 10; c = 15

1. !( a< b ) False

2.!( a> b ) True

6.6.4 Assignment Operator

An assignment operator is used to assign a value to a variable. The

most commonly used assignment operator is =. The general

format for assignment operator is :

<Identifier> = < expression >

Where identifier represent a variable and expression represents a

constant, a variable or a Complex expression.

If the two operands in an assignment expression are of different

data types, then the value of the expression on the right will

automatically be converted to the type of the identifier on the left.

Page 98 of 198
Introduction to Problem Solving - CSC 102

Example:

Suppose that I is an Integer type Variable then

1. I = 3.33 ( Value of I )

2.I = 3.93 ( Value of I )

3.I = 5.745 ( Value of I )

Multiple assignment

< identifier-1 > = < identifier-2 > = - - - = < identifier-n > =

<exp>;

Example:

a,b,c are integers; j is float variable

1. a = b = c = 3;

2. a = j = 5.6; then a = 5.6 and j value will be 5.6

C contains the following five additional assignment operators

1. +=

2. -=

3. +=

4. *=

5. /=

The assignment expression is: - Exp1 < Operator> Exp-2

Page 99 of 198
Introduction to Problem Solving - CSC 102

Example:

I = 10 (assume that)

Expression Equivalent to Final Value of ‘I’

1. I + = 5; I = I + 5; result = 15

2. I - = 5; I = I - 5; result = 10

3. I * = 5; I = I * 5; result = 50

4. I / = 5; I = I / 5; result = 10

6.6.5 Increment & Decrement Operator

The increment & decrement operator acts upon a Single operand

and produces a new value, it is also called “unary operator”. The

increment operator ++ adds 1 to the operand and the Decrement

operator – subtracts 1 from the operand.

Syntax: < operator >< variable name >;

The ++ or – operator can be used in two ways:

++a; Pre-increment (or) a++ Post increment —a; Pre- Decrement (or) a—

Post decrement

1. ++ a Immediately increments the value of a by 1.

2. a ++ The value of a will be incremented by 1 after it is utilized.

Example 1:

Suppose a = 5 ;

Page 100 of 198


Introduction to Problem Solving - CSC 102

Statements; Outputs

printf ( “a value is %d”, a ); a value is 5

printf ( “a value is %d”, ++ a ); a value is 6

printf ( “a value is %d “, a) ; a value is 6

Example 2:

Suppose : a = 5 ;

Statements; Output

printf (“a value is %d “, a); a value is 5

printf (“a value is %d “, a++); a value is 5

printf (“a value is %d “,a); a value is 6

a and a- will be act on operand by decrement value like

increment operator.

6.6.6 Conditional operator (or) Ternary operator (? :)

It is called ternary because it uses three expressions. The ternary

operator acts like If- Else construction.

Syn :( <Exp –1 > ? <Exp-2> : <Exp-3> );

Expression-1 is evaluated first. If Exp-1 is true, then Exp-2 is

evaluated; otherwise, Exp-3 will be evaluated.

Flow Chart :

Exp-1
Page 101 of 198
Introduction to Problem Solving - CSC 102

Exp-2

Exp-3 Exit

Example:

1. a = 5 ; b = 3;

( a> b ? printf (“a is larger”) : printf (“b is larger”));

Output is :a is larger

2. a = 3; b = 3;

(a> b ? printf (“a is larger”) : printf (“b is larger”));

Output is :b is larger

6.6.7 Bit wise Operator

A bitwise operator operates on each bit of data. These bitwise

operators can be divided into three categories.

i. The logical bitwise operators.

ii. The shift operators

iii. The one’s complement operator.

The logical Bitwise Operator

There are three logical bitwise operators.

Meaning Operator:

Page 102 of 198


Introduction to Problem Solving - CSC 102

a)Bitwise AND &

b)Bitwise OR |

c) Bitwise exclusive XOR ^

Suppose b1 and b2 represent the corresponding bits within the first and

second operands, respectively.

B1 B2 B1 & B2 B1 | B2 B1 ^ B2

11110

10011

01011

00000

The operations are carried out independently on each pair of

corresponding bits within the operand, thus the least significant

bits (i.e., the rightmost bits) within the two operands. Will be

compared until all the bits have been compared. The results of

these comparisons are

A Bitwise AND expression will return a 1 if both bits have a value of 1.

Otherwise, it will return a value of 0.

A Bitwise OR expression will return a 1 if one or more of the bits

have a value of 1. Otherwise, it will return a value of 0.

A Bitwise EXCLUSIVE OR expression will return a 1 if one of the

bits has a value of 1 and the other has a value of 0. Otherwise, it

Page 103 of 198


Introduction to Problem Solving - CSC 102

will return a value of 0.

Example:

Variable Value Binary Pattern

X 5 0101

Y 2 0010

X & Y 0 0000

X | Y 7 0111

X ^ Y 7 0111

The Bitwise shift Operations:

The two bitwise shift operators are Shift left (<<) and Shift right

(>>). Each operator requires two operands. The first operand that

represents the bit pattern to be shifted. The second is an

unsigned integer that indicates the number of displacements.

Example:

c = a << 3;

The value in the integer a is shifted to the left by three -bit position. The

result is assigned to c.

Page 104 of 198


Introduction to Problem Solving - CSC 102

A = 13; c= A<<3;

Left shift << c= 13 * 2 3 = 104;

Binary number 0000 0000 0000 1101

After left bit shift by 3 places

ie,. a<<3 0000 0000 0110

1000

The right –bit – shift operator ( >> ) is also a binary operator.

Example:

c = a >> 2 ;

The value of a is shifted to the right

by 2 position insert 0’s Right – shift

>> drop off 0’s

0000 0000 0000 1101

After right shift by 2 places

is a>>2 0000 0000 0000

0011 c=13>>2 c= 13/4=3

Bit wise complement:

The complement operator switches all the bits in a binary pattern,

i.e., all the 0s become 1s and all the 1s become 0s.

Variable; value Binary 8-bit

Page 105 of 198


Introduction to Problem Solving - CSC 102

x = 23 0001 0111 (Original)

~x =132 1110 1000 (Complement)

6.6.8 Comma Operator

A set of expressions separated by commas is a valid construction

in C.

Example :

int i, j; i= ( j =

3, j + 2 ) ;

The first expression is j = 3, and second is j + 2. These

expressions are evaluated from left to right. From the

above example, I = 5.

Size of operator:

The operator size gives the size of the data type or variable in

terms of bytes occupied in the memory. This operator allows a

determination of the number of bytes allocated to various data

items.

Example :

int i; float x; double d; char c; OUTPUT

Printf (“integer : %d\n”, sizeof(i)); Integer : 2

Printf (“float : %d\n”, sizeof(i)); Float : 4

Printf (“double : %d\n”, sizeof(i)); double : 8

Printf (“char : %d\n”,sizeof(i)); character : 1


Page 106 of 198
Introduction to Problem Solving - CSC 102

Conclusion

This session introduced the students to the C programming language, its

features, structures, various data types, tokens, operators used for basic

operations, and input and output statements. More information will be

taught in the next study session.

Summary

In this session, you have learned to:

1. What is C Language and its importance?

2. Explain the features of C language

3. Understand various data types

4. Understand working function of input and output statements in C

5. Understand operators in C-programming language

Self-Assessment Questions (SAQ)

SAQ6.1. What are the different components of the structure of a C

program?(Tests learning outcome 6.2)

SAQ6.2. What is the purpose of preprocessor statements in a C

program? Give some examples.(Tests learning outcome 6.2)

SAQ6.3. What are global declarations in a C program? Where

Page 107 of 198


Introduction to Problem Solving - CSC 102

should they be made?(Tests learning outcome 6.2)

SAQ6.4. Why is the main() function important in a C program? Can

a program run without it?(Tests learning outcome 6.2)

SAQ6.5. What are delimiters in C? Provide examples of different

delimiters.(Tests learning outcome 6.3)

SAQ6.6. What are variables/identifiers in C programming?(Tests

learning outcome 6.3)

SAQ6.7. What are the different categories of operators in C?.(Tests

learning outcome 6.6)

SAQ6.8. How do relational operators work in C? Give examples of

their usage.(Tests learning outcome 6.6)

Self-Assessment Answers (SAA)

SAA6.1. The components of the structure of a C program includes:

● main() function

● Pair of braces {}

● Declarations and statements

● User-defined functions

● Preprocessor statements

● Global declarations

SAA6.2. Preprocessor statements in a C program, indicated by the

# symbol, direct the C preprocessor to include header files and

define symbolic constants. They provide instructions to the

compiler before the actual compilation process.

Page 108 of 198


Introduction to Problem Solving - CSC 102

SAA6.3. The main() function is the central function of every C

program. It serves as the starting point of program execution and

must be present in every C program. It calls other library functions

and user-defined functions.

SAA6.4. Braces, represented by {}, are used to define the

beginning and end of various sections in a C program, including the

main() function, user-defined functions, and compound

statements. They help in grouping statements together.

SAA6.5. Delimiters in C programming are symbols that have

syntactic meaning and significance. Some examples include: #

(hash), comma, colon, semicolon, parentheses (), curly braces {},

square braces [], etc.

SAA6.6. Variables/identifiers are names given to objects in a C

program whose values can be changed during program execution.

They are used to store and manipulate data. Variables are declared

with a specific data type and naming conventions need to be

followed.

SAA6.7. There are various types of operators, they include the

following:

● Arithmetic Operators:

Arithmetic operators are used to perform mathematical

calculations.

Examples: + (addition), - (subtraction), * (multiplication), /

(division), % (modulo)

Page 109 of 198


Introduction to Problem Solving - CSC 102

● Relational Operators:

Relational operators are used to compare values and

determine the relationship between them.

Examples: == (equal to), != (not equal to), < (less than), >

(greater than), <= (less than or equal to), >= (greater than or

equal to)

● Logical Operators:

Logical operators are used to perform logical operations on

Boolean expressions or values.

Examples: && (logical AND), || (logical OR), ! (logical NOT)

● Assignment Operators:

Assignment operators are used to assign values to variables.

Examples: = (simple assignment), += (addition assignment),

-= (subtraction assignment), *= (multiplication assignment),

/= (division assignment), %= (modulo assignment)

● Increment and Decrement Operators:

Increment and decrement operators are used to increase or

decrease the value of a variable by 1.

Examples: ++ (increment), -- (decrement)

● Bitwise Operators:

Bitwise operators are used to perform operations at the bit

level.

Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~

(bitwise NOT), << (left shift), >> (right shift)

Page 110 of 198


Introduction to Problem Solving - CSC 102

● Conditional Operator (Ternary Operator):

The conditional operator is a shorthand way of writing if-else

statements.

Example: (condition) ? (expression1) : (expression2)

● Comma Operator:

The comma operator is used to separate expressions and

evaluate them sequentially. The value of the entire

expression is the value of the last expression.

Example: expression1, expression2, expression3

SAA6.8. Relational operators in C programming are used to

compare values and evaluate logical and relational expressions.

They include: < (less than), > (greater than), <= (less than or equal

to), >= (greater than or equal to), == (equal to), and != (not equal

to).

Tutor-Marked Assignment

1. Explain the basic structure of a C program.

2. Write about data types used in C

3. What is Constant? Explain various types of constants in C.

4. Explain various types of Operators in C.

5. Explain formatted and unformatted input and output statements in

References/Further Reading

Page 111 of 198


Introduction to Problem Solving - CSC 102

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics. Association for Computational Linguistics.

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 112 of 198


Introduction to Problem Solving - CSC 102

Study Session 7: Expressions in C-Language

Introduction

An expression is a combination of operators, constants, and variables. An

expression may consist of one or more operands, and zero or more

operators to produce a value.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

7.1. Explain the expression and statements in C-Language

7.2. Have knowledge of the evaluation procedure.

7.3. Understand the various types of input and output

statements.

7.4. Understanding the importance of assignment statements.

7.1 Expression

An expression can be defined as a collection of data objects and

operators that can be evaluated to lead to a single new data

object. A data object is a constant, variable, or another data

object.

Example:

a+b

x + y + 6.0
Page 113 of 198
Introduction to Problem Solving - CSC 102

3.14 * r * r

( a + b ) * ( a – b)

The above expressions are called arithmetic expressions because the

data objects (constants and variables) are connected using arithmetic

operators.

7.2 Evaluation Procedure

The evaluation of arithmetic expressions is as per the hierarchy

rules governed by the C compiler. The precedence or hierarchy

rules for arithmetic expressions are:

1. The expression is scanned from left to right.

2. While scanning the expression, the evaluation preference

for the operators are (*, /, %) are evaluated first and (+, -)

are evaluated next.

3. To overcome the above precedence rules, the user has to

make use of parentheses, if parentheses are used, the

expression/expressions are evaluated first as per the above

hierarchy.

7.3 Statements

7.3.1 Data Input & Output

Page 114 of 198


Introduction to Problem Solving - CSC 102

An input/output function can be accessed from anywhere within a

program simply by writing the function name followed by a list of

arguments enclosed in parentheses. The arguments represent

data items that are sent to the function.

Some input/output functions do not require arguments, though

empty parentheses must still appear. They are:

Table 7.1 : Input and Output statements in C

Input Output
Statements Statements
Formatted scanf() printf()

Unformatted getchar() putchar()

gets() puts()

getchar()

Single characters can be entered into the computer using the C

library Function getchar(). It returns a single character from a

standard input device. The function does not require any

arguments.

Syntax: <Character variable> = getchar();

Example:

char c;

c = getchar();

Page 115 of 198


Introduction to Problem Solving - CSC 102

putchar()

Single characters can be displayed using the function putchar().

It returns a single character to a standard output device. It must

be expressed as an argument to the function.

Syntax: putchar(<character variable>);

Example:

char c;

putchar( c );

gets()

The function gets() receives the string from the standard input device.

Syntax: gets(<string type variable or array of char> ); Where s is a string.

The function accepts the string as a parameter from the

keyboard, until a newline character is encountered. At the

end, the function appends a “null” terminator and returns.

puts()

The function puts() outputs the string to the standard output device.

Conversion Characters Characters Meaning

%c data item is a single character.

Page 116 of 198


Introduction to Problem Solving - CSC 102

%d data item is a decimal integer.

%f data item is a floating-point value.

%e data item is a floating- point value.

%g data item is a floating-point value.

%h data item is a short integer.

%s data item is a string.

%x data item is a hexadecimal integer.

%o data item is an octal integer.

printf()

The printf() function is used to print the data from the computer’s

memory onto a standard output device. This function can be used

to output any combination of numerical values, single characters,

and strings.

Syntax: printf(“control string”, arg-1, arg-2,———arg-n );

Where control string is a string that contains formatted

information, and arg-1, arg-2 —— are arguments that

represent the output data items.

Example:

Page 117 of 198


Introduction to Problem Solving - CSC 102

#include<st

dio.h> main()

char

item[20];

int partno;

float cost;

———————

printf (“%s %d %f”, item, partno, cost);

Syntax: puts(s);

Where s is a string that was real with gets();

Example:

main()

char line[80];

gets(line);

puts(line);

scanf()

Page 118 of 198


Introduction to Problem Solving - CSC 102

Scanf() function can be used to input the data into memory from

the standard input device. This function can be used to enter any

combination of numerical values, single characters, and strings.

The function returns a number of data item characters.

Syntax:-scanf (“control strings”, &arg1,&arg2,——&argn);

Where control string refers to a string containing certain

required formatting information and arg1, arg2——argn are

arguments that represent the individual input data items.

Example:

#include<st

dio.h> main()

char

item[20];

int partno;

float cost;

scanf(“%s %d %f”,&item,&partno,&cost);

Where s, d, and f with % are conversion characters. The

conversion characters indicate the type of the

corresponding data. Commonly used conversion

Page 119 of 198


Introduction to Problem Solving - CSC 102

characters from data input.

} (Where %s %d %f are conversion characters.)

7.4 Assignment Statement

Assignment statement can be defined as the statement through which

the value obtained from an expression can be stored in a variable. The

general form of assignment statement is

< variable name> = < arithmetic expression> ;

Example:

sum = a + b + c;

tot = s1 + s2 + s3;

area = ½ * b* h;

Conclusion

This session introduced the students to expressions in C-language, input

and output statements, and the working functions of branching

statements in C language. The looping statements and break statements

were also examined in this session.

Summary

In this session, you have learned to:

Page 120 of 198


Introduction to Problem Solving - CSC 102

1. Explain the expression meaning in C-Language

2. Understand working function of Branching statements in C

3. Understand working function of Looping statements in C

4. Understand differences between Break and Continue

Self-Assessment Questions (SAQ)

SAQ7.1. What are statements in C programming?(Tests learning

outcome 7.1)

SAQ7.2. What is the purpose of input/output functions in C?(Tests

learning outcome 7.3)

SAQ7.3. Provide examples of input and output statements in

C.(Tests learning outcome 7,3)

SAQ7.4. Explain the purpose and usage of the getchar()

function.(Tests learning outcome 7.3)

SAQ7.5. How is the putchar() function used in C?(Tests learning

outcome 7.3)

Self-Assessment Answers (SAA)

SAA7.1. Statements in C programming are individual instructions

or commands that make up a program. They are used to perform

specific actions or operations.

SAA7.2. The purpose of input/output functions in C is to allow the

program to interact with the user and the external environment.

Page 121 of 198


Introduction to Problem Solving - CSC 102

These functions enable the program to take input from the user,

display output on the screen, read/write files, and perform other

input/output operations.

SAA7.3. Examples of input statements in C include:

scanf() - used to read input from the user.

getchar() - used to read a single character from the standard input.

gets() - used to read a string from the standard input.

Examples of output statements in C include:

printf() - used to display output on the screen.

putchar() - used to display a single character on the screen.

puts() - used to display a string on the screen.

SAA7.4. The getchar() function is used to read a single character

from the standard input (usually the keyboard). It does not require

any arguments. The function waits for the user to enter a character

and returns that character. The character can be stored in a variable

for further processing.

SAA7.5. The putchar() function is used to display a single

character on the standard output (usually the screen). It takes a

single character as an argument and outputs it. The character to be

displayed can be a literal character or a character stored in a

variable.

Page 122 of 198


Introduction to Problem Solving - CSC 102

Tutor-Marked Assignment

1. What is the gets() function used for? Provide its syntax.

2. Explain the purpose and usage of the puts() function.

3. What are conversion characters in C's printf() function? Provide

some examples.

4. Describe the usage of the scanf() function in C. Give an example.

5. What is an assignment statement in C?

6. How is an assignment statement formed?

7. Give examples of assignment statements in C.

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics.

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/
Page 123 of 198
Introduction to Problem Solving - CSC 102

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 124 of 198


Introduction to Problem Solving - CSC 102

Study Session 8: Control Structure

Introduction

Control structures are simply a method for specifying control flow in

programs. Any algorithm or program can be made more transparent and

comprehensible by employing modules known as logic or control

structures. It analyses and selects the flow direction of a program based

on certain parameters and conditions. A control structure is analogous to

a programming block that analyses variables and selects an action based

on given parameters. The term flow control describes the program's

direction (which way program control "flows"). Consequently, it is the

fundamental decision-making process in computing; it is a forecast.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

8.1. Explain the Conditional statements

8.2. Understand the if statement

8.3. Explain the if else statement

8.4. Understand the else-if statement

8.5. Describe the switch statement

Page 125 of 198


Introduction to Problem Solving - CSC 102

8.1 Conditional Statements

The conditional expressions are mainly used for decision making. The

following statements are used to perform the task of the conditional

operations.

1. if statement.

2.If-else statement or 2 way if statement

3.Nested else-if statement.

4.Nested if –else statement.

5. Switch statement.

8.1.1 if statement

The if statement is used to express conditional expressions. If the

given condition is true then it will execute the statements

otherwise skip the statements.

The simple structure of ‘if statement is

i. If (< conditional expression>)

statement-1;

(or)

ii. If (< conditional expression)

Page 126 of 198


Introduction to Problem Solving - CSC 102

statement-1; statement-2;

statement-3;

……………

…………… STATEMENT-N

The expression is evaluated, and if the expression is true, the

statements will be executed. If the expression is false, the

statements are skipped, and execution continues with the next

statements.

Example:

a=20; b=10;

if ( a > b )

printf (“big number is %d” a);

8.1.2 if-else statements

The if-else statement is used to execute either of the two statements

depending upon the value of the expression. The general form is:

if(<exp>)

Statement-1;

Statement -2;

………….. “ SET-I”
Page 127 of 198
Introduction to Problem Solving - CSC 102

……………

Statement- n;

else

Statement1;

Statement 2;

………….. “ SET-II

……………

Statement n;

SET - I statements will be executed if the

exp is true. SET – II statements will be

executed if the exp is false.

Example:

if ( a> b )

printf (“a is greater than b”);

else

printf (“a is not greater than b”);

8.1.3 Nested else-if statements


Page 128 of 198
Introduction to Problem Solving - CSC 102

In some situations, it may be desirable to nest multiple if-else

statements. In this situation, one of several different courses of

action will be selected.

Syntax

if ( <exp1> )

Statement-1;

else if ( <exp2> )

Statement-2;

else if ( <exp3> )

Statement-3;

else

Statement-4;

When a logical expression is encountered whose value is true, the

corresponding statements will be executed, and the remainder of

the nested else if statement will be bypassed. Thus, control will be

transferred out of the entire nest once a true condition is

encountered.

The final else clause will be applied if none of the expressions is true.

8.1.4 Nested if-else statement

It is possible to nest if-else statements, one within another. There

Page 129 of 198


Introduction to Problem Solving - CSC 102

are several different forms that a nested if-else statement can

take.

The most general form of two-layer nesting is

if(exp1){

if(exp2){

statement - 1;}

else{

statement - 2;}

else{

if (exp3){

statement - 3;}

else{

statement - 4;}

One complete if-else statement will be executed if expression 1 is

true, and another complete if-else statement will be executed if

expression 1 is false.

Page 130 of 198


Introduction to Problem Solving - CSC 102

8.1.5 Switch statement

A switch statement is used to choose a statement (for a group of

statements) among several alternatives. The switch statement is

useful when a variable is to be compared with different constants,

and in case it is equal to a constant, a set of statements are to be

executed.

Syntax:

Switch (exp){

case constant1 :

statement-1;

break;

case constant2 :

statement-2;

break;

default :

statement-3;}

Where constant1, constant2, — — — are either integer constants or

character constants. When the switch statement is executed, the exp is


Page 131 of 198
Introduction to Problem Solving - CSC 102

evaluated and control is transferred directly to the group of statements

whose case label value matches the value of the exp. If none of the case

label values match the value of the exp, then the default part statements

will be executed.

If none of the case labels match the value of the exp and the

default group is not present, then no action will be taken by the

switch statement and control will be transferred out of the switch

statement.

A simple switch statement is illustrated below.

Example 1:

main()

char choice;

printf(“Enter Your Color (Red - R/r, White – W/w)”);

choice=getchar();

switch(choice= getchar())

case‘r’:

case‘R’:

printf

(“Red”);
Page 132 of 198
Introduction to Problem Solving - CSC 102

break;

case‘w’:

case‘W’:

printf (“white”); break;

default :

printf (“no colour”);

Example 2:

switch(day)

case 1:

printf

(“Monday”);

break;

———

———

Conclusion

This session introduced the students to conditional statements, the if

statement, the if else statement, and the nested if else statement. The

Page 133 of 198


Introduction to Problem Solving - CSC 102

switch statement and else-if statement were also examined in this

session.

Summary

In this session, you have learned to:

1. Explain the Conditional statements

2. Understand the if statement

3. Explain the if else statement

4. Understand the else-if statement

5. Describe the switch statement

Self-Assessment Questions (SAQ)

SAQ8.1. What are the different types of conditional statements

mentioned in the text?(Tests learning outcome 8.1)

SAQ8.2. How does the "if" statement work in C? Provide an

example.(Tests learning outcome 8.2)

SAQ8.3. Explain the purpose and structure of the "if-else"

statement in C. Give an example.(Tests learning outcome 8.3)

SAQ8.4. What is the purpose of nested else-if statements? Provide

the syntax and explain their execution.(Tests learning outcome 8.4)

SAQ8.5. What is the switch statement used for in C? Provide its

syntax and explain how it works.(Tests learning outcome 8.5)

Page 134 of 198


Introduction to Problem Solving - CSC 102

Self-Assessment Answers (SAA)

SAA8.1. The different types of conditional statements mentioned

in the text are:

● if statement

● if-else statement

● nested else-if statement

● nested if-else statement

● switch statement

SAA8.2. The "if" statement in C is used to express conditional

expressions. It evaluates a condition and executes a block of

statements if the condition is true. If the condition is false, the block

of statements is skipped.

Example:

int num = 10;

if (num > 0) {

printf("The number is positive.");

SAA8.3. The purpose of the "if-else" statement is to execute

different blocks of code based on the condition. If the condition is

true, the statements in the "if" block are executed. If the condition

is false, the statements in the "else" block are executed.

Example:

Page 135 of 198


Introduction to Problem Solving - CSC 102

int num = 10;

if (num % 2 == 0) {

printf("The number is even.");

} else {

printf("The number is odd.");

SAA8.4. Nested else-if statements allow for multiple conditions to

be checked in a sequential manner. They are useful when there are

multiple possible courses of action based on different conditions.

Syntax:

if (condition1) {

// Statements if condition1 is true

} else if (condition2) {

// Statements if condition1 is false and condition2 is true

} else {

// Statements if both condition1 and condition2 are false

Execution: When a logical expression is encountered whose value is

true, the corresponding statements are executed, and the rest of

the nested else-if statement is bypassed. If none of the conditions

are true, the statements in the else block are executed.

SAA8.5. The switch statement in C is used to choose a statement

(or a group of statements) among several alternatives based on the

Page 136 of 198


Introduction to Problem Solving - CSC 102

value of a variable. It provides a convenient way to handle multiple

cases efficiently.

Syntax:

switch (expression) {

case constant1:

// Statements for constant1

break;

case constant2:

// Statements for constant2

break;

default:

// Statements when none of the cases match

How it works: The expression is evaluated, and its value is compared

with the constant values specified in each case. If a match is found,

the corresponding statements are executed. The "break"

statement is used to exit the switch block. If none of the cases

match and a default case is present, the statements in the default

block are executed. If there is no match and no default case, the

switch statement is skipped.

Tutor-Marked Assignment

1. Write about ‘Switch” Statement.

Page 137 of 198


Introduction to Problem Solving - CSC 102

2. Write the syntax of Simple if statement.

3. Write the syntax of if … else statement.

4. What is a Preprocessor statement in C?

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics Association for Computational Linguistics.

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

Page 138 of 198


Introduction to Problem Solving - CSC 102

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html.

Page 139 of 198


Introduction to Problem Solving - CSC 102

Study Session 9: Looping Structures

Introduction

Loops are among the most basic and powerful programming concepts. A

loop in a computer program is an instruction that repeats until a specified

condition is reached. In a loop structure, the loop asks a question. If the

answer requires action, it is executed. The same question is asked again

and again until no further action is required. Each time the question is

asked, it is called an iteration. A computer programmer who needs to use

the same lines of code many times in a program can use a loop to save

time. Just about every programming language includes the concept of a

loop.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

9.1.Understand working function of looping statements in C

9.2. Understand the differences between each looping statements in

9.3. Understand differences between Break and Continue

9.4. Understand the working function of a goto statement

9.1 Loop Statement


Page 140 of 198
Introduction to Problem Solving - CSC 102

Loop statements are used to execute the statements repeatedly

as long as an expression is true. When the expression becomes

false, the control is transferred out of the loop. There are three

kinds of loops in C, they are while loop, do-while loop, and for loop.

9.1.1 While statement

While loop will be executed as long as the exp is true.

Syntax:

while (exp)

statements;

The statements will be executed repeatedly as long as the exp is

true. If the exp is false, then the control is transferred out of the

while loop.

Example:

int digit = 1;

While (digit <=5) FALSE

printf (“%d”, digit);


Page 141 of 198
Introduction to Problem Solving - CSC 102

TRUE Cond Exp

Statements; ++digit;

The while loop is top tested i.e., it evaluates the condition before

executing statements in the body. Then it is called an entry control loop.

9.1.2 do-while statement

The do-while loop evaluates the condition after the execution of

the statements in the body.

Syntax:

do

Statement; While<exp>;

Here also, the statements will be executed as long as the exp value

is true. If the expression is false the control comes out of the loop.

Example:

-int

d=1;

do

printf (“%d”, d); FALSE

++d;

Page 142 of 198


Introduction to Problem Solving - CSC 102

} while (d<=5);

TRUE Cond Exp

statements;

exit

The statement within the do-while loop will be executed at least

once. So the do-while loop is called a bottom tested loop.

9.1.3 for statement

The for loop is used to execute the structure a number of times.

The for loop includes three expressions. First expression specifies

an initial value for an index (initial value), second expression that

determines whether or not the loop is continued (conditional

statement) and a third expression used to modify the index

(increment or decrement) of each pass.

Note: Generally, a for loop is used when the number of iteration is

known in advance.

Syntax:

for (exp1;exp2;exp3)

Page 143 of 198


Introduction to Problem Solving - CSC 102

Statement –1;

Statement – 2;

} —————; FALSE

exp2 —————;

Statement - n; TRUE

exp3

Statements;

Exit

loop

exp1

start

Where expression-1 is used to initialise the control variable. This

expression is only run once, at the start of the loop.

Where expression-2 is a logical expression. If expression-2 is

true, the statements will be executed, otherwise, the loop will be

terminated. This expression is evaluated before every execution of

the statement.

Where expression-3 is an increment or decrement expression,

after executing the statements, the control is transferred back to

expression-3 and updated. There are different formats available

Page 144 of 198


Introduction to Problem Solving - CSC 102

in a for loop. Some of the expressions in a loop can be omitted.

Format - I

for( ; exp2; exp3

) Statements;

In this format the initialization expression (i.e., exp1) is omitted.

The initial value of the variable can be assigned outside of the for

loop.

Example 1

int i = 1;

for( ; i<=10;

i++ ) printf

(“%d \n”, i);

Format - II

for( ; exp2 ; )

Statements;

In this format, the initialization and increment or

decrement expressions (i.e., expression-1 and

expression-3) are omitted. The exp-3 can be given in the

statement part.

Example 2

int i = 1;

Page 145 of 198


Introduction to Problem Solving - CSC 102

for( ; i<=10; )

printf (“%d

\n”,i); i++;

Format - III

for( ; ; )

Statements;

In this format the three expressions are omitted. The loop itself

assumes the expression-2 is true. So, the statements will be

executed infinitely.

Example 3

int i = 1;

for ( ; i<=10; )

printf (“%d

\n”,i); i++;

9.2 Nested Looping Statements


Page 146 of 198
Introduction to Problem Solving - CSC 102

Many applications require nesting of the loop statements, allowing

one statement to be embedded within another loop statement.

9.2.1 Definition of Nesting

Nesting can be defined as the method of embedding one control

structure into another control structure.

While making the control structure reside within another, the

inner and outer control structures may be of the same type or may

not be of the same type. But, it is essential for us to ensure that

one control structure is completely embedded within another.

/*program to implement nesting*/

#include <stdio.h>

main()

int a,b,c,

for (a=1,a< 2, a++)

printf (“%d”,a)

for (b=1,b<=2,b++)

Page 147 of 198


Introduction to Problem Solving - CSC 102

print f(%d”,b)

for (c=1,c<=2,c++)

print f( “ My Name is Sunny \n”);

9.3 Multi-Objective Loops

For effective handling of the loop structures, C allows the

following types of control break statements, break and continue

statements.

9.3.1 Break Statement

The break statement is used to terminate the control in loops or to

exit from a switch. It can be used within a while, do-while, for.

The general format is : break;

If a break statement is included in a while, do-while or for then

control will immediately be transferred out of the loop when the

break statement is encountered.

Example

for ( ; ; ) normal loop

Page 148 of 198


Introduction to Problem Solving - CSC 102

break Condition

within loop

scanf (“%d”,&n); if ( n < -1)

break;

sum = sum + n;

9.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. Rather, the remaining loop

statements are skipped, and the loop proceeds directly to the

next pass through the loop. The “continue” can be included within

a while, a do-while and a for loop statement.

General form : continue;

The continue statement is used for the inverse operation of the break

statement .

Condition with in loop

Remaining part

of loop continue

Example

while (x<=100)

Page 149 of 198


Introduction to Problem Solving - CSC 102

if (x <= 0)

printf (“zero or negative value found \n”);

continue;

The above program will execute only if a positive number is passed

as the variable.; whenever a zero or negative value is encountered,

the message will be displayed, and it will continue the same loop

as long as the given condition is satisfied.

9.4 Differences between Break and Continue statements

Table 9.1: Differences between break and continue

Break Continue

Page 150 of 198


Introduction to Problem Solving - CSC 102

1. Break is a key word 1. Continue is a keyword

used to terminate the loop used for

or exit from the block. The containing the next

control jumps to next iteration of the loop

statement after the loop or

block 2. This statement when

2. Break statements can occurs in a loop does not

be used with for, while, terminate it rather skips

do-while, and switch the statements after this

statements. When break is continue statement and

used in nested loops, then the control goes for next

only the innermost loop is iteration. ‘Continue’ can be

terminated. used with for, while and do-

while loop.

3. Syntax:{ statement1; 3. Syntax: {

statement2; statement3; statement1;

break;} continue; statement

2; statement3; break; }

4. Example :Switch ( 4. Example:- I = 1,

choice){ Case ‘y’: j=0;While( i<= 7){ I = I + 1;

printf(“yes”); break; Case ‘n’: If(( I = = 6) Continue; j = j +

printf(“NO”); break;} 1;}

5. When the case 5. In the above loop,

matches with the choice when the value of ‘ i'

Page 151 of 198


Introduction to Problem Solving - CSC 102

entered, the corresponding becomes 6 , the continue

case block gets executed. statement is executed. So,

When the ‘break’ statement j= j+1 is skipped and control

is executed, the control is transferred to the

jumps out of the switch beginning of the while loop.

statement.

9.5 Unconditional Branching (goto Statement)

The goto statement is used to alter the program execution sequence by

transferring the control to some other part of the program.

Syntax

Where label is an identifier used to label the target statement to

which control would be transferred, the target statement will

appear as:

Syntax

goto<label>;

label : statements;

Example 1

#include

<stdio.h>

Page 152 of 198


Introduction to Problem Solving - CSC 102

main();

inta,b;

printf (“Enter the two numbers”);

scanf (“%d %d”,&a,&b);

if (a>b)

gotobig;

else

gotosmall;

big :printf (“big value is %d”,a);

gotostop;

small :printf (“small value is %d”,b);

gotostop; stop}

Page 153 of 198


Introduction to Problem Solving - CSC 102

Practice Programs

1. Write a C program to find out the smallest

value among A, B,C.

Ans:

include

<stdio.h> int

a,b,c;

clrscr();

scanf(%d %d %d, &a, &b, &c);

if (a<b)

if(a<c)

printf(“a is small/n”)

else

02. Write a ‘C’ program for 5th multiplication table

with the help of goto statement.

Ans.

#include <stdio.h>

int main() {
Page 154 of 198
Introduction to Problem Solving - CSC 102

int num = 5;

int i = 1;

loop:

printf("%d x %d = %d\n", num,

i, num * i);

i++;

if (i <= 10) {

goto loop;

return 0;}

03. Write a ‘C’ program to find the greatest among

three numbers.

Ans:

#include <stdio.h>

int main() {

int num1, num2, num3;

printf("Enter three numbers: ");

scanf("%d %d %d", &num1, &num2, &num3);

Page 155 of 198


Introduction to Problem Solving - CSC 102

if (num1 >= num2 && num1 >= num3) {

printf("%d is the greatest.\n", num1);

else if (num2 >= num1 && num2 >= num3) {

printf("%d is the greatest.\n", num2);

else {

printf("%d is the greatest.\n", num3);

return 0;}

Conclusion

This session introduced the students to branching statements in C,

Looping statements in C and break and continue statements. The goto

statement was also examined in this session.

Summary

In this session, you have learned to:

1. Understand working function of Branching statements in C

2. Understand working function of Looping statements in C

3. Understand differences between Break and Continue

Page 156 of 198


Introduction to Problem Solving - CSC 102

Self-Assessment Questions (SAQ)

SAQ9.1. How can looping statements in C, such as "for" or "while,"

be used to repeatedly execute a block of code until a specific

condition is met?(Tests learning outcome 9.1)

SAQ9.2. What are some common pitfalls or mistakes to avoid when

working with looping statements in C to ensure efficient and

error-free code execution?(Tests learning outcome 9.1)

SAQ9.3. Greatly state and explain the difference between for loop

and while loop(Test learning outcome 9.2)

SAQ9.4. Purpose of the goto statement with an example.(Tests

learning outcome 9.4)

Self-Assessment Answers (SAA)

SAA9.1. Looping statements in C, such as "for" or "while," allow you

to repeatedly execute a block of code until a specific condition is

met. With a "for" loop, you define an initialization statement, a

condition that determines whether the loop should continue, and

an increment or decrement statement that modifies the loop

variable. The loop will execute the block of code as long as the

condition remains true. Similarly, a "while" loop checks the condition

before executing the code block and continues until the condition

becomes false.

Page 157 of 198


Introduction to Problem Solving - CSC 102

SAA9.2. When working with looping statements in C, it is essential

to be aware of potential pitfalls and mistakes to ensure efficient and

error-free code execution. Some common points to consider are:

Infinite loops: Be cautious of accidentally creating infinite loops

where the loop condition never becomes false. It can lead to the

program getting stuck and not progressing further.

Initialization and termination conditions: Ensure proper initialization

and termination conditions are set for your loop. Incorrect

initialization or termination conditions may cause unexpected

behaviour or incorrect results.

Increment or decrement statements: Carefully choose the

increment or decrement statements within your loop. Incorrectly

modifying the loop variable can result in undesired outcomes or

logical errors.

SAA9.3. The main differences between the "for" loop and the

"while" loop in C are:

Syntax: The syntax of a "for" loop includes an initialization

statement, a condition, and an increment or decrement statement,

all within the loop declaration. In contrast, a "while" loop only

consists of a condition without any explicit initialization or

increment/decrement statements.

Page 158 of 198


Introduction to Problem Solving - CSC 102

Example "for" loop:

for (initialization; condition; increment/decrement) {

// code to be executed

Example "while" loop:

while (condition) {

// code to be executed

Initialization: The "for" loop allows you to initialise a loop variable

within the loop declaration itself. This initialization statement is

executed only once at the beginning of the loop. The "while" loop

requires you to initialise the loop variable before the loop starts.

Condition Checking: In a "for" loop, the condition is evaluated

before each iteration. If the condition is true, the loop body is

executed. In a "while" loop, the condition is evaluated at the

beginning of each iteration. If the condition is false, the loop body is

not executed at all.

Increment/Decrement: The "for" loop provides a convenient way to

specify the increment or decrement of a loop variable within the

loop declaration. This statement is executed after each iteration of

the loop body. In a "while" loop, you need to manually include the

increment or decrement statement within the loop body.


Page 159 of 198
Introduction to Problem Solving - CSC 102

Flexibility: The "for" loop is often used when you know the exact

number of iterations or want a concise loop structure. It is

commonly used for iterating over arrays or performing a specific

number of iterations. The "while" loop is more flexible and suitable

when the number of iterations is not known in advance or when the

loop condition is complex and cannot be easily expressed within

the loop declaration.

SAA9.4. The "goto" statement in C is a control transfer statement

that allows you to jump to a specific labelled point in the code. It is

considered a controversial statement and generally discouraged in

modern programming practices due to its potential to create

confusing and hard-to-maintain code. However, there are certain

situations where the "goto" statement can be useful, such as

breaking out of nested loops or handling error conditions.

Here's an example to demonstrate the purpose of the "goto"

statement:

#include <stdio.h>

int main() {

int number;

printf("Enter a positive number: ");

scanf("%d", &number);

if (number <= 0) {

Page 160 of 198


Introduction to Problem Solving - CSC 102

printf("Error: Invalid input.\n");

goto end;

printf("Countdown:\n");

while (number > 0) {

printf("%d\n", number);

number--;

if (number == 5) {

printf("Aborting countdown due to a special condition.\n");

goto end;

printf("Countdown complete.\n");

end:

printf("Program execution has reached the end.\n");

return 0;

In this example, the user is asked to enter a positive number. If the

user enters a non-positive number (<= 0), an error message is

printed, and the program jumps to the "end" label using the "goto"
Page 161 of 198
Introduction to Problem Solving - CSC 102

statement. It bypasses the remaining code in the "if" condition and

the "while" loop, proceeding directly to the end of the program.

The use of the "goto" statement here provides a straightforward

way to handle the error condition and exit the program without

duplicating code or introducing additional control variables.

However, it is important to use the "goto" statement judiciously and

consider alternative approaches, such as using conditional

statements or function calls, whenever possible to improve code

readability and maintainability.

Tutor-Marked Assignment

1. What is a nested loop?

2. Write the syntax of the while statement.

3. Write the syntax of for… loop statement

4. Write the syntax for the do loop control structure.

5. Write short notes on the goto statement?

6. Mention the difference between a while loop and a do... while loop.

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Page 162 of 198


Introduction to Problem Solving - CSC 102

Computational Linguistics Association for Computational Linguistics.

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history.html

Page 163 of 198


Introduction to Problem Solving - CSC 102

Study Session 10: Functions in C

Introduction

An experienced programmer divides any large (lengthy) program

into parts, and then manages those parts to be solved one by one.

This method of programming is intended to organise the typical

work in a systematic manner. This aspect is practically achieved in

the C language through the concept known as ‘Modular

Programming’.

The entire program is divided into a series of modules, and each

module is intended to perform a particular task. The detailed work

to be solved by the module is described in the module (sub

program) only, and the main program only contains a series of

modules that are to be executed. The division of a main program

into a set of modules and assigning various tasks to each module

depends on the programmer’s efficiency.

Where there is a need for us to repeatedly execute one block of

statements in one place of the program, loop statements can be

used. But, a block of statements needs to be repeatedly executed

in many parts of the program, then repeated coding as well as

wastage of the vital computer resource memory will occur. If we

adopt modular programming techniques, these disadvantages

can be eliminated. The modules incorporated in C are called


Page 164 of 198
Introduction to Problem Solving - CSC 102

functions, and each function in the program is meant for doing a

specific task. C functions are easy to use and very efficient.

Learning Outcomes (LOs)

By the end of this session, you should be able to:

10.1. Define a Function

10.2. Stress on Return statement

10.3. Write programs using function call techniques.

10.4. Function prototype

10.5. Differentiate Local and Global variables

10.6. Purpose of recursion and how to use it.

10.1 Definition of Function

A function can be defined as a subprogram that is meant to do a

specific task.

In a C program, a function definition will have a name, a

parentheses pair containing zero or more parameters, and a body.

The parameters used in the parenthesis need to be declared with

type, and if they are not declared, they will be considered of

integer type.

Page 165 of 198


Introduction to Problem Solving - CSC 102

The general form of the function is :

function type name (<arg1,arg2,arg3, ————,argn>)

data type arg1, arg2,;

data type argn;

body of function;

——————————

——————————

——————————

return (<something>);

From the above structure, the main components of function are:

• Return type

• Function name

• Function body

• Return statement

10.1.1 Return Type

Refers to the type of value it would return to the calling portion of

the program. It can have any of the basic data types such as int,

Page 166 of 198


Introduction to Problem Solving - CSC 102

float, char, etc. When a function is not supposed to return any

value, it may be declared as type void

Example

void function name();

int function name();

char function name ();

10.1.2 Function Name

The function name can be any name conforming to the syntax

rules of the variable.

A function name is relevant to the function's operation.

Example

output( );

read

data( )

Page 167 of 198


Introduction to Problem Solving - CSC 102

Formal arguments

The arguments are called formal arguments (or) formal

parameters, because they represent the names of data items

that are transferred into the function from the calling portion of

the program.

Any variable declared in the body of a function is said to be local to

that function, other variables which were not declared either

arguments or in the function body, are considered “global” to the

function and must be defined externally.

Example

int biggest (int a, int b)

————————————

————————————

————————————

return( );

a, b are the formal arguments.

10.1.3 Function Body

The function body is a compound statement that defines the


Page 168 of 198
Introduction to Problem Solving - CSC 102

action to be taken by the function. It should include one or more

“return” statements in order to return a value to the calling

portion of the program.

Example

int biggest(int a, int b)

if ( a > b)

return(a);

body of function.

else

return(b);

Every C program consists of one or more functions. One of these

functions must be called main. Execution of the program will always begin

by carrying out the instructions in main. Additional functions will be

subordinate to the main. If a program contains multiple functions, their

definitions may appear in any order, though they must be independent of

one another. That is, one function definition can’t be embedded within

another.

Generally, a function will process information that is passed to it

from the calling portion of the program and return a single value.

Information is passed to the function via arguments (parameters)

Page 169 of 198


Introduction to Problem Solving - CSC 102

and returned via the “return” statement.

Some functions accept information but do not return anything

(ex: printf()) whereas other functions (ex: scanf()) return

multiple values.

10.1.4 The Return Statement

Every function subprogram in C will have a return statement. This

statement is used in function subprograms to return a value to the

calling program/function. This statement can appear anywhere

within a function body, and we may have more than one return

statement inside a function.

The general format of return statement is:

return;

(or)

return (expression);

If no value is returned from the function to the calling program,

then there is no need for a return statement to be present inside

the function.

10.2 Programs using function Call Techniques

Example 1:

Write a program to find factorial to the given positive integer

,using function technique.


Page 170 of 198
Introduction to Problem Solving - CSC 102

Ans:

# include <stdio.h>

main( )

int n;

printf ( “ Enter any positive number\n”);

scanf( “%d”, &n);

printf( “ The factorial of %d s %d \n”,fact (n));

fact( i) int I;

int j; f = 1 ;

for ( j = I; j>0; j - -) f = f * I;

return ( f ) ;

In the above program, the function with the name ‘fact’ is called by

the main program. The function fact is called with n as a

parameter. The value is returned through variable f to the main

program.

Page 171 of 198


Introduction to Problem Solving - CSC 102

Example 2:

Write a program to find the value of f(x) as f(x) = x 2 + 4, for the

given value of x. Make use of the function technique.

Ans:

# include <stdio.h> main( )

f ( );

f()

{ int x,y ;

printf( “ Enter value of x \n”);

scanf( “ %d”, & x );

y = (x * x + 4);

printf ( “ The value of f (x) id %d \n”, y ) ;

Page 172 of 198


Introduction to Problem Solving - CSC 102

10.3 Differences between Functions and Procedures

Table 10.1: Difference between procedures and functions

Procedure
Function

1. Procedure is 1. Functions is a sub

a sub program program which is

which is intended for specific

included within tasks. Eg. sqrt()

the main

program.

2. Procedure 2. Functions may or

doesn't return may not return a value.

a value.

3. Procedure 3. Function once

cannot be called defined can be called

again and again. any where n number of


times.

4. In functions both
4. Global
local and global
variables
variables can be used.
cannot be used

in procedures.

Page 173 of 198


Introduction to Problem Solving - CSC 102

5. Procedures 5. Functions can be

can be writ- written in modular

ten only in programming such as

procedural C, C++

pro- gramming

such as Dbase,

Foxpro.

10.4 Advantages of Function

1. Easy to write a correct small function

2. Easy to read and debug a function.

3. Easier to maintain or modify such a function

4. Small functions tend to be self documenting and highly readable

5. It can be called any number of times in any place with

different parameters.

Storage class

A variable’s storage class explains where the variable will be

stored, its initial value, and the life of the variable.

Iteration

The block of statements executed repeatedly using loops is called

Iteration.
Page 174 of 198
Introduction to Problem Solving - CSC 102

Categories of Functions

A function, depending on, whether arguments are present or not

and a value is returned or not.

A function may belong to one of the following types.

1. Function with no arguments and no return values.

2. Function with arguments and no return values.

3. Function with arguments and return values

10.5 Advanced Features of Functions

1. Function Prototypes

2.Calling functions by value or by reference

3.Recursion.

10.5.1 Function Prototypes

The user defined functions may be classified as three ways based

on the formal arguments passed and the usage of the return

statement.

1. Functions with no arguments and no return value

2.Functions with arguments no return value

Page 175 of 198


Introduction to Problem Solving - CSC 102

3.Functions with arguments and return value.

Functions with no arguments and no return value

A function is invoked without passing any formal arguments from

the calling portion of a program and the function does not return

any value to the called function. There is no communication

between the calling portion of a program and a called function

block.

Example:

#include <stdio.h>

main()

void message( ); Function declaration

message( ); Function calling

void message( )

printf (“GOVT JUNIOR COLLEGE \n”);

printf (“\t HYDERABAD”);

Page 176 of 198


Introduction to Problem Solving - CSC 102

Function with arguments and no return value

This type of function passes some formal arguments to a function,

but the function does not return any value to the caller. It is any

one way data communication between a calling portion of the

program and the function block.

Example

#include <stdio.h>

main()

void square(int);

printf (“Enter a value for n \n”);

scanf (“%d”,&n);

square(n);

void square (int n)

int value;

value = n * n;

printf (“square of %d is %d “,n,value);

Page 177 of 198


Introduction to Problem Solving - CSC 102

Function with arguments and return value

The third type of function passes some formal arguments to a

function from a calling portion of the program and the computer

value is transferred back to the caller. Data is communicated

between the calling portion and the function block.

Example:

#include <stdio.h>

main()

int square (int);

int value;

printf (“enter a value

for n \n”); scanf(“%d”,

&n);

value = square(n);

printf (“square of %d is %d “,n, value);

int square(int n)

int p;

p = n * n;
Page 178 of 198
Introduction to Problem Solving - CSC 102

return(p);

The keyword "void" can be used as a type specifier when defining

a function that does not return anything or when the function

definition does not include any arguments.

The presence of this keyword is not mandatory, but it is good

programming practice to make use of this feature.

Actual and Formal Parameters (or) Arguments

Function parameters are the means of communication between

the function declaration and the function call. The parameters

may be classified into two groups.

1. Formal Parameters

2. Actual Parameters

1. Formal Parameters

The formal parameters are the parameters given in the

function declaration and function definition. The actual

parameters take the place of the formal parameters when

calling the function.

2. Actual Parameters

Page 179 of 198


Introduction to Problem Solving - CSC 102

The parameters appearing in the function call are referred

to as actual parameters. The actual arguments may be

expressed as constants, single variables, or more complex

expressions. Each actual parameter must be of the same

data type as its corresponding formal parameters.

Example

#include <stdio.h>

// Function declaration with parameters

int sum(int num1, int num2);

int main() {

int a, b, result;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

// Function call with arguments

result = sum(a, b);

printf("The sum of %d and %d is %d\n", a, b, result);

return 0;

// Function definition with parameters

int sum(int num1, int num2) {

int sum = num1 + num2;

return sum;

Page 180 of 198


Introduction to Problem Solving - CSC 102

In this example, we have a function sum that takes two parameters: num1

and num2, both of type int. The sum function calculates the sum of the

two numbers and returns the result.

In the main() function, we declare variables a, b, and result. We prompt

the user to enter two numbers using printf and scanf, and then pass

those numbers as arguments to the sum function when calling it.

Inside the sum function, the received values for num1 and num2 are used

to perform the addition operation, and the result is stored in the sum

variable, which is then returned.

Finally, in the main() function, we print the result obtained from the sum

function using printf.

Function parameters allow us to pass values to functions, and arguments

are the actual values that are passed to the function when calling it.

Local and Global variables:

The variables may be classified as local or global variables.

Local Variable

The variables defined can be accessed only within the

block in which they are declared. These variables are called

“Local” variables

Example

funct (int ,int j)


Page 181 of 198
Introduction to Problem Solving - CSC 102

intk,m;

————;

————;

The integer variables k and m are defined within a function block

of the “funct()”. All the variables to be used within a function

block must be either defined at the beginning of the block or

before using in the statement. Local variables refer only to the

particular part of a block of a function.

Global Variable

Global variables are defined outside the main function block.

Global variables are not contained in a single function. Global

variables that are recognized in two or more functions. Their

scope extends from the point of definition through the remainder

of the program.

10.5.2 Calling functions by value or by reference

The arguments are sent to the functions, and their values are

copied into the corresponding function. This is a sort of

information exchange between the calling function and the called

function. This is known as "parameter passing". It is a mechanism

Page 182 of 198


Introduction to Problem Solving - CSC 102

through which arguments are passed to the called function for the

required processing. There are two methods of parameter

passing.

1. Call by Value

2. Call by reference.

Call by value:

When the values of arguments are passed from a calling function

to a called function, these values are copied into the called

function. If any changes are made to these values in the called

function, there are no changes to the original values within the

calling function.

Example

#include <stdio.h>

main();

int n1,n2,x;

int cal_by_val();

N1 = 6;

N2 = 9;

printf( n1 = %d and n2= %d\n”, n1,n2);

X = cal_by_Val(n1,n2);
Page 183 of 198
Introduction to Problem Solving - CSC 102

Printf( n1 = %d and n2= %d\n”,

n1,n2); Printf(“ x= %d\n”, x);

/ * end of main*/

/*function to illustrate call

by value*/

Cal_by_val(p1,p2)

int p1,p2;

int sum;

Sum = (p1 + p2); P1 + = 2;

P2* = p1;

printf( p1 = %d and p2= %d\n”, p1,p2);

return( sum);

When the program is executed the output will be displayed N1 = 6 and n2

=9

P1 = 8 and p2 = 72

N1 = 6 and n2 = 9

X = 15

There is no change in the values of n1 and n2 before

Page 184 of 198


Introduction to Problem Solving - CSC 102

and after the function is executed.

Call by Reference:

In this method, the actual values are not passed, instead, their

addresses are passed. There is no copying of values since their

memory locations are referenced. If any modification is made to

the values in the called function, then the original values get

changed in the calling function. Passing addresses requires

knowledge of pointers.

Example

This program accepts a one-dimensional array of integers and

sorts them in ascending order. [This program involves passing the

array to the function].

# include <stdio.h>

main();

int num[20], I,max;

void sort_nums();

printf( “ enter the size of the array”\n”);

scanf(“%d”, &max);

for( i=0; i<max;I++)

sort_nums(num,max) /* Function

Page 185 of 198


Introduction to Problem Solving - CSC 102

reference*/

printf(“sorted numbers are as follows\n”);

for(i=0;i<max;I++)

printf(“%3d\n”,num[i]);

/* end of the main*/

/* function to sort list of numbers*/

Void sort_nums(a,n) Int a[],n;

Int I,j,dummy; For(i=0;i<n;i++)

For(j=0; j<n; j++)

If ( a[i] >a[j])

Dummy = a[i];

a[i] = a[j];

a[j] = dummy;

}
Page 186 of 198
Introduction to Problem Solving - CSC 102

10.5.3 Recursion

One of the special features of C is its support for recursion. Very

few computer languages will support this feature.

Recursion can be defined as the process by which a function can

call itself. The function that calls itself again and again, either

directly or indirectly,is known as a recursive function.

The normal function is usually called the main( ) function,

because of its name. But, the recursive function will be called by

itself depending on the condition.

For Example:

main ( )

f1( ) ; ——— Function called by main

——————

——————

——————

f1( ) ; ——— Function definition

——————

Page 187 of 198


Introduction to Problem Solving - CSC 102

——————

——————

f1( ) ; ——— Function called by itself

In the above, the main ( ) function is calling a function named f1( )

by invoking it with its name. But, inside the function definition f1( ),

there is another invocation of the function, and it is the function

f1( ) again.

Examples on Recursion

Example 1 :

Write a program to find the factorial of a given non-negative

integer using a recursive function.

Ans:

#include<stdio.h>

main ( )

int result, n;

printf( “ Enter any non-negative integer\n”);

scanf ( “ %d”, & n);

result = fact(n);

Page 188 of 198


Introduction to Problem Solving - CSC 102

printf ( “ The factorial of %d is %d \n”, n, result);

fact( n )

int n;

int i ; i = 1;

if ( i = = 1)

return ( i);

else

i = i * fact ( n - 1);

return ( i );

Example 2:

Write a ‘C’ program to generate Fibonacci series up to a limit using

recursion.

Ans:

#include<stdio.h>

#include<conio.h>

Page 189 of 198


Introduction to Problem Solving - CSC 102

int Fibonacci (int);

void main ( )

int i, n; clrscr ( );

printf (“Enter no. of Elements to be generated” \n);

scanf (“%d”, &n);

for (i=1; i<n; i++)

printf (“%d”, Fibonacci (i));

getch( );

int Fibonacci (int n)

int fno;

if (n= =1)

return 1;

else

if (n= =2);

return 1;

else

fno=Fibonacci (n-1) + Fibonacci (n-2);

else
Page 190 of 198
Introduction to Problem Solving - CSC 102

return fno;

Conclusion

This session introduced the students to the function definition, return

statement, programs using function call techniques, function prototypes,

and local and global variables. The recursion technique was also

examined in this session.

Summary

In this session, you have learned to:

1. Define a Function

2. Stress on Return statement

3. Write programs using function call techniques.

4. Function prototype

5. Differentiate Local and Global variables

6. Recursion.

Self-Assessment Questions (SAQ)

SAQ10.1. What is the purpose of a function in a C program? (Tests

Page 191 of 198


Introduction to Problem Solving - CSC 102

learning outcome 10.1)

SAQ10.2. Why is a return statement needed in a C program? (Tests

learning outcome 10.2)

SAQ10.3. Write two C programs that have functions. (Tests learning

outcome 10.3)

SAQ10.4. What is recursion in C?, and show an example. (Tests

learning outcome 10.6)

Self-Assessment Answers (SAA)

SAA10.1. The purpose of a function in a C program is:

● Organise code into smaller units for better readability and

maintenance.

● Promote code reusability by allowing functions to be called

multiple times.

● Encapsulate complex operations and hide implementation

details.

● Accept input parameters to customise function behaviour.

● Provide output to the calling code through return values.

SAA10.2. The return statement is needed because:

● Provide a result or computed value from a function back to

the calling code.

● Control the flow of execution within a function.

Page 192 of 198


Introduction to Problem Solving - CSC 102

● Terminate the function's execution and clean up resources.

● Indicate and handle error conditions by returning specific

values.

SAA10.3. Program 1: Finding the Maximum of Two Numbers:

#include <stdio.h>

// Function to find the maximum of two numbers

int findMax(int num1, int num2) {

if (num1 > num2)

return num1;

else

return num2;

int main() {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

// Call the function to find the maximum

int max = findMax(a, b);

printf("The maximum of %d and %d is: %d\n", a, b, max);

Page 193 of 198


Introduction to Problem Solving - CSC 102

return 0;

Program 2: Calculating the Factorial of a Number

#include <stdio.h>

// Function to calculate the factorial of a number

int factorial(int n) {

if (n == 0)

return 1;

else

return n * factorial(n - 1);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

// Call the function to calculate the factorial

int fact = factorial(num);

printf("The factorial of %d is: %d\n", num, fact);

Page 194 of 198


Introduction to Problem Solving - CSC 102

return 0;

In the first program, the findMax function takes two integers as

input and returns the maximum of the two numbers. The main

function prompts the user to enter two numbers, calls the findMax

function, and displays the result.

In the second program, the factorial function recursively calculates

the factorial of a given number. The main function prompts the user

to enter a number, calls the factorial function, and displays the

factorial.

SAA10.4. Recursion in C refers to the process of a function calling

itself directly or indirectly. It allows a function to solve a problem by

breaking it down into smaller, similar subproblems. Each recursive

call works on a smaller instance of the problem until it reaches a

base case, which is a condition that terminates the recursion.

Here's an example of a recursive function in C that calculates the

factorial of a number:

#include <stdio.h>

// Recursive function to calculate the factorial of a number

int factorial(int n) {

// Base case: factorial of 0 is 1

Page 195 of 198


Introduction to Problem Solving - CSC 102

if (n == 0)

return 1;

// Recursive case: multiply n with factorial of (n-1)

else

return n * factorial(n - 1);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

// Call the recursive function to calculate the factorial

int fact = factorial(num);

printf("The factorial of %d is: %d\n", num, fact);

return 0;

In this example, the factorial function calculates the factorial of a

number using recursion. It has a base case where if the input

number n is 0, it returns 1, indicating the termination condition.

Otherwise, it makes a recursive call to factorial(n - 1) and multiplies

Page 196 of 198


Introduction to Problem Solving - CSC 102

it by n. This recursive call continues until it reaches the base case,

and then the results are propagated back through the call stack to

calculate the final factorial.

Tutor-Marked Assignment

1. What is a function? Write its syntax.

2. What is an I/O function? List different types of I/O functions

3. What are the advantages of functions?

4. Write differences between Global and Local variables.

5. List categories of functions

6. What is storage class?

7. What is Iteration

8. What is recursion

References/Further Reading

Iverson, K. E. (1962, May). A programming language. In Proceedings of the

May 1-3, 1962, spring joint computer conference (pp. 345-351).

Shieber, S. (1984). The design of a computer language for linguistic

information. In Proceedings of the Tenth International Conference on

Computational Linguistics. Association for Computational Linguistics.

Page 197 of 198


Introduction to Problem Solving - CSC 102

Bell, Eona, and David Potter, “Computer Applications for People with

Autism,” 2001.

http://www.nas.org.uk/nas/jsp/polopoly.jsp?d=303a=3276.

Pierce, B. C. (2002). Types and programming languages. MIT press.Press

Brain, Marshall, “How computer mice work,” 2004.

http://www.howstuffworks.com/

mouse.htm.

Da Cruz, Frank, “Herman Hollerith,” 2004.

http://www.columbia.edu/acis/history/

hollerith.html.

Dowler, Mike, “Beginners Guides: Legally Copying Software and Music,” PC

Stats,

2003. http://www.pcstats.com/articleview.cfm?articleid=868.

Fernandes, Luis, “A Brief History of the Abacus,” 2003.

http://www.ee.ryerson.ca:8080/

~elf/abacus/history

Page 198 of 198

You might also like