Principles of Programming-2016

Download as pdf or txt
Download as pdf or txt
You are on page 1of 90
At a glance
Powered by AI
The key takeaways are that the document discusses the basics of computer systems including hardware components like the CPU and memory as well as different types of computers.

The main components of a computer system are the input, output, and central processing unit.

The three main components of the CPU are the memory unit, control unit, and arithmetic logic unit.

NDEJJE

UNIVERSITY
FACULTY OF BASIC SCIENCES
AND INFORMATION
TECHNOLOGY
CCO
OUURRSSEEDDEESSCCRRIIPPTTIIO
ONN
The course provides a strong base in the principles and practice of programming. A high level programming
language (e.g. C, C++) is used to explain the principles of programming and provide students with hands on
practical skills.

CCO
OUURRSSEEO
OBBJJEECCTTIIVVEESS
The course aims to provide students with:
1. Knowledge about the various programming languages ;
2. Knowledge and skills in programming concepts ;
3. Knowledge in planning and organization of programming projects ;
4. Techniques of evaluating syntactic and semantic correctness of a computer program.

CCO
OUURRSSEEO
OUUTTLLIIN
NEE
This course covers:
 Introduction to programming languages
 Program structure
 Variables and Operators
 Conditional / Selection Control Flow Structure
 Looping / Iterative / Repetitive Control Flow Structure
 Arrays and Strings
 Functions
CCO
OUURRSSEEAASSSSEESSSSM
MEEN
NTT
Coursework / Continuous Assessment (40% of the Total Weighted Score)
Final Examination (60% of the Total Weighted Score)

BBO
OOOKKSS
 Kenneth Louden, “Programming Languages”
 Kenneth Reek, “Pointers on C”
 Kernighan and Ritchie “The C Programming Language”
W
WEEBBRREESSO
OUURRCCEESS
 www.tutorialspoint.com
 www.programiz.com
 fresh2refresh.com
SSO
OFFTTW
WAARREE
 Bloodshed Dev-C++
 CodeBlocks
 Cfree

- Ndejje University - IT 1107 / CS 1107 Principles of Programming ii


11 INTRODUCTION

1.1 Computer Basics


A computer is an electronic system that can be instructed to input, process, store, and output information.
The credit of invention of the computer goes to the English Mathematician Charles Babbage. For any
machine to be considered as a computer, it has to:
 accept data [Input]
 process data [Processing]
 produce output [Output ]
 store results [Storage]

1.1.1 Types of Computers


Based on application, computers are classified as special purpose computers and general computers. As the
name tells special computers are designed to perform certain specific tasks whereas the other category is
designed to cater the needs of variety of users.
1.1.2 Anatomy of Computers
The main components of a computer are Input unit, Central Processing Unit (CPU) and Output unit. The
information like data, programs etc. are passed to the computer through input devices. The keyboard and
mouse are examples of input devices. The output devices get information from a computer after processing.
Examples include the computer monitors and printers.
1.1.3 The Central Processing Unit (CPU)
The CPU is referred to as the brain of the computer. CPU performs all types of data processing operations.
It stores data, intermediate results and instructions. The CPU also controls the operation of all parts of the
computer.
The CPU itself has three components i.e. Memory unit, Control unit and Arithmetic Logic Unit (ALU). The
Memory unit also called storage unit can store instructions, data and intermediate results. This unit supplies
information to other units of the computer when needed. The CPU’s control unit is for controlling the
execution and interpreting of instructions stored in the memory. The control unit does not perform any
actual data processing operations. ALU is the unit where the arithmetic and logical operations are
performed.
1.1.4 Types of Memory
There are two types memory i.e. RAM (random access memory) and ROM (read only memory). When a
program is called, it is loaded and processed in RAM. When the computer is switched off, whatever is
stored in RAM will be deleted. So it is a temporary memory. ROM is a permanent memory, where data,
programs etc. are stored for future use.
1.1.5 Other Important Computer Facts
Inside a computer there is storage device called Hard disk, where data is stored and can be accessed at any
time. The information to a computer is transformed to groups of binary digits, called bits. The length of a bit
varies from computer to computer, from 8 to 64. A group of 8 bits is called a Byte and a byte generally
represents one alphanumeric (Alphabets and Numerals) character.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming 3


The Physical components of a computer are called computer hardware. But for the machine to work it
requires certain programs. A program can be defined as a set of instructions that tell a computer how to
perform a particular task. Programs are referred to as software.
Software can be divided into two major categories called system software and application software. Systems
software includes operating systems, various device drivers and utilities. Application software is used to
perform real-world tasks and solve specific problems e.g. Microsoft Word is an application program used to
prepare documents like letters
Programs are developed using programming languages. These programs facilitate the users to make their
own programs. The individual or person who writes computer programs using programming languages is
referred to as a Computer Programmer.

1.2 Introduction to Programming


As this course is titled “Principles of Programming”, therefore it is most essential and appropriate to
understand what programming really means.
Computer programming is the art of developing computer programs.
At the basic level, computer programming simply means telling a computer to do something. There are no
other truly fundamental aspects of computer programming. Everything else we talk about will simply be the
details of a particular, usually artificial, mechanism for telling a computer what to do. Sometimes these
mechanisms are chosen because they have been found to be convenient for programmers to use, other times
they have been chosen because they are easy for the computer to understand.
“The first hard thing about programming is to learn, become comfortable with, and accept these
artificial mechanisms, whether they make ‘sense’ to you or not.”
A programming language provides a set of rules to develop a program. These set of rules are referred to as
Syntax. A person who writes a program using a programming language is called a programmer. A
programmer’s job is to convert a solution of a problem (often referred to as an algorithm) into set of
instructions understood by a computer.
An algorithm can be defined as a set of steps taken to solve a problem.
The programmer should also test the program to see whether it is working properly and corrective actions
should be taken if not. Gabe Newell (2013) states that “When you are programming it means that you are
teaching probably the stupidest thing in the entire universe, a computer, how to do something”. This
statement gives us the first reason why computer programming is so important. Without programs, we
would not be able to accomplish any task on our computers.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming 4


Today, we use computers to accomplish countless tasks. These tasks include creating social networking
platforms like Facebook and Twitter, computer games, websites, preparing official documents, etc. We have
solutions for all these tasks because of the existence of Computer Programming.
By designing programs, we learn many skills that are important for all professions. These skills can be
summarized as:
• Analytical thinking
• Critical reading
• Creative synthesis

1.2.1 Skills Required to Program


Programming is an important activity as people’s life and living depends on the programs one makes. Hence
while programming one should:
i. Pay attention to detail
ii. Think about the reusability.
iii. Think about user interface
iv. Understand the fact the computers are stupid
v. Comment the code liberally
i. Paying attention to detail
In programming, the details matter. This is a very important skill. A good programmer always analyzes the
problem statement very carefully and in detail. You should pay attention to all the aspects of the problem.
You can't be vague. You can't describe your program halfway, then say, "You know what I mean?'', and
have the compiler figure out the rest.
Furthermore you should pay attention to the calculations involved in the program, its flow, and most
importantly, the logic of the program. Sometimes, a grammatically correct sentence does not make any
sense.
So it may happen that a program is grammatically correct. It compiles and runs but produces incorrect or
absurd results and does not solve the problem. It is very important to pay attention to the logic of the
program.

ii. Think about the reusability


Whenever you are writing a program, always keep in mind that it could be reused at some other time. Also,
try to write in a way that it can be used to solve some other related problems. A classic example of this is:
Suppose we have to calculate the area of a given circle. We know the area of a circle is (Pi * r 2). Now we
have written a program which calculates the area of a circle with given radius. At some later time we are
given a problem to find out the area of a ring. The area of the ring can be calculated by subtracting the area
of outer circle from the area of the inner circle. Hence we can use the program that calculates the area of a
circle to calculate the area of the ring.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming 5


iii. Think about user interface
As programmers, we assume that computer users know a lot of things, this is a big mistake. So never
assume that the user of your program is computer literate. Always provide an easy to understand and
easy to use interface that is self-explanatory.

iv. Understand the fact that computers are stupid


Computers are incredibly stupid. They do exactly what you tell them to do: no more, no less-- unlike
human beings. Computers can't think by themselves. In this sense, they differ from human beings. For
example, if someone asks you, “What is the time?”, “Time please?” or just, “Time?” you understand
anyway that he is asking for the time but a computer is different. Instructions to the computer should be
explicitly stated. Computer will tell you the time only if you ask it in the way you have programmed it.

When you're programming, it helps to be able to "think'' as stupidly as the computer does, so that you
are in the right frame of mind for specifying everything in minute detail, and not assuming that the right
thing will happen by itself.

v. Comment the code liberally


Always comment the code liberally. The comment statements do not affect the performance of the
program as these are ignored by the compiler and do not take any memory in the computer. Comments
are used to explain the functioning of the programs. It helps the other programmers as well as the creator
of the program to understand the code.

1.2.2 Program Development


Most of these steps are common to any problem-solving task. Program development (software development)
may take several hours, days, weeks, months or years. After development, users can utilize the program.
While in use, the program needs to be maintained. The maintenance (corrective and upgrades) phase will
continue for several months, several years or even several decades.
Therefore software development is not a one-time task; it is a lifecycle where some of the above steps are
reformed again and again.
Developing a program involves a set of steps:
i. Define the problem
ii. Outline the solution
iii. Develop an algorithm
iv. Test the algorithm for correctness
v. Code the algorithm using a suitable programming language
vi. Compile and correction of compile errors
vii. Run the program on the computer
- Ndejje University - IT 1107 / CS 1107 Principles of Programming 6
viii. Test, document and maintain the program
Most of these steps are common to any problem solving task. Program development (software
development) may take several hours, days, weeks, months or years. After development, customers will
make use of the system. While in use the system needs to be maintained. The maintenance phase will
continue for several months, several years or even several decades. Therefore software development is not
a onetime task; it is a lifecycle where some of the above steps are reformed again and again. The steps are
discussed in the following.

i. Define the Problem


First of all the problem should be clearly defined. The problem can be divided into three components:
 Inputs – what do you have?
 Outputs – what do you want to have?
 Processing – how do you go from inputs to outputs?
Programmers should clearly understand “what are the inputs to the program”, “what is expected as
output(s)”and “how to process inputs to generate necessary outputs”. Consider an example where a
computer program is to be written to calculate and display the circumference and area of a circle when the
radius r.
 Inputs – the radius (r)
 Outputs – circumference (c) and area (a)
 Processing C= 2𝜋r, 𝑨 = 𝝅𝒓𝟐

ii. Outline the Solution


Outlining a solution means that the programmer should define:
 the major steps required to solve the problem
 any sub-tasks
 the major variables and data structures
 the major control structures (e.g. sequence, selection, repetition loops) in the algorithm
 the underlined logic
Consider the above mentioned example. In order to calculate the circumference:
 Variables radius(r), circumference(c)
 Calculation c = 2𝜋r
 In order to calculate the area:
 Variables radius(r), area (a)

- Ndejje University - IT 1107 / CS 1107 Principles of Programming 7


 Calculation a = 𝜋r2
iii. Develop the Algorithm for the solution
The next step is to develop an algorithm that will produce the desired result(s).We defined an algorithm as
a set of steps taken to solve a problem. Pseudo code can be used to express an algorithm.
Pseudo code can defined as an outline of a program written in a form that can easily be converted into real
programming statements. A pseudo code can be further defined as an informal high-level description of an
algorithm.
A pseudo code uses the structural conventions of a programming language, but is intended for human
reading rather than machine reading. A suitable pseudo code representing an algorithm for a program that
computes and displays area and circumference of a given circle would be:

 Start
 Declare PI
PI = 3.14
 Input radius r
 Calculate circumference
C = 2 * PI * r
 Calculate area
A = PI* r2
 Output C&A
 End
Please note that 𝜋 𝑖𝑠 𝑟𝑒𝑝𝑙𝑎𝑐𝑒𝑑 𝑏𝑦 𝑃𝐼 in the pseudo code above

Flow charts

For a better understanding of an algorithm, it is represented pictorially. The pictorial representation of an


algorithm is called a Flow Chart. For this certain pictures are used.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming 8


Consider a problem of multiplying two numbers

Algorithm (Pseudo code)


Step1: Input the numbers as a and b
Step2: find the product a x b
Step3: Print the result

Flow chart
In the above example execution is done one after another and straight
forward. But such straight forward problems occur very rarely.
Sometimes we have to depend on decision making at certain stage in a
normal flow of execution. This is done by testing a condition and
appropriate path of flow is selected. For example consider the following
problem

Example Two: To find the highest of three numbers


Algorithm (Pseudo code)
Step 1: read the numbers as x ,y and z
Step 2: compare x and y
Step 3: if x > y then compare x with z and find the greater Step 4: Otherwise compare y with z and find the
greater

- Ndejje University - IT 1107 / CS 1107 Principles of Programming 9


Flow Chart:
The flow chart represents an
algorithm for a program that
computes and displays area and
circumference of a given circle:

iv. Test the Algorithm for Correctness


The programmer must make sure that the algorithm is correct. The objective is to identify major logic
errors early, so that they may be easily corrected and not be passed on into the program code.
Logic errors occur due to incorrect algorithms (although you provide correct inputs you do not get
the correct outputs).
Test data should be applied to each step, to check whether the algorithm actually does what it is
supposed to. An algorithm can be checked by submitting some values for radius (r) and walking
through the algorithm to find out if the resulting output is correct for each input.

v. Code the Algorithm

After testing the algorithm and ensuring that it is 100%


correct, the algorithm should be implemented using a
suitable programming language.
The programming statements can be typed in a text
editing software like Notepad as shown. These
programming statements are referred to as source code.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 10 -


vi. Compile
The next step is to compile the program using a special program known as a compiler. A compiler is a
computer program (or a set of programs) that transforms source code written in a programming
language into another computer language often having a binary form known as object code (a language
a computer understands).While compiling, syntax errors can be identified.
Syntax Errors
Syntax errors occur when the written program does not adhere to the programming language rules.
These errors occur mostly due to miss typed characters, symbols, missing punctuations, etc. If there
are no syntax errors the program gets compiled and it produces an executable program.
An Executable program / file
An executable is a file that contains a program - that is, a particular kind of file that is capable of being
executed or run as a program in the computer. In Windows operating system, an executable file usually
has a file name extension of .exe or .bat. A file whose name ends in ".exe" is really a program that
when opened or double-clicked, it causes the operating system to run the program.

vii. Running the Program


