Principles of Programming-2016
Principles of Programming-2016
Principles of Programming-2016
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
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.
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
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
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
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.
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
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.
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
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()
{
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;
}
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
\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’
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.4 –Basic C data types and modifiers (on a 32-bit machine)
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
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. */
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.
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.
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.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.
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
3.3Arithmetic Operators
C supports five major arithmetic operators and two extended operators (See Table 3.1).
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;
k++ + 10;
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;
Relational Operators
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 //gives 0
Logical Operators
! Logical NOT !(5 == 5) // gives 0
&& Logical AND 5 < 6 && 6<7 //gives 1
|| Logical OR 5 < 6 || 6 < 5 // gives 1
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;
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) ______
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”.
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;
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.
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;
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.
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;
}
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;
}
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;
}
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;
}
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
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
/* 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("$");
Assessment 5c
1. Using nested loops, write a C program to display the following symbol patterns:
i) * ii) *****
** ****
*** ***
**** **
***** *
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:
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
Solution 1:
float weights[7];
Solution 2:
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.
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.
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.
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( )
{
………..
}
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.
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;
}
printf("\nArea: %.2f",a);
printf("\nCircumference: %.2f",c);
return 0;
}
/* Function computes area of a circle */
float area(float r)
{
return (pi * r * 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;
}
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.
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
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.
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.
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
Initializing a variable refers to the process of bringing a value into the reserved space.
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;
return 0;
int main()
float a = 4.32;
float b = 3.4;
float product;
product = a * b;
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
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;
}
int a, b,sum1,sum2;
a = 2, b = 7;
sum1 = a + (++b);
sum2 = a + (b++);
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
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--;
return 0;
Workings
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
i)
OUTPUT:
The value of
final is: 80 and easy is 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;
}
#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;
}
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;
}
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;
}
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;
}
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
#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;
}
#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.
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,
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.
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.
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.