ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
EXPECTED LEARNING OUTCOMES
By the end of this lecture, you should have:
1. Understood the basics of programming and the IDE platform
2. Learnt the syntax and structure of the C Program language
3. Understood fundamental C programming concepts such as variables, data types, arithmetic
operators, input and output operations.
4. Developed debugging and problem-solving skills
5. Developed simple programming skills through hands-on practice
INTRODUCTION RECAP
C – Is a general purpose structured programming language that is powerful, efficient and compact.
It was an offspring of the Basic Combined Programming Languages (BCPL) called B, developed
in the 1960’s at Cambridge University.
B Language was modified by Dennis Ritchie and was implemented at bell Laboratory in 1972.
The new language was named C. It was strongly associated with UNIX, which was also developed
at bell laboratories.
CHARACTERRISTICS OF IMPORTANCE OF C LANGUANGE.
It has rich set of built function and operations that can be used to write and complex
program.
The C – compiler combines the capabilities an assembly language with the feature of a
high level language and therefore it is well suited for writing both system software and
business packages.
Programs written in C are efficient and fast this is due to its variety of date types and
powerful operation.
Its highly portable i.e C programs written for one computer can be run on another with
little or no modification. This is important if we plan to use a new computer with a
different Operating System (OS).
It’s well suited for structured programming by using function modules or blocks which
make a complete program.
C language is extensible. It can be extended by a programmer by adding our own
functions to the C library with the available of a large number of functions. The
programming task becomes simple.
Page 1 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
LECTURE 2
BASIC STRUCTURE OF A C-PROGRAM.
A C-program may include one or more sections as following:
1) Documentation section: Consists of comment line giving the name of the program,
the author, date, aim of the program. Done in two approaches: single line (//…) or
multiline (/*….*/).
2) Link section: Provide instructions to the computer to link the function to its system
library.
3) Definition section: Defines all symbolic constants.
4) Global declaration section: There are some variable that are used in more than one
function, and are called global variable. They are declared in this section outside all
the functions including the main function.
5) The Main()
Declaration part – declares the variables used in the executable part.
Executable part - contains at least one statement.
6) Subroutines Section: Contains all user defined function.
C is NOT a force-form language but a free-form language.
It does require knowing where to type the program even as long as the termination is right, because
as earlier defined C is a general-purpose programming language that was originally developed for
system programming.
It is often referred to as a high-level programming language due to its expressive syntax and
powerful features.
We use upper case characters for symbolic constant otherwise C language should be in lower case.
Sample Programs
/* This program displays the word “HELLO”
Author: Lawrence
Dates: 30/05/2023 */
# include <stdio.h> //Header file
void main ()
{
printf(“ HELLO”);
}
Page 2 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
C-PROGRAM CHARACTER SET
The character in C language is grouped into the following categories:
1. Letter A-Z both upper case and lowercases
2. Digits 0-9
3. White spaces: Blank space, Horizontal tab, carriage return, new lime, form feed
4. Special Character
Comma, period, semi colon, colon,? ,” ”, ||, vertical bar (||), % ,#, &, (caret), \, minus sign,
<, >, ( ),etc
Reserved Words/keywords
They appear in lower case and have special meaning in a program and cannot be used for other
purposes.
auto double int struct
break else long switch
case enum register typeof
char extern return union
const float short unsigned
continue for signed void
default go to sizeof volatile
do if static while
STANDARD IDENTIFIERS
These are words having special meaning but one that a programmer may redefine (but redefinition
is not recommended).
e.g printf, scanf.
User defined identifiers
Refers to the name of variables, functions and arrays.
Syntax rules
1. An identifier must consist only of letters, digits and underscores.
2. Cannot begin with digit
3. C language reserved words cannot be used as an identifier.
4. An identifier defined in a C standard library should not be redefined.
NB:
- Pick a meaningful name for a user – defined identifier, so its use is easy to understand.
- They use of uppercase and lowercase characters must be taken into consideration.
e.g RATE, Rate and rate are viewed as different identifiers.
Page 3 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
Constants
These are fixed values that do not change during the execution of a program.
They consist of:-
1) Numeric constants – integer constant, real constant
2) Character constant
(a) Single character constant – consists of a single character enclosed within a pair
of single quote mark e.g “5”, ‘X’
Character constants have integer values known as all values
e.g. Printf(“A”) i.e. would point 97as the value of letter A
(b) String Constant:
A sequence of character enclosed in double quotes e.g “Hello”
Backslash Character constants
These combination of characters is known as escape sequence. They are used in output function.
Constant Meaning
\a Audible alert (bell)
\n New line
\r carriage return
\t Horizontal tab
\v Vertical tab
VARIABLES
A variable is a data name that may be used to store a data value and take different value at different
times during executing.
Variable Declaration
A variable declaration starts with a data type followed by variable lists; it tells the compiles what
the variable name is of which type.
e.g
int apple,ball;
double X,Y,Z;
Page 4 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
Data Type
A data type is a set of value and a set of operations on those values they include.
1. Standard / Primary / Fundamental data types
a) int – Integers i.e. whole numbers e.g. 1,2,3,….
b) double – double precision floating point, float i.e. floating point e.g. 1.12, 2.34, 0.567, etc
We can use scientific rotation for representing real numbers.
e.g
1.23 x 107 is written as 1.23e +7
1.23 x 10-7 is also written as 1.23e -7
c) char – Presents an individual character value; a letter, a digit, a special symbol, and must be
enclosed in single quotes.
Data Type Range of Values
char - 128 to 127
int - 32,768 to 32,767
float - 4e -38 to 3.4 e +38
double - 1.7 e -308 to 1.7 e +308
2. User defined data types
Supports features known as “type definition” that allows user to define an identifier that would
represent an existing data type.
Format:
typedef data-type identifier;
e.g
typedef int units;
typedef double marks;
Enumerated date type
These user – defined data type is enumerated date type defined as follows.
Format:
enum identifier{ v1,v2,…………….,vN};
The enumeration constants are enclosed in brace after this definition we can declare to be of this
new type.
e.g
enum identifies{variable1, variable2,……..,variableN};
Example:
enum days{Monday,Tuesday,Wednesday,…..,Sunday};
enum day{week _st , week_end};
Week_st = Monday,Tuesday,…..,Friday
Page 5 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
Week_end = Saturday and Sunday
3. Derived data types
Examples:
Arrays, functions, structure and pointers
Assignments Statements
Format:
Variable = expression
e.g
x= y+z+2.0; We need to -double- x y z since the variable in the expression has 2dp.
INPUT / OUTPUT (Operations and Functions)
1. The printf function.
This displays the program’s output.
The function arguments are enclosed in parenthesis after the function name.
Format:
Format strings – strings of characters enclosed in quotation marks (“ ”).
Placeholder – is a symbol beginning with % in a format string that indicates where to
display the output value.
Printlist – in a call to print, is the variable or expressions whose values are displayed.
Place Holder Variable Function
%c char printf()/scanf()
%d or %i int printf()/scanf()
%f double printf()
%lf double scanf()
2. Scanf Function
This copies the data from a standard input device e.g keyboard into a variable (stored in temporal
memory).
e.g
scanf (“ % d’’ ,&a, &b);
Return 0 – last statement in a program and it transfers control from your program to the operating
system.
NB:
The placeholders used with scanf() are the same as those used with printf() except for
variable of types double. The double variable use a %f placeholder in printf() and %lf in
scanf() format string in most compilers.
Page 6 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
Multiple Placeholder
If the printlist of a printf() call has several variables, the format-strings should contain the same
number of placeholder that matches variables; from left to right order.
e.g.
printf(” %d %d % f”, a,b,c);
Prompts messages
These are displayed to indicate what data to enter and in what form we use printf function for this.
Formatting number in the output
1. Formatting value of type int.
If you simply add a number between the % and the i of the %i placeholder in the printf format-
string, it specify the field-width i.e. the number of columns to be used for the display of the value.
e.g
printf(“%4i”,perimeter);
2. Formatting value of type double
We indicate both the total field-width needed and the number of decimal places desired, the total
field-width should be large enough to accommodate all i.e. digit before and after the decimal place.
Syntax:
%n.mf
Where:
n is the total field-width,
m number of decimal place.
COMMON PROGRAMMING ERRORS.
Errors in a program are called bugs and the process correcting them is called debugging the
program.
When the compiler detects an error, the computer displays an error message, which indicates what
mistakes you have made and the likely cause of the error.
Three kinds of error can occur.
1. Syntax Error:
Occurs when your code violates one or more grammar rule of C and is detected by the compiler
as it attempts to translate your program.
2. Run – time Error:
Are detected and displayed during the execution of a program. It occurs e.g. when the program
divides a number by zero.
Page 7 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
e.g
int first, second, temp, ans;
Printf (“Enter two integers\n”);
Scanf (“%i %i”,&first, &second);
temp = second / first;
ans = first / temp;
Assuming the value you enter are 14 and 3
3. Undetected Errors:
Many execution errors may not prevent a C program from running to completion, but may simply
lead to incorrect result.
4. Logic Error:
Occurs when a program follows a fault algorithm.
The only sign of a logical error - may be an incorrect output.
e.g
Omitting character ‘&’ in the scanf() function
i.e.
Enter two values and find in the program their scanf(“ %i %i’’, First, Second); function
appearing as “First, Second” without ‘&’…
OPERATORS AND EXPRESSIONS
An operator is a symbol that tells the computer to perform certain methodical or logical
manipulations.
1. Arithmetic Operations
These includes; +, -, /, %
- Integer division indicates any fractional part.
- Modula division produces the remainder of an integer division.
Exercise:
Write a C program that takes the number of days as input and outputs the months and days
Hint:
months = days /30
remainingDays = days % 30
NB:
In mixed mode arithmetic (including with real and integers numbers), if either
operand is of real type, the results is always a real number.
Page 8 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
2. Relational Operator
These are used to compare quantities of 6 relational operators that yields true or
false, they are:-
<,>,<= >=, = =,! =
The arithmetic operands have a higher priority over relational operands.
3. Logical operators && and ||
The && and | | logical operation are used when we want to test more than one
condition and make decision.
4. Assignment Operation
Are used to assign the result of an express to a variable.
We used the “=” as the assignment operator.
Syntax:
var = expression (operator) expression
e.g
x = x + (y+1)
In addition we can use shorthand assignment operation of the form:
var (op) = exp
e.g x + = y+1 which is equivalent of x= x+y+1
a = a% b which is equivalent of a % = b
Advantages of using shorthand assignment operation.
a) What appears in the Left Hand Side need not be repeated and therefore it becomes easier to
write.
d) The statement is more precise and easier to read.
c) The statement is more efficient to use.
d) Increment and decrement operations take the forms: M++ or ++M
M-- or --M
If the operator proceeds, the operand will be altered in value before it is used in the statement
If the operator follows the operand the values of the operand will be changed after the variable is
used.
Conditional operator “?:”
Syntax:
exp1? exp2 : exp3
Expression 1 is evaluated first, if it is true (>0); then the expression 2 is evaluated and becomes
the value of the expression, If exp1 is false (<0), exp3 is evaluated and becomes the value of the
expression
Page 9 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
e.g.
for: a=5, b=10
x = (a>b) ? a : b
is equivalent to:
if (a>b)
x=b
else
x=a
Writing Mathematical Formulas in C Language
Mathematical formula C-program expression
b2 – 4ac b*b – 4*a*c
y b m = (y-b)/(x-a)
m=
xa
Area = r 2 2 rh Area = pi*r*r - 2*pi*r*h
Mathematical Library Functions (Pre-defined Functions)
To use any of the functions (below the table) we should include; #include <math.h>
Functions Standard Purpose Argument Result
Library
Header file
abs(x) < stdlib.h> Absolute value of x int int
ceil(x) < math .h> Returns smallest integral double double
value not less than x
e.g. ceil(45.23) = 46
Returns the biggest integral ,, ,,
floor(x) <math.h> value that is not greater than
x e.g. floor(45.73) = 45.0
cos(x) < ,, > double double
sin(x) ,, Returns exponential of x (radians)
exp(x) ,,
double double
Abs. value of double
fabs(x) <math.h>
double double
Page 10 of 11
ICS 1102 PROGRAMMING CONSTRUCTS Introduction to Programming
Others Pre-defined Functions
1. sqrt(x) - square root of x
2. pow(x,y) - returns x to power of y i.e. (x y)
3. mod(x,y) - remainder of x÷y
4. Log(x) – returns the natural log of x
5. Log10(x) – returns base 10 to logarithm of x
Exercise
1. Rewrite the following mathematical expressions using C functions
x y
3
a) u y n2 b)
c) log x y d) 1xy z
2. Write a complete C program that prompts the user for the Cartesian coordinates of two
prompt (x1,y1) & (x2,y2) and displays the distance between them using formula.
distance = ( x1 x 2) 2 ( y1 y 2) 2
3. Write a C program that prompts for a, b and x and calculate.
side = a 2 b 2 2ab cos(x)
4. For a certain electrical circuit with an inductance I and resistance R, the damped
nature frequency is given by.
I R2
frequently =
4c 2
It is desired to study the function of this frequency with capacitance (c). Write a program to
calculate frequency for different values of C starting from 0.01 to 0.1 in steps of 0.01
Page 11 of 11