After a program is developed using a programming language, it should be executed by the computer.
Programmers write programs in human readable languages called high-level languages. However, the
computer understands only 0’s and 1’s (referred as the machine language or machine code).
The executable program generated after compiling is then be executed. While the program is running
runtime errors and sometimes logic errors can be identified.
Runtime errors occur while executing the program and those are mostly due to incorrect inputs.
As defined earlier, Logic errors occur due to incorrect algorithms (although you provide correct inputs
you do not get the correct outputs).
Machine language refers to the native/local language of the computer (i.e. language that is understood
by the computer hardware).
Therefore we need to convert the human readable programs into a
machine language before executing. This conversion is achieved
by a special set of programs called compilers or interpreters.
A Translator (Compiler or Interpreter) is a program that
converts the high-level programming language into machine
language that a computer understands.
Compiler vs. Interpreter
A compiler and an Interpreter perform the same task but the major
difference is that a compiler scans the entire program and
translates it as a whole into machine code whereas an interpreter
translates a program one statement at a time.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 11 -


viii. Test the Program
Test the running program using test data to make sure program is producing correct output(s). During
this phase logic errors can be found.

ix. Document and Maintain the Program


All the steps involved in developing the program algorithm and code should also be documented for
future reference. Programmers may maintain and update the program according to new or changing
requirements.

Assessment 1a
1. “Programming is an important activity as society depends on the programs one makes”. Discuss in
detail at least four skills required by a programmer in developing programs that are to be used by
society.
2. Developing computer programs entails a number of steps that a programmer has to undertake
during the process of Program Development. Discuss at least five of those steps.
3. What is the relationship between an Algorithm, a Flowchart and a Pseudo code?
4. Distinguish between syntax errors and runtime errors.
5. Why are logic errors so hard to identify?
6. What is the major difference between a compiler and an interpreter?
7. Outline the pseudo code and flow chart for the solution to the following problems:
i. To find the sum of 4 numbers.
ii. To find the maximum number among 3 numbers.
iii. To find out whether a number is even or odd

1.2.3 Programming Languages


Programming languages were invented to make programming easier. They became popular because
they are much easier to handle than machine language which is made up of 0’s and 1’s. Programming
languages are designed to be both high-level and general purpose.
High-level programming languages let the programmer concentrate on the logic of the problem to be
solved rather than the intricacies of the machine architecture such as is required with low-level
assembly languages.
Assembly Language is a low-level programming language for microprocessors and other
programmable devices. Also known as assembly code, the term is often also used synonymously with
2GL. Programs written in assembly language are converted into machine language by specialized
programs called assemblers.
High level programming languages were invented to make programming easier. They became popular
because they are much easier to handle than machine language. High level Programming languages
are designed to be both high-level and general purpose. A language is considered as high-level if it is
independent of the underlying hardware of a computer. Programming languages are considered general
purpose if they can be applied to a wide range of situations.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 12 -
1.2.3.1 Evolution of Programming Languages
As microprocessors, programming languages also can be grouped into several generations and
currently we are in the fourth generation. In the early days, computers were programmed using
machine language instructions that the hardware understood directly.
Programs written using machine language belong to the first generation of programming languages.
The programs that were written in machine language were hardly human readable, therefore
understanding and modifying them was a difficult task.
Later programs were written in a human readable version of machine code called Assembly language.
Assembly language programs are automatically translated into machine language by a program called
an assembler. Assembly language belongs to the second generation of programming languages. Each
Assembly language instruction directly maps into a machine language instruction (there is a 1-to-1
mapping.
With the introduction of third generation (also referred as 3GL) high-level languages were introduced.
These languages allowed programmers to ignore the details of the hardware. The programs written
using those languages were portable to more than one type of hardware.
Portable refers to running the same program on machines with different hardware architecture.
Languages such as FORTRAN, COBOL, C and Pascal belong to the third generation. All the modern
languages such as Visual Basic, VB Script, Java, C# and MatLab belong to the fourth generation
(4GL).
Programs written in 4GLs are more readable and understandable than the 3GL. They are much closer
to natural languages. Natural languages enable users to access stored data and interact with the
computer using ordinary words. Most of these 4GLs support development of Graphical User Interfaces
(GUIs) and responding to user events such as movement of the mouse, clicking of mouse or pressing a
key on the keyboard. However, programs developed in 4GL generally do not utilize resources
optimally. 4GLs consume large amount of processing power and memory and they are generally
slower than the programs developed using languages belonging to other generations.
Some people think that the next generation of programming languages (fifth generation languages) is
likely to be even closer to natural languages. Fifth generation programming languages (abbreviated as
5GL) are based on the concept of solving problems using constraints given to the program, rather than
using an algorithm written by a programmer.

Assessment 1b
1. C is often referred to as ____________
A. Object Oriented Language C. Assembly Language
B. Machine Language D. High level Language
2. Which generation of languages allows for the use of words and commands?
A. 1st Generation B. 3rd Generation C. 5th generation D. 2nd Generation
3. An assembler is a program that
A. Translates machine code to assembly language
B. Converts high level source code to machine language
C. Converts assembly language to machine code
4. Give three reasons why C is the best choice of programming language.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 13 -


1.2.3.2 Overview of C Programming Language
“C” seems a strange name for a programming language but it is one of the most widely used
languages in the world. C was introduced by Dennis Ritchie in 1972 at Bell Laboratories as a
successor of the language called B (Basic Combined Programming Language –BCPL).
Now, what about the name? The C language is so named because its predecessor was called B. The B
language was developed by Ken Thompson of Bell Labs. You should be able to guess why it was called
B.
Since C was developed along with the UNIX operating system it is strongly associated with UNIX.
UNIX was developed at Bell Laboratories and it was written almost entirely in C.
For many years, C was used mainly in academic environments. However with the release of C
compilers for commercial use and increasing popularity of UNIX, it began to gain wide-spread interest
among computer professionals. Various languages such as C++, Visual C++, and Java and C # have
branched away from C by adding object-orientation and GUI features. Today C compilers are
available for a number of operating systems including all flavors of UNIX, Linux, MS-DOS, Windows
and Apple Mac.
C is a robust language whose rich set of built-in functions and operations can be used to write any
complex program. C is well suited to write both commercial applications and system software since it
incorporates features of high- level languages and Assembly language. Programs written in C are
efficient and fast. Most C programs are fairly portable; that is with little or no modification and
compiling, C programs can be executed on different operating systems.
The syntax and coding style of C is simple and well structured. Due to this reason most of the modern
languages such as C++, Java and C# inherit Coding style. Therefore it is one of the best languages to
learn the art of programming. C is also suitable for many complex engineering applications.

Why Use C?
In today's world of computer programming, there are many high-level languages to choose from, such
as C, Pascal, BASIC, and Java. These are all excellent languages suited for most programming tasks.
Even so, there are several reasons why many computer professionals feel that C is at the top of the list:
1) C is a powerful and flexible language. What you can accomplish with C is limited only by your
imagination. The language itself places no constraints on you. C is used for projects as diverse as
operating systems, word processors, graphics, spreadsheets, and even compilers for other languages.
2) C is a popular language preferred by professional programmers. As a result, a wide variety of
C compilers and helpful accessories are available.
3) C is a portable language. Portable means that a C program written for one computer system (an
IBM PC, for example) can be compiled and run on another system (a DEC VAX system, perhaps)
with little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules
for C compilers.
4) C is a language of few words, containing only a handful of terms, called keywords, which serve as
the base on which the language's functionality is built. You might think that a language with more
keywords (sometimes called reserved words) would be more powerful. This isn't true. As you
program with C, you will find that it can be programmed to do any task.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 14 -
5) C is modular. C code can (and should) be written in routines called functions. These functions can
be reused in other applications or programs. By passing pieces of information to the functions, you
can create useful, reusable code.

As these features show, C is an excellent choice for your first programming language. What about
C++? You might have heard about C++ and the programming technique called object-oriented
programming. Perhaps you're wondering what the differences are between C and C++ and whether
you should be teaching yourself C++ instead of C.
Not to worry! C++ is a superset of C, which means that C++ contains everything C does, plus new
additions for object-oriented programming. If you do go on to learn C++, almost everything you learn
about C will still apply to the C++ superset. In learning C, you are not only learning one of today's
most powerful and popular programming languages, but you are also preparing yourself for object-
oriented programming.
Another language that has gotten lots of attention is Java. Java, like C++, is based on C. If later you
decide to learn Java, you will find that almost everything you learned about C can be applied

1.2.4 Steps in Developing a Program in C


A programmer uses a text editor to create and modify files containing the C source code. A file
containing source code is called a source file (C source file share given the extension .c). After a C
source file has been created, the programmer must invoke the C compiler before the program can be
executed. If the compiler finds no errors in the source code it produces a file containing the machine
code (this file referred as the executable file).
The compilation of a C program is in fact a three stages process; preprocessing, compiling and linking.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 15 -


1) Preprocessing
Preprocessing is performed by a program called the preprocessor. It modifies the source code (in
memory) according to preprocessor directives (example: #define) embedded in the source code. It
also strips comments and unnecessary white spaces from the source code. Preprocessor does not
modify the source code stored on disk; everything is done on the copy loaded into the memory.

2) Compiling the Source Code


Compilation really happens then on the code produced by the preprocessor. The compiler translates
the preprocessor -modified source code into object code (machine code). While doing so it may
encounter syntax errors. If errors are found it will be immediately notified to the programmer and
compiling will discontinue. If the compiler finds any non -standard codes or conditions which are
suspicious but legitimate it will notify to the programmer as warnings and it continues to compile. A
well written program should not have any compilation errors or warnings.

A computer requires digital, or binary, instructions in what is called machine language. Before your C
program can run on a computer, it must be translated from source code to machine language. This
translation, the second step in program development, is performed by a program called a compiler.
The compiler takes your source code file as input and produces a disk file containing the machine
language instructions that correspond to your source code statements. The machine language
instructions created by the compiler are called object code, and the disk file containing them is called
an object file.
After you compile, you have an object file. If you look at a list of the files in the directory or folder in
which you compiled, you should find a file that has the same name as your source file, but with an
.OBJ (rather than a .C) extension. The .OBJ extension is recognized as an object file and is used by the
linker.
On UNIX systems, the compiler creates object files with an extension of .O instead of .OBJ.

3) Linking to Create an Executable File


Linking is the final step and it combines the program object code with other object codes to produce
the executable file. The other object codes come from run-time libraries, other libraries, or object files
that the programmer has created. Finally it saves the executable code as a file on the disk. If any linker
errors are encountered the executable file will not be generated.

One more step is required before you can run your program. Part of the C language is a function
library that contains object code (code that has already been compiled) for predefined functions. A
predefined function contains C code that has already been written and is supplied in a ready-to-use
form with your compiler package.
The printf() function is a library function. These library functions perform frequently needed tasks,
such as displaying information on-screen and reading data from disk files. If your program uses any of
these functions (and hardly a program exists that doesn't use at least one), the object file produced
when your source code was compiled must be combined with object code from the function library to
create the final executable program. (Executable means that the program can be run, or executed, on
your computer.) This process is called linking, and it's performed by a program called (you guessed it)
a linker

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 16 -


2. THE C PROGRAM STRUCTURE
In order to see the structure of a C program, it is best to start with a simple program. The following
code is a C program which displays the message “Hello, World!” on the screen.
/* Program-2.1 – My First Program */
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}

i. Comments
/* Program-2.1 – My First Program */
The first line starting with characters /*and ending with characters */is a comment. Comments are used
by programmers to add remarks and explanations within the program.Comments can be described as
non-executable code used to provide documentation to a programmer.
Comments are ignored by the compiler therefore, they are not executed.Comments are useful in
program maintenance. They provide clarity to the source code allowing others to better understand
what the code was intended to accomplish. This greatly aids the process of debugging the code.
Debugging refers to the process of identifying and resolving errors that prevent correct operation of a
program.
Comments are especially important in large projects containing hundreds or thousands of lines of
source code or projects in which many programmers are working on the same source code. There are
two types of comments:
a) Multiple Line Comment / Block Comment
b) Single Line Comment
a) Multiple Line Comment / Block Comment
A multiple line comment starts with a slash asterisk /* and ends with an asterisk slash */ and
can be anywhere in your program.Multiple line comments can be on one line or can span
several lines within your C program.Adding multiple line comments to your C source code is
highly recommended. They are typically added directly above the related C source code (See
example below).
/* Program-2.1 – My First Program */
#include <stdio.h>
int main()
{

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 17 -


/* multiple line comment can be placed here to explain the next line*/

printf("Hello World!");
return 0;
}
Additionally, a multiple line comment can span several lines as already mentioned. See example
below:
/*
*Purpose: To show a comment that spans multiple lines
*Language: C
*/
b) Single Line Comment
Single Line Comment is used to comment out / explain just a single line of code.Single Line
Comment starts with ‘//’. Any symbols after ‘//’ are ignored by the compiler.Single Line
Comment cannot hide statements written before ‘//’ and on the successive newline.
#include <stdio.h>
int main()
{
printf("Hello!"); // Line comment
return 0;
}

ii. Preprocessor Directive


#include <stdio.h>
Lines that start with a hash (#) symbol are called directives for the preprocessor. A directive is not a
part of the actual program. It is used as a command to the preprocessor to direct the translation of the
program.
This line includes the “standard I/O Library”.A library is simply a package of code that someone else
writes to make your life easier.The “Standard I/O Library” lets you read from the keyboard
(standard in) and also write output to the screen (standard out).

iii. Main Function


int main()declares the main function. The keyword int is added before the function main because it
indicates that main() function returns an integer value. The main() is a special function that is
required in every C program.
In C, the braces mark the beginning and end of a block of code.The block of code makes up the main
function.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 18 -
In this particular case, the block of code contains two lines:
i.e.
 printf (“Hello World”);
 return 0;
The printf statement in C allows us to send output to the standard out which is on the screen.The heart
of this program is the function printf, which actually does the work. The C language is built from
functions like printf that execute different tasks.
Notice the semicolon at the end of these two statements. The semicolon tells the compiler that you
are at the end of a command. You will see that the semicolon is used to end many lines in C.
Because function main() returns an integer value, there must be a statement that indicates what this
value is. The statement “return 0;” does that; in this case it returns zero (conventionally 0 is returned
to indicate the success of a function).

1.3 Displaying Text


The printf is the most important function used to display text on the screen. It has two parentheses
which contain the string to be displayed, enclosed in quotation marks.
/* Program-2.2*/
#include <stdio.h>
int main()
{
printf("Hi there");
printf("How are you?");
return 0;
}
Program-2.2. displays two successive statements using the printf function. Therefore, the output will
be:
Hi thereHow are you?

How does this happen?


The printf function first prints the string “Hi there”. The second time printf function starts printing the
second string from next position on the screen.
Hi thereHow are you?

This output can be modified by adding the new line (\n) character before the start of the second string
or at the end of the first string. See the program below.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 19 -
OR
/* Program-2.3a */ /* Program-2.3b */
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
printf("Hi there\n"); printf("Hi there");
printf("How are you?"); printf("\nHow are you?");
return 0; return 0;
} }

The output for both programs 2.3a and 2.3b above will be:
Hi there
How are you?
The \n is actually treated as a single character that stands for a newline. Therefore, when included in
the programs above, Hi there is printed first on the screen, then How are you? is printed on a newline
when the compiler encounters \n .

printf( format-string[,arguments,...]);
printf() is a function that accepts a series of arguments, each applying to a conversion specifier in the
given format string. It prints the formatted information to the standard output device, usually the
display screen. When using printf(), you need to include the standard input/output header file,
STDIO.H.
The format-string is required; however, arguments are optional. For each argument, there must be a
conversion specifier. The format string can also contain escape sequences. The following are examples
of calls to printf() and their output:
Example 1
#include <stdio.h>
int main()
{
printf( "This is an example of something printed!");
return 0;
}
Example 1 Output
This is an example of something printed!
Example 2
printf( "This prints a character, %c\na number, %d\na floating point, %f",
`z', 123, 456.789 );
Example 2 Output
This prints a character, z
a number, 123
a floating point, 456.789

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 20 -


1.4 Escape Codes in C
Escape codes are special characters that cannot be expressed otherwise in the source code such as new
line, tab and single quotes. All of these characters or symbols are preceded by an inverted (back) slash
(\).Note that each of these escape codes represents one character, although they consist of two
characters.

Escape Code Meaning

\n New Line
\t Horizontal Tab
\” Double Quotes ( “ )
\’ Single Quote ( ‘ )

\\ Backslash
Example 2.1:
Write a C program that prints the following text on the screen:
NDEJJE
UNIVERSITY
KAMPALA “CAMPUS”

/* Program-2.4 */
#include <stdio.h>
int main()
{
printf("NDEJJE \n");
printf("UNIVERSITY \n");
printf("KAMPALA \"CAMPUS\" ");
return 0;
}

Assessment 2a
Write complete C programs to output the following on the screen as it appears
a) “ Eva is a ” b) “MUSOKE IS A”
‘ good ’ student GOOD STUDENT
of “ programming ” OF ‘PROGRAMMING’

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 21 -


1.5 C Tokens
The smallest element identified by the compiler in a source file is called a token. It may be a single
character or a sequence of characters to form a single item. Tokens can be classified as keywords,
literals, identifiers, operators etc. Literals can be further classified as numeric constants, character
constants and string constants.
Language specific tokens used by a programming language are called keywords. Keywords are also
called as reserved words. Reserved words / keywords are defined as a part of the programming
language therefore cannot be used for anything else. Any user defined literals or identifiers should not
conflict with keywords or compiler directives.

1.5.1 Literals
Literals are values that appear directly in a program. Numeric constants are an uninterrupted sequence
of digits (possibly containing a period). Examples of numerical values are 123, 10000 and 99.78
int age = 23; // 23 is a numeric literal
Character constants represents a single character and it is surrounded by single quotation mark ( ‘).
Characters such as ‘a’, ‘A’, ‘$’ and ‘4’ are examples of Character Constants.
char letter = ‘A’; // A is a character constant

1.5.2 Identifiers
Identifiers are referred to as names given to variables. There are four major rules that must be
considered when coming up with identifiers (variable names):
i. An identifier must begin with a letter and the rest can be letters, digits or underscores. An
identifier must not start with a number / digit. e.g. 2Age and 23sum cannot be used as
identifiers.
ii. Identifiers are case sensitive, therefore the identifier abc is different from ABC or Abc.
iii. C reserved / key words such as int, float, double, void, main, include etc. cannot be used as
identifiers. Programmers cannot use any of the keywords as variable names.
iv. Identifiers should never have spaces between them e.g. an identifier cannot be “age of
student” but can be “age_of_student”.
Sometimes a C compiler may consider only the first 32 characters in an identifier. While defining
identifiers programmers should follow some of the naming standards for better readability of the
program. One such standard is the use of underscores symbol (_) to combine two words (example:
sub_total).
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 22 -
1.5.3 Data Types
A data type in a programming language is a set of data with values having predefined characteristics
such as integers and characters.
The language usually specifies the range of values for a given data type, how the values are processed
by the computer and how they are stored. Storage representations and machine instructions to handle
data types differ from machine to machine.
The variety of data types available allows the programmer to select the type appropriate to the needs of
the application as well as the machine. C supports a number of data types. If they are not enough,
programmers can define their own data types.
C supports three classes of data types:
 Primitive (or basic) data types –these are the fundamental data types supported by the
language. These can be classified as integer types, floating point types and character types.
 User defined data types – based on the fundamental data types users can define their own data
types. These include type defined data types (using typedef keyword) and enumerated types
(using enum keyword).
 Derived data types – programmers can derive data types such as arrays, structures, unions and
pointers by combining several data types together.
1.5.3.1 Primitive Data Types
The C language supports five primitive data types; namely integers (int) floating point numbers
(float), double precision floating point numbers (double), characters (char) and void (void). Many of
these data types can be further extended as long int and long double. Each of these data types requires
different storage capacities and has different range of values (depending on the hardware) as shown in
Table 2.2 below.

Table 2.3 – Basic C data types (on a 32-bit machine)


Data Type Size of Range of Values
Bits
Char 8 -128 to +127
Int 32 -2147483648 to 2147483647
Float 32 3.4e-38 to 3.4e+38 (accuracy up to 7 digits)
Double 64 1.7e-308 to 1.7e+308 (accuracy up to 15 digits)
Void 0 Without value (null)

Table 2.4 –Basic C data types and modifiers (on a 32-bit machine)

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 23 -


1.5.3.2 Modifiers
The basic data types can be modified by adding special keywords called data type modifiers to produce
new features or new types. The modifiers are signed, unsigned, long and short. For example short
int represents fairly small integer values and require half the amount of storage as regular int numbers.
Except with void type, the modifiers can be used with all the basic data types as shown in Table 2.4

1.5.4 Variables
A variable is a value that can change. A variable is described as a reserved memory location that can
hold a value of a certain data type.
Programmers refer to a variable by its name (identifier) so that it can be accessed during the course of
the program. Programmers cannot use any of the keywords as variable names as stated in the rules that
govern the formulation of identifiers.
int age = 23; // age is a variable
1.5.4.1 Declaring Variables
In order to use a variable in C, the programmer must first declare it specifying the data type. The most
important restriction on using a variable in C is that they have to be declared at the beginning of the
program.
Declaring a variable refers to reserving named space in memory where data of a specified data type
is stored.
The syntax to declare a new variable is to first write the data type then followed by a valid variable
identifier as given in the following examples:
inta;
float total;
unsignedint number_of_students;
chargender;
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 24 -
Above set of expressions declared:
 variables “a” as an integer,
 “ total” as a floating point number,
 “number_of_students” as integer (since there are no negative number of students) and
 “gender” as a character (a person can either be Male ‘M’ or Female ‘F’).
Multiple variables belonging to the same data type can be defined as separate set of expressions or by
listing variable names one after the other (should be separated by a coma sign ( ,)).Consider the
following examples:
int a;
int b;
float total;
floatsub_total;
above variables can also be defined as:
int a, b;
float total, sub_total;
1.5.4.2 Initializing a Variable
After declaring a variable it may be initialized with a suitable value. In C, an uninitialized variable can
contain any garbage value therefore it is good practice that the programmer ensures that all the
variables are initialized before using them in any of the expressions.
int a; //variable a is declared as an integer
a = 10; //variable a is initialized with value 10
Initializing a variable can be done while declaring it, just after declaring it or later within the code
(before accessing/evaluating its value within an expression).
int age = 10;
1.5.4.3 Constants
The value of a constant cannot be changed after an initial value is assigned to it.The C language
supports two types of constants; namely declared constants and defined constants. Declared
constants are more common and they are defined using the keyword const. With the const prefix the
programmer can declare constants with a specific data type exactly as it is done with variables
const float pi = 3.141;
Programmers can define their own names for constants which are used quite often in a program.
Without having to refer to a variable such a constant can be defined simply by using the #define pre-
processor directive. These are called defined constants. Following expression illustrates the use of the
#define pre-processor directive.
#define pi 3.141

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 25 -


How a #define Works
The precise action of the #define directive is to instruct the compiler as follows: "In the source code,
replace CONSTNAMEwith literal." The effect is exactly the same as if you had used your editor to go
through the source code and make the changes manually. Note that #define doesn't replace instances of
its target that occur as parts of longer names, within double quotes, or as part of a program comment.
For example, in the following code, the instances of PI in the second and third lines would not get
changed:
#define PI 3.14159
/* You have defined a constant for PI. */
#define PIPETTE 100

Defining Constants with the const Keyword


The second way to define a symbolic constant is with the const keyword. const is a modifier that can
be applied to any variable declaration. A variable declared to be const can't be modified during
program execution--only initialized at the time of declaration. Here are some examples:
const int count = 100;
const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;

const affects all variables on the declaration line. In the last line, debt and tax_rate are symbolic
constants. If your program tries to modify a const variable, the compiler generates an error message, as
shown here:
const int count = 100;
count = 200; /* Does not compile! Cannot reassign or alter */
/* the value of a constant. */

A program that demonstrates the use of variables and constants.


1: /* Demonstrates variables and constants */
2: #include <stdio.h>
3:
4: /* Define a constant to convert from pounds to grams */
5: #define GRAMS_PER_POUND 454
6:
7: /* Define a constant for the start of the next century */
8: const int NEXT_CENTURY = 2000;
9:
10: /* Declare the needed variables */
11: long weight_in_grams, weight_in_pounds;
12 int year_of_birth, age_in_2000;
13:
14: main()
15: {
16: /* Input data from user */
17:
18: printf("Enter your weight in pounds: ");
19: scanf("%d", &weight_in_pounds);
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 26 -
20: printf("Enter your year of birth: ");
21: scanf("%d", &year_of_birth);
22:
23: /* Perform conversions */
24:
25: weight_in_grams = weight_in_pounds * GRAMS_PER_POUND;
26: age_in_2000 = NEXT_CENTURY - year_of_birth;
27:
28: /* Display results on the screen */
29:
30: printf("\nYour weight in grams = %ld", weight_in_grams);
31: printf("\nIn 2000 you will be %d years old\n", age_in_2000);
32:
33: return 0;
34: }
Enter your weight in pounds: 175
Enter your year of birth: 1960
Your weight in grams = 79450
In 2000 you will be 40 years old
ANALYSIS: This program declares the two types of symbolic constants in lines 5 and 8. In line 5, a
constant is used to make the value 454 more understandable. Because it uses GRAMS_PER_POUND,
line 25 is easy to understand. Lines 11 and 12 declare the variables used in the program. Notice the
use of descriptive names such as weight_in_grams. You can tell what this variable is used for. Lines 18
and 20 print prompts on-screen. The printf() function is covered in greater detail later. To allow the
user to respond to the prompts, lines 19 and 21 use another library function, scanf(), which is covered
later. scanf() gets information from the screen. For now, accept that this works as shown in the listing.
Later, you will learn exactly how it works. Lines 25 and 26 calculate the user's weight in grams and
his or her age in the year 2000. These statements and others are covered in detail in the next chapter.
To finish the program, lines 30 and 31 display the results for the user.

1.5.5 The printf Conversion Specifiers


When displaying numbers special care must be given to the data type. Each data type has to be used
with printf function in a specific format. In order to display the correct values using the printf function
conversion specifiers should be used. They are used to instruct the compiler about the type of
numbers appearing in the program, which in turn determines the suitable memory storage locations.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 27 -


The conversion specifiers are also referred as format characters or format specifiers. Table 2.5 above
summarizes conversion specifies supported by the printf function. Consider the example given:
/* Program-2.5 */
#include<stdio.h>
int main()
{
int a = 20;
float b = 20.0;
printf("%d\n",a);
printf("%f\n",b);
return 0;
}

The first number is of the type integer while the second number is of the type float. Conversion
specifier %d stands for decimal (whole number) while %f stands for float. Incorrect use of format
characters would result in wrong outputs.

Assessment 2b:
1. With examples, explain the meaning of the following terms as applied in Computer
Programming:
i) Variable ii) Data type iii) Literal iv) identifier
2. Write down a C program where you declare and initialize variables for your age and height,
and then output those values on the screen. Height should be declared as a floating point value.
3. With examples, distinguish between Declaring a variable andInitializing a variable.

Consider Program-2.7 which makes use of variables.


/* Program-2.7*/
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 28 -
#include <stdio.h>
int main()
{
int a = 3;
float b = 10.0;
float c;
c = b/a;
printf("A is %d\n", a); //decimal value
printf("B is %f\n",b); //decimal value
printf("Answer is %f\n",c); //floating point value
return 0;
}
In this program variables a andb are initialized with values 3 and 10.0 and the answer (b/a) is stored in
variable “c”.
In Program-2.7 you may wish to see the answer appearing in a more manageable form like 3.3 or 3.33
rather than 3.333333. This can be achieved by using modifiers along with the format characters in
order to specify the required field width.
Program-2.8 shows how digits to the right of the decimal point can be suppressed.
/* Program-2.8*/
#include <stdio.h>
int main()
{
int a = 3;
float b = 10.0;
float c;
c = b/a;
printf("A is %d\n", a); //decimal value
printf("B is %d\n",b); //decimal value
printf("Answer is %.2f \n",c); //float value
return 0;
}

The format %.0f will suppress all the digits to the right of the decimal point, while the format %.2f
will display first two digits after that decimal point.

Assessment 2c
1. Write a program to assign the number 34.5678 to a variable named “number” then display the
number rounded to the nearest integer value and next the number rounded to two decimal
places.
2. Write a program where you declare two float variables and initialize them with 4.32 and 3.4
respectively. Calculate their product and display the result correct to one decimal place.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 29 -


1.5.6 ASCII (American Standard Code for Information Interchange)
ASCII (pronouncedask-ee), is a code for representing English characters as numbers, with each letter
assigned a number from 0 to 127. For example, the ASCII code for uppercase M is 77 and the ASCII
code for lowercase t is 116.
For a list of commonly used characters and their ASCII equivalents, refer to the ASCII table on the
next page. Most computers use ASCII codes to represent text, which makes it possible to transfer data
from one computer to another.
Table 2.6 –ASCII Table

1.5.6.1 Displaying Character Variables


Program-2.9 illustrates the use of character variables.
/* Program-2.9*/
#include <stdio.h>
int main()
{
charfirst_letter;
first_letter = ‘A’;
printf("Character: %c\n", first_letter); //display character
printf("ASCII value: %d\n", first_letter); //display ASCII
return 0;
}

Executing Prog-2.9 will display the following:


Character: A
ASCII value: 65

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 30 -


1.5.7 Formatted Input
We have already used printf function to display formatted output. The scanfis a similar function that
is used to read data into a program. The scanf function accepts formatted input from the keyboard.
In Program-2.10, three integer variables are declared (a, b and sum). Values of a and b are to be read
from the keyboard using the scanf function, while the value of the variable sum is calculated as the
summation of a and b.
/* Program-2.10 */
#include <stdio.h>
int main()
{
int a, b, sum;
printf(“Enter the first number: ”);
scanf("%d", &a); //read 1st number
printf(“Enter the second number: ”);
scanf("%d", &b); // read 2nd number
sum = a + b; // calculates sum of a and b
printf("a+b =%d\n", sum); //display answer
return 0;
}
The scanf function uses the same set of formatting characters as the printf function to describe the
type of expected input i.e. %f for floats and %d for whole numbers.Program-2.10 shows the use of
%d for integer values and Program-2.11 shows the use of %f for floats.
Note that the scanf function uses the variables a andb as “&a” and “&b”. The symbol “&”is called
the address of operator.The string “&a” represents the memory address containing variable a and is
called a pointer. Pointers will be covered later in this course.The scanf function also supports mixed
types of input data .Consider the following line of code:
scanf("%d%f", &a,&b);
The scanf function accepts variable “a” as an integer and “b” as a floating point number. In certain
cases you may want to separate your inputs using a comma (,) rather than using the Enter key or a
blank space. In such cases you must include the comma between format characters as:
scanf("%f,%f", &a,&b);
For such a program your inputs should be in the form:
2,3
One insufficiency of the scanf function is that it cannot display strings while waiting for user input.
This will require use of an additional function like the printf in order to display a message as a prompt
for the user reminding the required data item. (See Program-2.10 and Program-2.11 above).
In Program-2.10, the user has to be first prompted for input by the statement
printf(“Enter the first number: ”);
Assessment 2d
a) Outline a pseudo code for a program that accepts three float values, adds them and computes
their average. The sum and average should be then be displayed.
b) Draw a flowchart diagram to represent the pseudo code you have outlined above.
c) Transform the pseudo code you have written in (e) above into a complete C program that can
be used to compute and display the sum and average of any three float values entered from the
keyboard.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 31 -


2 STATEMENTS, EXPRESSIONS, AND OPERATORS IN C

2.1 Statements
A statement is a complete direction instructing the computer to carry out some task. In C, statements
are usually written one per line, although some statements span multiple lines. C statements always
end with a semicolon (except for preprocessor directives such as #define and #include). You've already
been introduced to some of C's statement types. For example:
x = 2 + 3;
is an assignment statement. It instructs the computer to add 2 and 3 and to assign the result to the
variable x. Other types of statements will be introduced.

2.2 Null Statements


If you place a semicolon by itself on a line, you create a null statement--a statement that doesn't
perform any action. This is perfectly legal in C. As you advance in programming, you will learn how
the null statement can be useful.

2.3 Compound Statements


A compound statement, also called a block, is a group of two or more C statements enclosed in braces.
Here's an example of a block:
{
printf("Hello, ");
printf("world!");
}
In C, a block can be used anywhere a single statement can be used. Note that the enclosing braces can
be positioned in different ways. The following is equivalent to the preceding example:
{printf("Hello, ");
printf("world!");}
It's a good idea to place braces on their own lines, making the beginning and end of blocks clearly
visible. Placing braces on their own lines also makes it easier to see whether you've left one out.

2.4 Expressions
In C, an expression is anything that evaluates to a numeric value. C expressions come in all levels of
complexity.

a) Simple Expressions
The simplest C expression consists of a single item: a simple variable, literal constant or
symbolic constant. Here are four expressions:
Expression Description
PI A symbolic constant (defined in the program)
20 A literal constant
rate A variable
A literal constant evaluates to its own value. A symbolic constant evaluates to the value it was
given when you created it using the #define directive. A variable evaluates to the current value
assigned to it by the program.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 32 -


b) Complex Expressions
Complex expressions consist of simpler expressions connected by operators. For example:
2+8
is an expression consisting of the sub expressions 2 and 8 and the addition operator +. The expression
2 + 8 evaluates, as you know, to 10. You can also write C expressions of great complexity:
1.25 / 8 + 5 * rate + rate * rate / cost
When an expression contains multiple operators, the evaluation of the expression depends on operator
precedence. This concept is covered later in this chapter, as are details about all of C's operators.
C expressions get even more interesting. Look at the following assignment statement:
x = a + 10;
This statement evaluates the expression a + 10 and assigns the result to x. In addition, the entire
statement x = a+ 10 is itself an expression that evaluates to the value of the variable on the left side of
the equal sign.
Thus, you can write statements such as the following, which assigns the value of the expression a + 10
to both variables, x and y:
y = x = a + 10;
2.5 Operators in C
Expressions can be built up from literals, variables and operators. An operator is a symbol that tells
the compiler to perform specific mathematical or logical functions.
Operators perform actions on operands. An operand is the object of a mathematical or logical
operation, a quantity on which an operation is performed.
For example, in the expression
5 + x
xand 5 are operands and + is an operator. All expressions have at least one operand. Examples of
operators include +, - , / , += , = , == and so many more. C language is rich in built-in operators and
provides the following types of operators:

3.2Assignment Operator
The assignment operator is the simple equal sign (=). The assignment operator is used to assign a
value to a variable or variable to a variable. The format of an assignment statement is:
variable_name = expression;
e.g. int a = 2; // value 2 is assigned to variable a
int a = 7+4; // expression 7 plus 4 is assigned to variable a
The assignment operator always assigns the expression (the value on the right) to the variable name
(on the left).Consider the following set of examples:
• a = 5;//5 is assigned to variable a. Value of variable a becomes 5
• a = 5+10;//15 is assigned to variable a. Value of variable a becomes 15
• a = 5 + b;//value of 5 plus value of b is assigned to variable a

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 33 -


Variable to a variable example:
variable_name = variable_name;
e.g. int a = b;// variable b is assigned to variable a
int a = b+c;//expression b plus c is assigned to variable a
The expression can be a numeric value or a literal, or it may contain mathematical expressions.

3.3Arithmetic Operators
C supports five major arithmetic operators and two extended operators (See Table 3.1).

Program-3.1 illustrates the usage of major arithmetic operators.


/* Program-3.1*/
#include <stdio.h>
int main()
{
inta,b;
printf("Enter a: ");
scanf("%d", &a); //read value of a
printf("Enter b: ");
scanf("%d", &b); //reads value of b
printf("\na+b = %d", a+b); //display sum of a and b
printf("\na-b = %d", a-b); //display subtraction of b from a
printf("\na*b = %d", a*b); //display multiplication of a and b
printf("\na/b = %d", a/b); //display division of a by b
printf("\na%b = %d", a%b); //display modulus of a divided by b
return 0;
}
Sample Run:
Enter a: 8
Enter b: 4
a+b = 12
a-b = 4
a*b = 32
a/b = 2
a%b = 0

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 34 -


3.3.1 Increment (++) and Decrement (--) Operators
The auto increment (++) and auto decrement (--) provide a convenient way of, respectively, adding or
subtracting 1 from a numeric values. These are summarized in Table 3.2 . The Examples assume the
following variable definition:
int k = 5;
Table 3.2 illustrates the Increment and Decrement Operators
Operator Name Example
Auto Increment (prefix) ++k + 10 // gives 16
++
Auto Increment (postfix) K++ + 10 // gives 15
++
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) K-- + 10 // gives 15

Both operators can be used in prefix and postfix form. The difference is significant though.When used
in prefix form, the operator is first applied and the outcome is then used in the expression.
int k = 5;
++
k + 10;

/*prefix increment operator is first applied to variable k hence incrementing it by 1


*giving 6 as a result which is then used to evaluate the expression k+10
* Expression becomes (6+10) making the final result 16 as shown in Table 3.2*/
When used in the postfix form, the expression is evaluated first and then the operator is applied.
int k = 5;

k++ + 10;

/*when a postfix increment operator is used, the expression k+10


*is first evaluated with expression becoming (5+10) making
*the result 15 as shown in Table 3.2, then the operator is applied
*to make k=6 */
Both increment and decrement operators can be used as a prefix or as a postfix. The operator can be
written before the identifier as a prefix (--a) or after the identifier as a postfix (a--). In simple
operations such as a-- or --a both have exactly the same meaning. However in some cases there is a
difference.
Consider the following set of statements:
int a, x;
a = 21;
x = --a; //line 3

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 35 -


After executing above segment of code, a will be 20 and x will be 20.In line 3, first the variable a is
decremented by 1 before assigning it to variable x.
Consider the following segment of code.
int a, x;
a = 21;
x = a--; // line 2
After executing above code segment a will be 20 and x will be 21.In the second approach in line 3
first a is assigned to x and then a is decremented by 1 to make it 20.

3.4 Compound Assignment Operators


In C lots of shortcuts are possible. For example, instead of the statement,
a = a + b;
The programmer may use the shorthand format:
a += b;
Such operators are called compound assignment operators. The assignment operator can be
combined with the major arithmetic operations such as;+, -, *, / and %. Therefore many similar
assignments can be used such as:
a -= b; // is same as a = a-b;
a *= b; // is same as a = a*b;
a /= b; // is same as a = a/b;
a %= b; // is same as a = a%b;
More Examples include:
a -= 5; // is same as a = a-5;
a *= 9; // is same as a = a*9;
a /= 50; // is same as a = a/50;
a %= 32; // is same as a = a%32;
Similarly, the following expressions can be used to increment a variable:
a++;
you may use:
a +=1; or a = a + 1;
Also expression:
a--;
can be written as:
a -= 1; or a = a - 1;

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 36 -


Precedence and Associativity of Operators
Precedence defines the priority of an operator i.e. which operator is considered first in an
expression. If more than one operator is involved in an expression then, C language has predefined rule
of priority of operators. This rule of priority of operators is called operator precedence.
Associativity of an operator is a property that determines how operators of the same precedence are
grouped in the absence of parentheses. Associativity indicates in what order operators of equal
precedence in an expression are applied or handled.

Table 3.3 illustrates the precedence & Associativity of operators

Table 3.3 illustrates the precedence of arithmetic operators and their associativity. In the same
expression, if two operators of the same precedence are found, they are evaluated from left to right,
except for increment and decrement operators which are evaluated from right to left.
Parentheses can also be used to change the order of evaluation and it has the highest precedence.
For Example, givenint a=2,b=24,c=4. Calculate the value of p in the expression below:
int p= ++c + a * b / 3;
In the expression above, the ++ operators are handled first according to Table 3.3. Parentheses can be
used during the evaluation.
int p= (++c) + a * b / 3;
p = 5 + a * b / 3;
Then * and / are handled next. Since * and / have the same precedence, their associativity of left to
right is applied meaning that * is handled first and then /.
p = 5 + (a * b) / 3;
p = 5 + (2 * 24) / 3;
p = 5 + (48 / 3);
p = 5 + 16;
Therefore, the value of p will be 21

Assessment 3a
1. Give the values of variables “a”, “b”, “sum1” and “sum2” if the following code segment is
executed.
int a, b,sum1,sum2;
a = 2, b = 7;
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 37 -
sum1 = a + (++b);
sum2 = a + (b++);
2. Outline the rules that you have to consider when coming up with variable names (identifiers).
3. Distinguish between operator precedence and operator associativity.
4. Write expressions that are equivalent to the following
i) x--; ii) x %= 2; iii) x/=8;
5. Calculate the values of p and q in the code fragment below:
int a=10, b=20, c=40;
int p, q;
p= c + a * b / 2;
q= c / 2 / a * 2;

3.5 Relational and Logical Operators


The relational operatorsare used to compare values forming relational expressions. The logical
operatorsare used to connect relational expressions together using the rules of formal logic.
Both types of expressions produce TRUE or FALSE results. In C, FALSE is the zero while any
nonzero number is TRUE. However, the logical and relational expressions produce the value “1” for
TRUE and the value “0” for FALSE.
Table 3.4 illustrates relational and logical operators
Operator Name Example

Relational Operators
== Equality 5 == 5 // gives 1

!= Inequality 5 != 5 //gives 0

< Less than 5 < 5.5 //gives 1


<= Less than or Equal 5 <= 5 //gives 1

> Greater than 5 > 5.5 // gives 0

>= Greater than or Equal 6.3 >= 5 // gives 1

Logical Operators
! Logical NOT !(5 == 5) // gives 0
&& Logical AND 5 < 6 && 6<7 //gives 1
|| Logical OR 5 < 6 || 6 < 5 // gives 1

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 38 -


Precedence of Relational and Logical Operators
As arithmetic operators, relational and logical operators also have precedence. Table 3.5 summarizes
the relative precedence of the relational and logical operators. These relational operators are lower in
precedence than arithmetic operators.

Table 3.4 illustrates precedence and associativity of Operators

For an example consider the following expression:


10 > 8+1
is equivalent to the expression:
10 > (8+1)
In order to understand how logical expressions are evaluated consider the following expression:
a==b && c > d
This expression says that ; “ (a is equivalent to b) AND (c is greater than d) ”. In other words this
expression is evaluated as TRUE if both the conditions are met.
Suppose a = 24, b = 24, c = 50 and d = 30
Then a == b is TRUE and c > d is also TRUE. Therefore, the expression (a==b) && (c > d) will be
evaluated as TRUE. For expressions involving Logical AND, both conditions are have to be evaluated
as TRUE for the expression to return TRUE.
If AND (&&) is replaced by logical OR ( || ) operator, then only one condition needs to be
TRUE.Example: Suppose a = 24, b = 90, c = 50 and d = 30. Then given expression (a==b) || (c > d)
a == b is FALSE and c > d is TRUE.
Therefore, expression (a==b) || (c > d) will return TRUE becauseonly one condition needs to be
TRUE.
Consider another expression, supposeint a = 5, b = 5;
!(a==b)
In this case, since both “a” and “b” have similar value 5, the logical value of the expression within the
parenthesis is TRUE. However the NOT operation will negate the result which is TRUE. Therefore
the final result will be FALSE.
In order to see the effect of precedence consider the following expression:
a==b && x==y || m==n

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 39 -


Since equal operator (==) has a higher precedence than the logical operators the equality will be
checked first.
Then the logical AND operation will be performed and finally logical OR operation will be
performed. Therefore this statement can be rewritten as:
((a==b) && (x==y))|| (m==n)
Suppose int a = 24, b = 9, m = 65, n = 65, x = 44, y = 51;
Evaluating the expression :
((a==b) && (x==y))|| (m==n)
((24==9)&&(44==51)) || (65==65)
((FALSE) &&(FALSE))|| TRUE
FALSE || TRUE
TRUE
Therefore, the expression is evaluated as TRUE

Summary: Precedence of Arithmetic, Relational and Logical Operators


In C, precedence of arithmetic operators( * , % , / , + , - ) is higher than relational operators( == , != , >
, < , >= , <=) and precedence of relational operator is higher than logical operators( && , || and ! ).

3.6Bitwise Operators
Using C you can access and manipulate bits in variables, allowing you to perform low level operations.
C supports six bitwise operators and they are listed in Table 3.5 below.
Table 3.4 illustrates precedence and associativity of Operators(See Table on the next page)

Bitwise AND, OR and XOR operators perform logical AND, OR and XOR operations at the bit
level.Consider following set of expressions:
inta,b,c;
a = 12;
b = 8;
c = a & b;

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 40 -


The bitwise AND operation will be performed at the bit level as follows:
a = 12 00001100
b=8 00001000 &
00001000
For Bitwise AND (&) operator, False (0) and False(0) gives FALSE, True (1) and False (0) gives
FALSE(0) and True (1) and True(1) gives TRUE(1).
Then the variable “c” will hold the result of bitwise AND operation between “a” and “b” which is
000010002 (810).
Example:Write a C program to convert a given character from uppercase to lowercase and vice versa.
Solution:
ASCII values of the uppercase and lowercase characters have a difference of 32.For example, in
ASCII, “A” is represented by 6510 while “a” is represented by 9710 . Therefore (97-65 = 32).
At the bit level, only difference between the two characters is the 5th bit.
65 = 010000012
97 = 011000012
32 = 001000002
Therefore by inverting the 5th bit of a character it can be changed from uppercase to lowercase and vice
versa. Bitwise XOR operation can be used to invert bits.
/* Program-3.2*/
#include <stdio.h>
int main()
{
char input;
printf("Character to convert: ");
scanf("%c",&input); //read character
printf("Converted character: %c", input ^ 32); //input XOR 32
return 0;
}

3.7Shift Operators
Shift operators allow shifting of bits either to left or right. We know that 8 is represented in binary as:
8 =00001000
and when it is shifted by one bit to right, we get:
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 41 -
8 =00001000 00000100 = 4
In general the right shift operator is used in the form:
variable>> number-of-bits
and left shift is given in the form:
variable>> number-of-bits
In the following expression the value in the variable “a” is shift by 2 bits to right:
a>> 2

Assessment 3b
For each of the following expressions, write the value returned. Assume the following initializations
have been made. All problems are valid code and will compile. For boolean values, write either true or
false.
int w = 1; int x = 2; int k=4; double y = 1.0; double z = 2.0;
Expression Value
i. x / w ______
ii. k + x * w / x ______
iii. k / y / z / y / w ______
iv. (k / w) / (x / z) ______

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 42 -


33 CONTROL FLOW STRUCTURES
3.1 Introduction
The order in which statements are executed in a program is called a control flow. Control structures
form the basic entities of a structured programming language. C, C++ or Java are all structured
programming languages. Control structures are used to alter the flow of execution of the program.
So, why do we need to alter the program flow?
The reason why we alter program flow is predominantly to aid “decision making“. In life, we may be
given with a set of options like doing “Electronics” or “Computer science”. We do make a decision by
analyzing certain conditions (like our personal interest, scope of job opportunities etc.). With the
decision we make, we alter the flow of our life’s direction. This is exactly what happens in a C
program.
Control structures combine instructions into logical units. A Logical unit has one entry point and one
exit point.Control flow is a term routinely used in control structures. Control flow refers to the order in
which programming statements in a program are executed.
There are three types of control structures available in C
 Sequence Control Structures
 Conditional / Selection Control Structures
 Repetition Control Structures

3.2 Sequence Control Structures


Statements are executed in a top down order. No statement is skipped and no statement is executed
more than once.
For Example:
#include<stdio.h>
intmain()
{
int a;
int a=5;
printf(“Square of a = %d”, a);
return 0;
}

3.3 Conditional Control Structures


Conditional or selection structure opts for a statement to execute on the basis of a condition. The
statement is executed when the condition is TRUE and ignored when it is FALSEe.gif, if-else,
switch structures.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 43 -
Figure 4.1 Flowchart representing Selection control structures

3.3.1 The if Statement


A simple condition is expressed in the form:
if (condition)
statement;
It starts with the keyword if, followed by a condition (a logical expression) enclosed within
parenthesis, followed by the result statement.
The resulting statement is executed if the condition is evaluated as TRUE. Note that there is no
semicolon (;) after the condition expression. Consider the following example:
if (marks >50)
printf("You have passed the exam!");
If the value of the variable “marks” is greater than 50, the message “You have passed the exam!” is
displayed on the screen; otherwise the statement is skipped and no message is displayed.
/*Program 4.1 illustrates the use of if statement in a C program */
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks); //get marks
if(marks > 50) // if marks > 50 display message
printf("You have passed the exam!");
return 0;
}
Executing Program-4.1 with different inputs will behave as follows:
Case 1: Enter marks: 73
You have passed the exam!
Case 2: Enter marks: 34
Case 3: Enter marks: 50
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 44 -
In the second and third cases, the message “You have passed the exam!” will not be displayed.
More than one statement can be executed as a result of the condition by embedding set of statements in
a block (between two braces {}). See Program 4.2 below.
/*Program 4.2*/
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if(marks > 50)
{
printf("You have passed the exam!");
printf(“\nCongratulations”);
}
return 0;
}

3.3.2 If-else Structure


The if-else structure takes the form:
if (condition)
statement- 1;
else
statement- 2;
When the condition is evaluated, one of the two statements will be executed and then the program
resumes its original flow. The C language allows us to use the if-else structure in scenarios where there
is more than one outcome. You can include both the cases (TRUE and FALSE) using the if-else
structure.
Let’s take our previous example, If the value of the variable “marks” is greater than 50, the message
“You have passed the exam!” is displayed on the screen; otherwise the statement “You have failed
the exam!” is displayed.
/*Program 4.3*/
#include <stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks);

if (marks >50)
printf("You have passed the exam!");
else
printf(“You have failed the exam!”);
return 0;
}
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 45 -
In many programs it is required to perform some action when a condition is TRUE and another action
when it is FALSE. In such cases, the if clause can be used to check the TRUE condition and act upon
it.
However it does not act upon the FALSE condition. Therefore, the expression resulting the FALSE
condition needs to be re-organized. Hence the use of if-else structure.
Assessment 4a
1. Write a C program that displays the message “You have passed the exam!”, if marks are
greater than 60. If not display the message “You have failed!”.
2. Write a program to identify whether a number input from the keyboard is Even or Odd. If it is
even, the program should display the message “Number is Even”, else it should display
“Number is Odd”.

3.3.3 if-else-if Ladder


In certain cases multiple conditions are to be detected. In such cases the conditions and their associated
statements can be arranged in a construct that takes the form:
if (condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;

else
statement- n;
This construct is referred as the if-else-if ladder. The different conditions are evaluated starting from
the top of the ladder and whenever a condition is evaluated as TRUE, the corresponding statement(s)
are executed and the rest of the construct is skipped.
Example 4.1 –Write a program to display the student’s grade based on the following table:

Marks Grade

>=75 A
> =50 and <75 B
> =25 and <50 C
< 25 F
In this case multiple conditions are to be checked. Marks obtained by a student can only be in one of
the ranges. Therefore if-else-if ladder can be used to implement following program.
/*Program 4.2*/
#include <stdio.h>
int main()
{
int marks;

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 46 -


printf("Enter marks: ");
scanf("%d", &marks);

if (marks>=75)
printf("A");
else if((marks>=50)&&(marks<75))
printf("B");
else if((marks>=25)&&(marks<50))
printf("C");
else if (marks<25)
printf("F");
else
printf("Invalid Input or mark out of range!");
return 0;
}

In Program-4.6, when the marks are entered from the keyboard the first expression (marks > 75) is
evaluated.If marks is not greater than 75, the next expression is evaluated to see whether it is greater
than 50.
If the second expression is not satisfied either, the program evaluates the third expression and so on
until it finds a TRUE condition. If it cannot find a TRUE expression statement(s) after the else
keyword are executed.

3.3.4 Nesting Conditions


Sometimes we need to check for multiple decisions. This can be accomplished by two approaches;
• using compound relational tests or
• using nested conditions.
• When conditions are nested the if–else/ if-else-if construct may contain other if-else/ if-else-if
constructs within themselves.
In nesting you must be careful to keep track of different ifs and corresponding elses.Consider the
following example:
if (age>=15 && age<=35)
if (age<=19)
printf(“Youth and Teenager!");
else
printf(“Youth!");
An else matches with the last if in the same block. In this example the else corresponds to the second
if.
Therefore, if both age>=15 && age<=35 AND age<=19 are TRUE “Youth and Teenager” will be
displayed; if (age>=15 && age<=35) is TRUE but if age<=19 is FALSE “Youth” will be displayed.
If (age>=15 && age<=35) is FALSE nothing will be displayed.
To reduce any confusion, braces can be used to simplify the source code.Therefore the above can be
rewritten as follows:

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 47 -


if (age>=15 && age<=35)
{
if (age<=19)
{
printf(“Youth and Teenager!");
}
else
printf(“Youth!");
}

Example 4.2 – A car increases it velocity from u ms-1 to v ms-1 within t seconds. Write a
program to calculate the acceleration.
The relationship among acceleration (a), u, v and t can be given as
v = u + at
𝐯−𝐮
Therefore the acceleration can be found by the formula 𝐚 = 𝐭 .
In the program we implement users to input any values for u, v and t. However, to find the correct
acceleration, the time has to be non-zero and positive (since we cannot go back in time and a number
should not be divided by zero).
So our program should make sure it accepts only the correct inputs (Time cannot be 0 or less than 0).
The Program-4.7 calculates the acceleration given u, v and t.

#include<stdio.h>
int main()
{
floatv,u,t,a;

printf("Enter the initial velocity u: ");


scanf("%f",&u);
printf("Enter the final velocity v: ");
scanf("%f",&v);
printf("Enter the time t: ");
scanf("%f",&t);
if(t<=0)
{
printf("Time cannot be zero or less than zero\n");
printf("Enter another value for time t: ");
scanf("%f",&t);
a=(v-u)/t;
}
else
a=(v-u)/t;
printf("Acceleration = %.2f m/s ",a);
return 0;
}
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 48 -
3.3.5 Conditional Operator
Conditional operator (?:) is one of the special operators supported by the C language. The
conditional operator evaluates an expression and returns one of two values based on whether condition
is TRUE or FALSE. It has the form:
condition ?result - 1 : result- 2;
If the condition is TRUE the expression returns result - 1 and if not it returns result - 2.
Example 4.3
Consider the following example which determines the value of variable “b” based on the whether the
given input is greater than 50 or not.If the input is greater than 50 variable “b” will be assigned “1”
and if not it will be assigned “2”.
/* Program-4.8*/
#include <stdio.h>
int main()
{
inta,b;
printf("Enter value of a: ");
scanf("%d", &a); //get value a
b = a >50 ?1 : 2;
printf("Value of b: %d", b);
return 0;
}

Sample Run:
Enter value of a: 49
Value of b: 2
Conditional operator can be used to implement simple if-else constructs. However use of conditional
operator is not recommended as a good programming practice.

3.3.6 The switch Construct


Instead of using if-else-if ladder, the switch construct can be used to handle multiple choices, such as
menu options. The syntax of the switch construct is different from if -else construct. The objective is to
check several possible constant values for an expression. It has the form:
switch (control variable )
{
case constant-1:
statement(s);
break;
case constant- 2:
statement(s);
break;

case constant- n:
statement(s);
break;
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 49 -
default:
statement(s);
}

The switch construct starts with the switch keyword followed by a block which contains the different
cases. Switch evaluates the control variable and first checks if its value is equal to constant-1; if it is
the case, then it executes the statement(s) following that line until it reaches the break keyword.
When the break keyword is found no more cases will be considered and the control is transferred out
of the switch structure to next part of the program. If the value of the expression is not equal to
constant-1 it will check the value of constant-2.
If they are equal it will execute relevant statement(s). This process continuous until it finds a matching
value. If a matching value is not found among any cases, the statement(s) given after the default
keyword will be executed.The control variable of the switch must be of the type int, long or char (any
other data type is not allowed). Also note that the value we specify after case keyword must be a
constant and cannot be a variable (example: n*2).
Example 4.4: Program-4.8 can be re-written as a switch structure. See Program-4.9 below:
/* Program-4.8*/
#include<stdio.h>
int main( )
{
int x = 12;
if(x==12)
printf(“The number is Twelve”);
else if(x==22)
printf(“The number is Twenty Two”);
else if(x==32)
printf(“The number is Thirty Two”);
else
printf(“The number is not 12, 22 or 32”);
return 0;
}

Switch Structure (Corresponding to the program above)


/* Program-4.8*/
#include<stdio.h>
int main( )
{
int x = 12;
switch(x)
{
case 12:
printf(“The number is Twelve”);
break;
case 22:
printf(“The number is Twenty Two”);
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 50 -
break;
case 32:
printf(“The number is Thirty Two”);
break;
default:
printf(“The number is not 12, 22 or 32”);
}
return 0;
}

Practical Assessment / Class Project


Develop a simple calculator to accept two floating point numbers from the keyboard. Then display a
menu to the user and let him/her select a mathematical operation to be performed on those two
numbers. Then display the answer. A sample run of you program should be similar to the following:

GROUP MEMBERS DETAILS


-----------------------------------------------------------
STUDENT NAME REGISTRATION NUMBER COURSE
1. JOHN SMITH 16/2/314/W/000 BIT
2. SHARON BLACK 16/2/306/E/000 BCS
3. ……………………………… …………………………………… …………
-----------------------------------------------------------
Enter first number: 20
Enter second number: 12
Mathematical Operation
-----------------------------------
1 - Add
2 - Subtract
3 - Multiply
4 - Divide
-----------------------------------
Enter your preference: 2
Answer: 8.00

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 51 -


3.4 Repetition Control Structures
A Program is usually not limited to a linear sequence of instructions or conditional structures and it is
sometimes required to execute a statement or a block of statements repeatedly. These repetitive
constructs are called loops or repetitioncontrol structures.
The C language supports three constructs; namely for, while and do- while loops. The rest of this
section introduces these repetitioncontrol structures.

3.4.1 The for Loop


The for loop construct is used to repeat a statement or block of statements a specified number of times. The
general for m of a for loop is:

for (counter - initialization; condition; increment/decrement)

statement(s);

• The construct includes the initialization of the counter, the condition and the increment.

The main function of the for loop is to repeat the statement(s) while the condition remains true. The
condition should check for a specific value of the counter.In addition it provides ways to initialize the
counter and increment (or decrement) the counter. Therefore,the for loop is designed to perform a
repetitive action for a pre-defined number of times.Consider the following example:
/* Program-5.1 */
#include <stdio.h>
int main()
{
int x;
for(x = 80; x <=85; x++) //loop 4 times
{
printf("%d\t",x);
}
return 0;
}

Execution of Program-5.1 displays:


80 81 82 83 84 85
Program-5.1 Explanation: In the above example, the variable “x” starts with an initial value of “80”.
The second expression inside the parenthesis determines the number of repetitions of the loop. It reads
as; “as long as “x” is less than or equal to 85 repeat the statement(s)”.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 52 -


The third expression is the incrimination of x; it is achieved by the ++operator. You may also
decrement x depending on the requirement, but you have to use suitable control expression and an
initial value. In the first round of execution “x” is set to “80”. Then the expression “x<= 85” is
evaluated. Since the current value of the “x “is “80” expression is evaluated as TRUE.
Therefore the printf function gets executed. Then “x” is incremented by the ++operator and now its
new value becomes “81”. At this point the first round of the loop is completed. Then in the second
round the expression is evaluate d again. Since “x” is “81” the expression will be TRUE. Therefore
the printf function gets executed for the second time.
Then “x” is incremented once more and its new value becomes “82”.This process continues for
another 3 rounds. After a total of six rounds “x” becomes “86”. When the expression is evaluated at
the beginning of the sixth round “x” is greater than 85 therefore expression becomes FALSE. Then
the loop will terminate and the control is given to rest of the instructions which are outside the loop.
Example 5.2: Write down program that will output the following on the screen:
21 24 27 30 33 36 39 42
From the output given above, we identify that there is a common difference of 3 between the
successive integer outputs.
/* Program-5.2 */
#include <stdio.h>
int main()
{
int y;
for(y = 21; y<=42; y+=3) //increment by 3
{
printf("%d\t",y);
}
return 0;
}

Example 5.3: Write down a program that will output the following on the screen:
96 90 84 78 72 66 60
From the output given above, we identify that there is a common difference of 6 and the output is
descending.
/* Program-5.3 */
#include <stdio.h>
int main()
{
int p;
for(p = 96; p>=60; p-=6) //decrement by 6
{
printf("%d\t",p);
}
return 0;
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 53 -


Example 5.4 – Write a program to calculate the sum of all the even numbers up to 100.
Solution
• First even number is 0 and the last even number is 100. By adding 2 to an even number the
next even number can be found.
• Therefore the counter should be incremented by 2 in each round. Program-5.4 is an
implementation of the above requirement.
/* Program-5.4 */
#include <stdio.h>
int main()
{
int counter, sum;
sum = 0;
for(counter = 0; counter <= 100; (counter += 2)) //increment by 2
{
sum += counter;
}
printf("Total : %d", sum);
return 0;
}

Assessment 5a
Using a for loop in your program:
1. Write a C program to display all the integers from 140 to 161.
2. Write a C program to display all even numbers between 39 and 65.
3. Write a C program that displays all odd numbers between 14 and 45.
4. Modify Program-5.4 such that it computes the sum of all the odd numbers from 45 to 80.
/* Program-5.4 */
#include <stdio.h>
int main()
{
int counter, sum;
sum = 0;
for(counter = 0; counter <= 100; (counter += 2)) //increment by 2
{
sum += counter;
}
printf("Total : %d", sum);
return 0;
}

5. Write a program to compute the sum of all integers from 52 to 69.


6. Write a program to calculate the factorial of any given positive integer.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 54 -


3.4.2 The while Loop
The while loop construct contains only the condition. The programmer has to take care of the other
elements (initialization and incrementing / decrementing) inside the block. The general form of the
while loop is:
while (condition)
{
statement(s);
}
The loop is controlled by the logical expression that appears between the parentheses. The loop
continues as long as the expression is TRUE.It will stop when the condition becomes FALSE. You
need to make sure that the expression will stop at some point otherwise it will become an infinite
loop.The while loop is suitable in cases where the exact number of repetitions is not known in
advance. Consider Example-5.5:
/* Program-5.5 */
#include <stdio.h>
int main()
{
int x=80;
while(x <=85)
{
printf("%d\t",x);
x++;
}
return 0;
}

OUTPUT:
80 81 82 83 84 85

Example 5.6: Write down a program that will output the following on the screen:
96 90 84 78 72 66 60

From the output given above, we identify that there is a common difference of 6 but this time, the
output is descending. Therefore, the program would look like this:
/* Program-5.6 */
#include <stdio.h>
int main()
{
int x=96;
while(x>=60)
{
printf("%d\t",x);
x-=6;
}
return 0;
}
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 55 -
3.4.3 The do-while Loop
Another useful loop is the do- while loop. The only difference between the do-while loop and other
loops is that in the do-while loop the condition comes after the statement(s). It takes the following
form:
do
{
statement(s);
}
while (condition);

Example 5.8: Write down a program that will output the following on the screen:
96 90 84 78 72 66 60

/* Program-5.8 */
#include <stdio.h>
int main( )
{
int x=96;
do
{
printf("%d\t",x);
x -= 6;
}
while(x>=60);
return 0;
}

This means that the statement(s) inside the loop will be executed at least once regardless of the
condition being evaluated. Consider Example-5.7:
/* Program-5.7 */
#include <stdio.h>
int main( )
{
int x=80;
do
{
printf("%d\t",x);
x++;
}
while(x<=85);
return 0;
}
OUTPUT:
80 81 82 83 84 85

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 56 -


Conclusion: Repetition Statements
• In summary, the for loop is recommended for cases where the number of repetitions is known
in advance.
• The while loop is recommended for cases where the number of repetitions are unknown or
unclear during the development process.
• The do- while loop is recommended for cases where the loop to be executed needs to run at
least once regardless of the condition.
• However, each type of loop can be interchanged with the other two types by including proper
control mechanisms.

Assessment 5b
1. Using a while loop in your program:
i. Write a C program to display all the integers from 59 to 99.
ii. Write a C program to display the following output:
20 40 60 80 100 120
i. Write a C program that computes the sum of all odd numbers between 98 and 120.
2. Rewrite the programs you have written in i, ii and iii above using a do-while loop

3.4.4 Nesting of Loops


Like the conditional structures loops can also be nested inside one another. You can nest loops of any
kind inside another to any depth you want. However having large number of nesting will reduce the
readability of your source code.
Example-5.9 –Write a C program to display the following pattern using nesting loops:
$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$
$$$$$$$$$$
There are 10 “$” symbols in a single row (10 columns) and there are 5 rows. This can be implemented
by having a two loops one nested inside another which print individual “$” symbols.
However the printf function does not support displaying text on a row that you have already printed.
Therefore first you need to fully complete the first row and then you should go to the next. Therefore
the loop which handles printing of individual rows should be the outer loop and one which prints
elements within a row (columns) should be the inner loop.

/* Program-5.6 */
#include <stdio.h>
int main()
{
inti,j;
for(i=0;i<=5;i++) //outer loop
{
for(j=0;j<=10;j++) // inner loop
{
printf("$");

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 57 -


} // end of inner loop
printf(" \n ");
} //end of outer loop
return 0;
}

Assessment 5c
1. Using nested loops, write a C program to display the following symbol patterns:
i) * ii) *****
** ****
*** ***
**** **
***** *

3.4.5 The break Keyword


The break keyword is used to terminate a loop, immediately bypassing any conditions. The control
will be transferred to the first statement following the loop block. If you have nested loops, then the
break statement inside one loop transfers the control to the immediate outer loop. The break statement
can be used to terminate an infinite loop or to force a loop to end before its normal termination.
/* Program-5.10 */
#include <stdio.h>
int main()
{
int n;
for(n = 1; n <= 5; n++) //loop 5 times
{
printf("%d\n",n);
if(n = = 3)
{
printf("Sequence Aborted!");
break;
}
}
return 0;
}
During the first 3 iterations the program executes normally displaying the numbers 1 and 2. Then the
moment the variable “n” becomes “3”, 3 is displayed and then the if condition which evaluates
whether “n==3” becomes TRUE, so it will execute the printf function and then the break instruction.
At this point the loop will terminate because of the break keyword.

Assessment 5d
1. Write a C program to display the message “Hello World!” 105 times. However, you should set
the program to terminate the moment the message is printed 79 times.
2. Write down the output of the Program-5.11 below:

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 58 -


/* Program-5.11 */
#include<stdio.h>
int main()
{
int x;
for (x = 9; x > 2; x--)
{
if (x == 4)
{
break;
}
printf ("%d\t", x);
}
return 0;
}

3.4.6 The continue Keyword


The keyword continue causes the program to skip the rest of the loop in the current iteration, causing it to jump
to the next iteration. Consider Example 5.12:
/* Program-5.12 */
#include <stdio.h>
int main()
{
inti;
for(i = 1 ; i<= 5 ; i++) //loop 5 times
{
if(i = = 3)
continue;
printf("%d\t",i);
}
return 0;
}

Assessment 5e
1. Using the continue keyword, write C programs that will produce the output given below:
N.B. First write the programs using a for loop, then rewrite the programs using a while loop
and lastly with a do-while loop
i. 2 4 8 10 12 14 16
ii. 5 10 15 25 30 35 40
iii. 135 115 75 55 35
iv. 99 88 66 44 33 22

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 59 -


44 ARRAYS
Arrays are a series of elements of the same data type placed consecutively in memory that can be
individually referenced by adding an index to a unique name.
Using an array we can store five values of type intwith a single identifier without having to declare
five different variables with a different identifier.
Arrays are useful when you store related data items, such as grades received by the students, sine
values of a series of angles, etc. Like any other variable in C an array must be declared before it is
used.
The typical declaration of an array is:
datatypearray_name[no_of_elements];
Number of elements is also called the index.
Please Note:the array name must notbe separated from the square brackets containing the index.
When declaring an array, the number of array elements should be a constant. As arrays are blocks of
static memory locations of a given size, the compiler must be able to determine exactly how many
memory locations to allocate at compilation time.
In the first approach, the value of each element of the array is listed within two curly brackets ({})
and a comma ( ,) is used to separate one value from another. For example:
marks[5] = {55, 33, 86, 81, 67};
In the second approach elements of the array can be initialized one at a time. This approach makes use
of the format:
array-name[index];
For example:
marks[0] = 55;
marks[1] = 33;
marks[2] = 86;
marks[3] = 81;
marks[4] = 67;
In an array index of the first element is considered as zero rather than one. Therefore in an array with
“n” elements, the first index is “ 0” and the last index is “ n-1”. This confusion can be overcome by
initializing an array with “n+1” elements and neglecting the first element (element with zero index).
Example 6.1: Below are the weights of seven students in a Computer Science class:
67.8, 78.9, 56.3, 75.4, 66.0, 62.7 and 88.0
i. Declare and initialize an array that will store the above weights
ii. Write down an expression that will add the first element of the array to the fourth
element of that array.
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 60 -
iii. Write down an expression that will increment the last element of the array above.
iv. Write down a printf statement that will output the third element of the array above.
v. Write down one statement which will allow a user to input another value for the fifth
element of that array.
Solution: Example 6.1
a) Below are the weights of seven students in a Computer Science class
67.8, 78.9, 56.3, 75.4, 66.0, 62.7 and 88.0
i. Declare and initialize an array that will store the above weights

Solution 1:

float weights[7];

weights[7]={67.8, 78.9, 56.3, 75.4, 66.0, 62.7, 88.0};

Solution 2:

float weights[7] ={67.8, 78.9, 56.3, 75.4, 66.0, 62.7, 88.0};

Solution 3:

float weights[7];
weights[0]=67.8;
weights[1]=78.9;
weights[2]=56.3;
weights[0]=75.4;
weights[0]=66.0;
weights[0]=62.7;
weights[0]=88.0;

ii. Write down an expression that will add the first element of the array to the fourth
element of that array.

[0] [1] [2] [3] [4] [5] [6]

67.8 78.9 56.3 75.4 66.0 62.7 88.0

We declare a variable sum that will store the result:


float sum = weights[0] + weights[3];
iii. Write down an expression that will increment the last element of the array above.

We declare a variable “y” that will store the result of the incremented element:
float y = ++weights[6];
iv. Write down a printf statement that will output the third element of the array above.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 61 -


printf(“The third element is %f”, weights[2]);
v. Write down one statement which will allow a user to input another value for the fifth
element of that array.

printf(“Input another value for the fifth element: ”);


scanf(“%f”,&weights[4]);

Assessment 6a
4. What is the output of the following program?
#include<stdio.h>
int main()
{
intMyArray[5] = {5, 1, 15, 20, 25};
inti, j, m;
i = ++MyArray[1];
j = MyArray[0]+ MyArray[3];
m = MyArray[4]= MyArray[4]- MyArray[2];
printf("i=%d,\n j=%d,\n m=%d", i, j, m);
return 0;
}
5. At Divine health clinic, a child health professional weighs a baby, measures it and asks routine
questions about its feeding and sleep. He may also chat to mothers about its general wellbeing and
the support it receives at home. Appointments after this generally takes place in the clinic. The
following information represents the weight of babies who were brought for check-up yesterday:
9.8, 7.8, 4.8,9.1, 8.7, 7.8, 4.7 and 6.3.
i. Declare and initialize an array called WEIGHT to store that information
ii. Write an expression that will add the second to the last element of that array
iii. Write an expression that will change the value held by the third element from 4.8 to 5.8
iv. Write down a printf statement that will output the seventh element of the array on the
screen.
v. Write down statements that will enable a user to enter another value for the fifth
element.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 62 -


55 FUNCTIONS IN C

5.1 Introduction to Functions


Now that you should have learned about variables, loops, and conditional statements it is time to learn
about functions. You should have an idea of their uses as we have already used them and defined one
in the guise of main. The main function is an example of an inbuilt C function. Other functions include
printfand scanffunctions.
The inbuilt C functions make up the C libraries, but you can also write your own functions. Therefore,
functions can be classified as built-inand user-defined.
In general, functions are blocks of code that perform a number of pre-defined commands to
accomplish something productive. You can either use the built-in library functions or you can create
your own functions. The general syntax of a function is:
return_typefunction_name (formal parameters or arguments)
{
statements;
return statement;
}

Functions are used extensively in computer languages and spreadsheets. A function takes an input,
does some calculations on the input, and then gives back a result. Once written, a function may be used
many times without having to rewrite it over and over.
In general, a modular program consists of the main( ) function followed by set of user defined
functions as shown:
#include ……
#define …..
Prototypes of functions
intmain( )
{
……….
}
function_1( )
{
………..
}
function_2( )
{
………..
}
…………
function_n( )
{
………..
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 63 -


The source code contains other elements in addition to the function blocks. It starts with the #include
directive, followed by the #define directive (if any) then followed by the prototypes of functions.
A function prototype is a declaration of a function used in the program. Then comes the program
building block which includes the main( ) function and implementation of the user defined functions.

5.2 Function Prototypes


Using functions in your program requires that you first declare the function (using a prototype). Later
you can implement the function.
The prototype tells the compiler in advance about some characteristics (name of the function, return
type and parameters) of a function.
A function prototype takes the form:
return_typefunction_name(type argument_1, type argument_2, …..);
The function prototype is a statement that ends with a semicolon.
Function Definition:
int sum (int a, int b)
{
int c; Function Prototype:

c = (a+b); int sum (int a, int b);


return c;
}

The function name is any legal identifier followed by the function parenthesis without any space in
between. The function “return_type” is the data type of the return value. If the function does not
return a value, the data type is defined as void.
The arguments (or parameters or formal parameters) come inside the parenthesis, preceded by their
types and separated by the commas. If the function does not any parameters, it is either kept blank or
the word void is used inside the parenthesises.
Following are some examples for prototypes:
void exit(int x);
int square( );
float power(int x, float y);
The first function returns no value and it takes an integer argument. Second prototype returns an
integer value and has no inputs. Third function returns a float value and takes one integer value and
one float value.

5.3 Function Definition


The definition of a function is the actual body of the function. It starts with function header, which is
the same as the function prototype but does not end with a semicolon.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 64 -


The function prototype and the definition must have exactly the same return type, name and parameter
list. If they do not match the compiler will issue error messages during compilation.
Function definition takes the form:
Return-type function-name(type argument-1, type argument-2, ….. )
{
Statement(s);
}
For example, a function may be written that finds the sum of two supplied numbers.
Figure 7.1 shows a function that computes sum of two numbers

Below is a function definition that defines a function that returns the sum of two integers.
int sum (int a, int b)
{
int c;
c = (a+b);
return c;
}
On the first line, the name of the function is ‘sum', It expects two integer inputs a andb. In computer
programming these are called formal parameters; they stand for the two values sent when the function
is used. The function has its own private variable c which is calculated from the parameters (a+b) and
then the function 'returns' the result c.
Consider the following function, which accepts an integer as the input and returns its square. The
definition of this function will look like this:
int square(int x)
{
int y;
y = x*x;
return y;
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 65 -


Whenever you want to call this function you can include a statement like the following in the program:
int b = square(a);
Here, the value of variable “a” is passed to the function, where it is received by the function as the
value of variable “x”.
The full program would look like this:
#include<stdio.h>
int square(int x);//function prototype
int main()
{
int a;
printf("Enter value: ");
scanf("%d",&a);
int b = square(a);//calling function
printf("The square of %d is %d",a,b);
return 0;
}
int square(int x)
{
int y;
y=x*x;
return y;
}
The function returns the square as the value of “y”. The variable “b” in the calling function receives
the return value.
Example 7.1 – Write a C program to calculate the circumference and area of a circle given its radius.
Implement calculation of area and circumference as separate functions.
/* Program - Example 7.1 */
#include<stdio.h>
const float pi = 3.141;

float area(float r); //function prototype


float circumference(float r); //function prototype

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 66 -


int main()
{
float radius;
printf("Enter radius: ");
scanf("%f",&radius); //read radius

float a = area(radius); //calling function area


float c = circumference(radius); //calling function circumference

printf("\nArea: %.2f",a);
printf("\nCircumference: %.2f",c);
return 0;
}
/* Function computes area of a circle */
float area(float r)
{
return (pi * r * r);
}

/* Function computes circumference of a circle */


float circumference(float r)
{
return (2 * pi * r);
}

Example 7.2: Define a function called ComputeAVG that accepts two integer values and two float
values, adds them and returns their average.
Solution:
floatComputeAVG(int a, intb,floatc,float d)
{
float average;
average=(a+b+c+d)/4;
return average;
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 67 -


5.4 Function Overloading
Function overloading (also method overloading) is a programming concept that allows programmers to
define two or more functions with the same name but different signatures in the same program.
Each function has a unique signature (or header), which is derived from:
• Function/procedure name
• Number of arguments
• Arguments’ type
• Arguments’ order
• Arguments’ name
• Return type
Please note: Not all above signature options are available in all programming languages.
It is possible to define several functions with the same name but with different parameters. As given
below:
float area(int r);
float area(float r);
Both these functions calculate the area of a circle given the radius. However, the first function accepts
an integer as the input while the second function accepts a floating point number.
Function overloading is present in most of the object oriented languages but C which is a structured
programming language, does not support this feature.

5.5 Scope of a Variable


A variable has a scope, which determines how long it is available to your program (or function) and
where it can be accessed from. Variables declared within a block are scoped only to that block; they
can be accessed only within that block and go out of existence when the execution of the block is
completed.
int sum (int a, int b)
{
int c; //variable c is a local variable
c = (a+b);
return c;
}

A variable declared inside a function is called a local variable. Scope of a local variable is limited to
the function. Such variables are not seen by any other functions including the main function.
When you pass a variable to a function (such as the variable radius in Program-7.1), you are actually
passing a copy of the variable (called passed by value), but not the variable itself. This means that the
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 68 -
value of the passed variable cannot be changed by any other function. Even if you use another variable
with the same name in the function, you still have two local variables isolated from each other.
On the other hand you can also define global variableswhich are accessible from any function within
the same source file. The global variable can be defined within the program but anywhere outside
function block including the main function. For example you can define a global variable “discount”
as follows:
#include <stdio.h>
float discount; //global variable
float sub_total(float total); //function prototype
int main()
{
....

A variable defined in such a manner is visible to the main function and the “sub_total” function. You
can modify its value in either place and read it from another place. A well written C source code
should not have any global variables unless they are specifically required since an accidental change to
a global variable may produce erroneous results.

Default Parameters
For every parameter you declare in a function prototype and declaration the calling function must pass
in a value. The value passed must be of the declared type. Thus if you have a function declared as:
longmy_function(int a);

the function must in fact take an integer value as an input. If the function definition differs or if you
pass a value of a wrong data type you will get a compilation error. However when you declare the
function prototype you can define a default value for the parameter as follows:
longmy_function(int a = 50);
The default value is used if no input is supplied to the function. Similarly a function with many input
parameters can have a default value for each parameter.

Assessment 7a
a) Define the following concepts clearly with relevant examples:
i. Function Prototype ii. Function Overloading
b) What is the relevance of a return type in a function definition?
c) Define a function called ComputeAVG that accepts two floats and two integer values, adds
them and returns their average.
d) Write down one programming statement that will call the function you have written in (c)
above if the following values are passed to it: 43.2, 27.4, 34, 23.
e) Write down a function prototype for the function in (c) above.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 69 -


66 SOLUTIONS TO ASSESSMENTS

Assessment 1b Solutions
1. Developing computer programs entails a number of steps that a programmer has to
undertake during the process of Program Development. Discuss at least five of those
steps.
This question requires one to discuss in detail at least five of the Program development steps.
Below, I outline them but if you are answering this question, you should provide some details
as given in the Program Development section in the course material herein.
Program Development Steps:
 Define the problem
 Outline the solution
 Develop an algorithm for the solution
 Test the algorithm for correctness
 Code the algorithm using a suitable programming language
 Compile and correction of compile compilation errors
 Run the program on the computer
 Test, document and maintain the program

2. What is the relationship between an Algorithm, a Flowchart and a Pseudo code?


An algorithm is a step by step procedure of solving a problem.
Pseudo code is an outline of a program written in a form that can be easily converted into real
programming statements.
Flowchart is a diagrammatic representation giving a step by step solution to a given problem.

Therefore, from the above definitions, we can conclude that a pseudo code and a flowchart are
representations of an algorithm. In order for a programmer to come up with an effective
algorithm, he has to first outline a pseudo code and then construct a flowchart.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 70 -


3. Distinguish between syntax errors and runtime errors.
A syntax error occurs when the programmer fails to obey one of the grammar rules of the
language. Typically this involves things like using the wrong case, putting punctuation where
it is not supposed to be, failing to put punctuation where it is supposed to be etc.
C runtime errors are those errors that occur during the execution of a c program and generally
occur due to some illegal operation performed in the program. Common examples include:
dividing a number by zero, entering a wrong datatype in a scanf program etc.
4. Why are logic errors so hard to identify?

Logical or logic errors are the errors that affect the output of the program. The presence of
logical errors leads to undesired or incorrect output. Logic errors are mainly caused by poor
logic applied in the program development.

Therefore, logic errors are hard to identify by the compiler, and thus, programmers have to
check the entire coding of a program line by line in order to identify an error.

5. What is the major difference between acompiler and an interpreter?


We need to convert the source code into machine code and this is accomplished by compilers
and interpreters. Hence, a compiler or an interpreter is a program that converts program
written in high-level language into machine code understood by the computer.
The major difference between the two is that a compiler scans the entire program and translates
it as a whole into machine code whereas an interpreter translates a program one statement at a
time.

Assessment 1c Solutions
1. D

2. B

3. C

Assessment 2a Solutions
a)

#include<stdio.h>
int main()
{
printf("\"Eva is a\"\n");
printf(" \'good\' student\n");
printf("of \"programming\" ");
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 71 -
return 0;
}

b)

#include<stdio.h>
int main()
{
printf("\"MUSOKE IS A\"\n");
printf("\tGOOD STUDENT\n");
printf("OF \'PROGRAMMING\'");
return 0;
}

Assessment 2b Solutions
1. With examples, explain the meaning of the following terms as applied in Computer
Programming:
i) Variable:In programming, a variable is a reserved memory location capable of storing
temporary data within a program. This data can then be modified, stored, or displayed
whenever needed.For example:
int age; //age is a variable in this statement

ii) Data type: A data type is a classification of the type of data that a variable or object
can hold in computer programming. Examples of data types in C include Integer, float
(floating-point numbers), Characters, Boolean etc.For example:
int age; //the data type of variable age is integer

iii) Literal: Literals are numeric values that appear directly in a program. For Example:
intage = 32; //32 is a literal in this statement

iv) Identifier:An identifier is a label or name given to a variable, function, array, structure or
union.
int age = 32; //age is an identifier given to this variable

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 72 -


2. Write down a C program where you declare and initialize variables for your age and height,
and then output those values on the screen. Height should be declared as a floating point value.
#include<stdio.h>
int main()
{
int age = 32;
float height = 5.8;

printf("I am %d years old\n",age);


printf("I am %f inches high",height);
return 0;
}
Output:
I am 32 years old
I am 5.80000 inches high

3. With examples, distinguish between Declaring a variable and Initializing a variable.


Declaring a variable refers to reserving named space in memory where data of a specified data
type is stored. Examples:

intage; // here we declare variable a of data type integer

floatheight; // here we declare a variable height of data type float

Initializing a variable refers to the process of bringing a value into the reserved space.

int age; // declaring variable a


age= 35; // initializing variable a with value 35

Assessment 2c Solutions
1. Write a program to assign the number 34.5678 to a variable named “number” then display the
number rounded to the nearest integer value and next the number rounded to two decimal
places.

#include<stdio.h>

int main()

{
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 73 -
float number = 34.5678;

printf("The number is %.2f",number);

return 0;

OUTPUT of the Program above:


The number is 34.57
2. Write a program where you declare two float variables and initialize them with 4.32 and
3.4 respectively. Calculate their product and display the result correct to one decimal
place.
#include<stdio.h>

int main()

float a = 4.32;

float b = 3.4;

float product;

product = a * b;

printf("The result is %.1f",product);

return 0;

Assessment 2d Solutions
a) Outline a pseudo code for a program that accepts three float values, adds them and computes
their average. The sum and average should be then be displayed.

Pseudo code
 Start
 Declare three variables
 Input values for the three variables
 Calculate the sum by adding the three values
 Calculate the average by dividing the sum by 3
 Display the sum and average
 End

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 74 -


b) Draw a flowchart diagram to represent the pseudo code you have outlined above.

c) Transform the pseudo code you have written in (e) above into a complete C program that can
be used to compute and display the sum and average of any three float values entered from the
keyboard.

#include<stdio.h>
int main()
{
float a,b,c;
printf("Enter the first float value:");
scanf("%f",&a);
printf("Enter the second float value:");
scanf("%f",&b);
printf("Enter the third float value:");
scanf("%f",&c);
float sum = a + b + c;
float average = sum / 3;
printf("SUM: %f\n",sum);
printf("AVERAGE: %f",average);
return 0;
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 75 -


Assessment 3a
1. Give the values of variables “a”, “b”, “sum1” and “sum2” if the following code segment is executed.

int a, b,sum1,sum2;

a = 2, b = 7;

sum1 = a + (++b);

sum2 = a + (b++);

//For the first statement:

sum1 = a + (++b); // ++b becomes 8


sum1 = 2 + 8 =10
//when we get to the second statement a is still 2 but b has been incremented by 1 becoming 8

sum2 = a + (b++);// during the evaluation of this statement, b remains 8 due to the postfix increment
but will be incremented after this operation becoming 9

sum2 = 2 + 8 = 10
Therefore at the end of the second statement’s evaluation, a =2 , b =9, sum1=10 and sum2 = 10

2.
#include<stdio.h>
int main()
{
int a=2,b=8,c=11,d,e;
a = b + c; //a=8+11=19
d = ++a * 2;//
e = ++c + b--;//
printf ("a=%d\n", a);//
printf ("d=%d\n", d);//
printf ("e=%d\n", e);//
printf ("b=%d\n", b);//
return 0;
}

Workings
a = b + c;
a = 8 + 11=19

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 76 -


d = ++a * 2
d = (19+1) * 2
d = 20 * 2 = 40

e = ++c + b--
e = (11+1) + 8 = 20

OUTPUT:

a=20
d=40
e=20
b=7

3. i)
#include <stdio.h>
int main()
{
int a=10,b=20,c=40;
int p, q, t;
p = c + a * b / 2;
q = c / 2 / a * 2;
t = a++ * b;
printf("Ans1:%d", p);
printf("\nAns2:%d", q);
printf("\nAns3:%d", t);
return 0;
}

Workings

p=c + a*b/2 q = c / 2 / a * 2;
p = 40+10*20/2 q = 40 / 2 / 10 * 2
p = (40+((10*20)/2)) q = (((40 / 2) / 10) * 2)
p = 40 + (200 / 2) q = ((20 / 10) * 2)
p = 40 + 100 = 140 q=2*2=4
t = a++ * b;
t = (a++) * 20
t = 10 * 20 = 200
OUTPUT:

Ans1: 140

Ans2: 4

Ans3: 200
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 77 -
ii)
#include<stdio.h>

int main()

int a=1,b=2,c=4,d,e;

a = b + c;

d = ++a * 2;

e = ++c + b--;

printf (“%d\n”, a);

printf (“%d\n”, d);

printf (“%d\n”, e);

return 0;

Workings

a=b+c e = ++c + b--;


a=2+4=6 e = 5 + 2 = 7
d = ++a * 2
d = (6+1) * 2 = 14
OUTPUT
7
14
7

2. Use the code fragment below to answer questions c(i) and c(ii).
#include<stdio.h>
int final, easy, a, b;
float easy;
a=20;
b=4;
final= a * b++;
easy= final / b;
// b+=2;
printf(“The value of \n final is:%d”, final);
printf(“\t and easy is:%.2f”, easy);
i) Write down the output of the code above.
ii) Write one programming statement that will output a and b on the screen

Workings
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 78 -
final = a * b++
final = 20 * 4 = 80

From the above statement, a = 20 , b = 5


easy = final / b
easy = 80 / 5 = 16
// b +=2; is a comment therefore has no bearing on the output

i)
OUTPUT:

The value of
final is: 80 and easy is 16.00

ii) a= 20, b = 16.00

Assessment 5a
Using a for loop in your program:
1. Write a C program to display all the integers from 140 to 161

#include <stdio.h>
int main()
{
int x;
for(x=140;x<=161;x++)
{
printf("%d\t",x);
}
return 0;
}

2. Write a C program to display all even numbers between 39 and 65.

#include <stdio.h>
int main()
{
int x;
for(x=39;x<=65;x+=1)
{
if(x%2==0) //if remainder of x divided by 2 is 0
printf("%d\t",x);
}
return 0;
}

3. Write a C program that displays all odd numbers between 14 and 45.
#include <stdio.h>
int main()
{
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 79 -
int x;
for(x=14;x<=45;x+=1)
{
if(x%2==1)
printf("%d\t",x);
}
return 0;
}

Assessment 4a
1. Write a C program that displays the message “You have passed theexam!”, if marks are greater than
60. If not display the message “Youhave failed!”.
#include<stdio.h>
int main()
{
int marks;
printf("Enter marks: ");
scanf("%d",&marks);
if(marks>=60)
printf("You have passed the exam");
else
printf("You have failed the exam");
return 0;
}
2. Write a program to identify whether a number input from the keyboardis Even or Odd. If it is even,
the program should display the message“Number is Even”, else it should display “Number is Odd”.
#include<stdio.h>
intmain()
{
int number;
printf("Enter number: ");
scanf("%d",&number);
if(number%2==0)
printf("Number is even!");
else
printf("Number is odd!");
return 0;
}

Assessment 5a
Using a for loop in your program:
1. Write a C program to display all the integers from 140 to 161
#include <stdio.h>
int main()
{
int x;
for(x=140;x<=161;x++)
{
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 80 -
printf("%d\t",x);
}
return 0;
}

2. Write a C program to display all even numbers between 39 and 65.


#include <stdio.h>
int main()
{
int x;
for(x=39;x<=65;x+=1)
{
if(x%2==0) //if remainder of x divided by 2 is 0
printf("%d\t",x);
}
return 0;
}

3. Write a C program that displays all odd numbers between 14 and 45.
#include <stdio.h>
int main()
{
int x;
for(x=14;x<=45;x+=1)
{
if(x%2==1)
printf("%d\t",x);
}
return 0;
}

4. Modify the Program-5.4 below such that it computes the sum of all the odd numbers from 45 to 80.
#include <stdio.h>
int main()
{
int counter, sum;
sum = 0;
for(counter = 0; counter <= 100; (counter += 1))
{
if(counter%2==1)
sum += counter;
}
printf("\nTotal : %d", sum);
return 0;
}

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 81 -


5. Write a program to compute the sum of all integers from 52 to 69.
#include <stdio.h>
int main()
{
int counter, sum;
sum = 0;
for(counter = 52; counter <= 69; (counter += 1))
{
sum += counter;
}
printf("\nTotal : %d", sum);
return 0;
}

6. Write a program to calculate the factorial of any given positive integer.


#include <stdio.h>
int main()
{
inti,f=1,num;

printf("Enter a number: ");


scanf("%d",&num);

for(i=1;i<=num;i++)
{
f=f*i;
}
printf("Factorial of %d is: %d",num,f);
return 0;
}

Assessment 5b
Using a while loop in your program:
i. Write a C program to display all the integers from 59 to 99.
#include <stdio.h>
int main()
{
inti=59;
while(i<=99)
{
printf("%d\t",i);
i++;
}
return 0;
}

ii. Write a C program to display the following output:


20 40 60 80 100 120

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 82 -


#include <stdio.h>
int main()
{
inti=20;
while(i<=120)
{
printf("%d\t",i);
i+=20;
}
return 0;
}

Assessment 5d
1. Write a C program to display the message “Hello World!” 105 times. However, you should set
the program to terminate the moment the message is printed 79 times.

#include <stdio.h>
int main()
{
int y;
for(y=1;y<=105;y++)
{
printf("Hello World!\t");
if(y==79)
break;
}
return 0;
}

2. Write down the output of the Program-5.11 below:


#include<stdio.h>
int main()
{
int x;
for (x = 9; x > 2; x--)
{
if (x == 4)
{
break;
}
printf ("%d\t", x);
}
return 0;
}

OUTPUT:
9 8 7 6 5
Assessment 5e
1. Using the continue keyword, write C programs that will produce the output given below:
N.B. First write the programs using a for loop, then rewrite the programs using a while loop
and lastly with a do-while loop

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 83 -


i. 2 4 8 10 12 14 16
From the display above, we observe that 6 is skipped in the sequence of the output.
Therefore our program will look like this:

#include<stdio.h>
int main()
{
int x;
for (x = 2; x<=16 ; x+=2)
{
if (x == 6)
{
continue;
}
printf ("%d\t", x);
}
return 0;
}

ii. 5 10 15 25 30 35 40
From the display above, we observe that 20 has been skipped in the sequence of the
output. Therefore our program will look like this:

#include<stdio.h>
int main()
{
int x;
for (x = 5; x<=40 ; x+=5)
{
if (x == 20)
{
continue;
}
printf ("%d\t", x);
}
return 0;
}

iii. 135 115 75 55 35


From the display above, we observe that 20 has been skipped in the sequence of the
output. Therefore our program will look like this:

#include<stdio.h>
int main()
{
int x;
for (x = 135; x>=35 ; x-=20)
{
if (x == 95)
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 84 -
{
continue;
}
printf("%d\t", x);
}
return 0;
}

iv. 99 88 66 44 33 22
From the display above, we observe that 77 and 55 are missing in the sequence of the
output. Therefore our program will look like this:

#include<stdio.h>
int main()
{
int x;
for (x = 99; x>=22 ; x-=11)
{
if ((x == 77)||(x ==55))//if x is 77 or 55
{
continue;
}
printf ("%d\t", x);
}
return 0;
}

Practice the use of the continue keyword by rewriting the programs above using the while and do while
loops.

Additionally, you can practice by coming up with your own output.

Assessment 6a
1. What is the output of the following program?

#include<stdio.h>
int main()
{
intMyArray[5] = {5, 1, 15, 20, 25};
inti, j, m;
i = ++MyArray[1];
j = MyArray[0]+ MyArray[3];
m = MyArray[4]= MyArray[4]- MyArray[2];
printf("i=%d,\n j=%d,\n m=%d", i, j, m);
return 0;
}

OUTPUT:
i=2,

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 85 -


j=25,
m=10

Explanation:
i = ++MyArray[1];//MyArray[1] is the second element which is 1
i = 2; //after being pre-incremented by 1
j = MyArray[0]+ MyArray[3];//first element added to fourth
j = 5 + 20 = 25
m = MyArray[4]= MyArray[4]- MyArray[2];
The precedence of arithmetic operators is higher than the precedence of assignment
operators. Therefore, statement(MyArray[4]- MyArray[2])is handled first.Then
the associativity of assignment operators is Right to Left. Therefore, the statement shall be
handled in the following order.
m = (MyArray[4]= (MyArray[4]- MyArray[2]));
m = (MyArray[4]= 25-15);
m = MyArray[4]=10;
Therefore, Element MyArray[4] is assigned value10 and then10 is assigned to m (Right to
Left Associativity)

2. At Divine health clinic, a child health professional weighs a baby, measures it and asks routine
questions about its feeding and sleep. He may also chat to mothers about its general wellbeing
and the support it receives at home. Appointments after this generally takes place in the clinic.
The following information represents the weight of babies who were brought for check-up
yesterday: 9.8, 7.8, 4.8, 9.1, 8.7, 7.8, 4.7 and 6.3.
i. Declare and initialize an array called WEIGHT to store that information
The values given for the weight of babies are eight(8), therefore, the number of
elements for the array to keep these baby weights will be 8

float WEIGHT[8]={9.8,7.8,4.8,9.1,8.7,7.8,4.7,6.3};

ii. Write an expression that will add the second to the last element of that array
We declare variable y to store the value attained from adding the second to the last
element of the array WEIGHT
float y;
y = WEIGHT[1] + WEIGHT[7];

iii. Write an expression that will change the value held by the third element from 4.8
to 5.8

WEIGHT[2] = 5.8;

iv. Write down a printf statement that will output the seventh element of the array on the
screen.
printf(“The seventh element is: %f”, WEIGHT[6]);

v. Write down statements that will enable a user to enter another value for the fifth
element.

printf(“Enter another value for 5th element:”);


- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 86 -
scanf(“%f”,WEIGHT[4]);

Assessment 7a
a) Define the following concepts clearly with relevant examples:
i. Function Prototype
Function Prototype refers to the declaration of a function in a program. Later on the function is
then defined or implemented.

int sum (int a, int b);//function prototype

ii. Function Overloading


Function overloading (also method overloading) is a programming concept that allows
programmers to define two or more functions with the same name but different signatures in
the same program.
e.g. int sum(int a, int b)
{
return (a+b);
}

float sum(float a, float b)


{
return (a+b);
}

b) What is the relevance of a return type in a function definition?


The return type defines the data type of the value returned by the function.
e.g. given the function below:

float sum(float a, float b)


{
return (a+b);
}

The return type of the function above is float because the function will return a floating point
value.

c) Define a function called ComputeAVG that accepts two floats and two integer values,
adds them and returns their average.

floatComputeAVG(float a,floatb,intc,int d)
{
return (a+b+c+d)/4;
}
d) Write down one programming statement that will call the function you have written in (c)
aboveif the following values are passed to it: 43.2, 27.4, 34, 23.

ComputeAVG(43.2, 27.4, 34, 23);

e) Write down a function prototype for the function in (c) above.


floatComputeAVG(float a,floatb,intc,int d);
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 87 -
77 REVISION QUESTIONS
1) What effect do comments have on the executable program?
2) What is the difference between a statement and a block?
3) What is a function?
4) What is the significance of a function prototype?
5) C offers two types of functions. What are they, and how are they different?
6) The following programs have problems. Enter them in your editor and compile them. Which lines
generate error messages?
(a) (b)
1: #include <stdio.h> 1: #include <stdio.h>
2: 2:
3: int main(); 3: int main()
4: { 4: {
5: printf( "Keep looking!" ); 5: printf( "This is a program with a " );
6: printf( "You\'ll find it!\n" ); 6: do_it( "problem!");
7: return 0; 7: return 0;
8: } 8: }

7) Consider the following program:


1: /* Functions */
2: #include <stdio.h>
3:
4: void display_line( );
5:
6: int main()
7: {
8: display_line();
9: printf("\n C language is so named coz its predecessor was called B \n");
10:display_line();
11:
12: return 0;
13: }
14:
15: /* print asterisk line */
16: void display_line( )
17: {
18: int counter;
19:
20: for( counter = 0; counter < 11; counter++ )
21: printf("*" );
22: }
23: /* end of program */
a. What line(s) contain statements?
b. What line(s) contain variable definitions?
c. What line(s) contain function prototypes?
d. What line(s) contain function definitions?
e. What line(s) contain comments?
f. Write down the output of the Program
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 88 -
8) Show two methods for defining a symbolic constant named MAXIMUM that has a value of 100.
9) In what variable type would you best store the following values?
a. A person's age to the nearest year. g. The temperature.
b. A person's weight in pounds. h. A person's net worth.
c. The radius of a circle. i. The distance to a star in miles.
d. Your annual salary.
e. The cost of an item.
f. The highest grade on a test (assume it is
always 100).
10) Determine appropriate variable names for the values in Question 8.
11) Write declarations for the variables in Question 9.
12) Which of the following variable names are valid?
a. 123variable g. RADIUS
b. x h. Radius
c. total_score i. radius
d. Weight_in_#s j.this_is_a_variable_to_hold_the_width_of_a_box
e. one.0
f. gross-cost
13) To what value do each of the following expressions evaluate?
a. (1 + 2 * 3) d. (5 == 5)
b. 10 % 3 * 3 - (1 + 2) e. (x = 5)
c. ((1 + 2) * 3)
14) If x = 4, y = 6, and z = 2, determine whether each of the following evaluates to true or false.
a. if( x == 4) c. if(z = 1)
b. if(x != y - z) d. if(y)
15) Fix the following program so that it runs correctly.
/* a program with problems... */
#include <stdio.h>
int x= 1:
main()
{
if( x = 1);
printf(" x equals 1" );
otherwise
printf(" x does not equal 1");
return 0;
}
16) You are required to design an interactive C program that allows a user to enter a mark between 0 and
100, then the program displays “CONGRATULATIONS! YOU HAVE PASSED AND YOU CAN
NOW FORGET ALL YOUR SLEEPLESS NIGHTS” if the value entered is between 100 and 50, and
“SORRY, IT’S A RETAKE, YOU WILL HAVE TO DO THIS COURSE UNIT AGAIN, THIS TIME
MORE INTELLIGENTLY” if the value entered is between 0 and 49.N.B the words should be
displayed along with the quotes they have.
i) Write down a pseudo code for the above task.
ii) Draw a flow chart diagram to represent the pseudo code in (a) above
iii) Write a complete source code in C to accomplish the above task.
17) What return type do the following functions return?
a) int print_error( float err_nbr);
b) long read_record( int rec_nbr, int size );
- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 89 -
18) What's wrong with the following function definition?
int twice(int y);
{
return (2 * y);
}
19) Write a function that receives two numbers as arguments and returns the value of their product.
20) Write a function that receives two numbers as arguments. The function should divide the first number
by the second. Don't divide by the second number if it's zero. (Hint: Use an if statement.)
21) Write a program that uses a function to find the average of five type float values entered by the user.
22) Write a declaration for an array that will hold 40 type long values.
23) Show a statement that assigns the value of 123.456 to the 50th element in the array from Question 22.
24) Write a for statement to count from 0 to 500.
25) Write a while statement to count from 0 to 500.
26) Write a do...while statement to count from 0 to 500.
27) What is the output of the following code fragment?
for (x = 0; x < 10; x++)
{
for (y = 5; y > 0; y--)
{
printf ("X=%d and Y=%d", x ,y);
printf("\n")
}
printf("Next \n")
}
28) Write pseudo code and create a flowchart for a program that calculates the average of three marks and
finally prints out the average. The word PASSED should be printed only if the average is greater than
49.
29) Write a complete source code in C for the task in Question 28 above.
30) Identify the error(s) in the following program:
int get_1_or_2( )
{
int answer = 0;
while (answer < 1 || answer > 2)
{
printf(Enter 1 for Yes, 2 for No);
scanf( "%f", answer );
}
return answer;
}
31) Write a program that inputs integers from the keyboard, storing them in an array. Input should stop
when a zero is entered or when the end of the array is reached. Then, finds and displays the array's
largest and smallest values.
32) Suppose we want to send some numbers over a phone line, but the phone line is tapped. We want to
use some (very simple) encryption to stop them from stealing our information. One quick and easy
way to do this is to reverse the digits of our number. For example, 12345 becomes 54321. Think about
how we can use %10 in a loop to get the last digit, and how we can make the new number using a
loop. Use only basic control structures and operators. Write a C code for problems (a) and (b).
a) Code a small program that will take in a number and prints out the encrypted number.
b) Write a decryption code that the receiver will use to decrypt the message.

- Ndejje University - IT 1107 / CS 1107 Principles of Programming - 90 -

You might also like