Scs101 - Introduction Computer Programming
Scs101 - Introduction Computer Programming
INTRODUCTION
COMPUTER
PROGRAMMING
Department: COMPUTER SCIENCE
Lecturer’s Name: Dr. Tirus Muya
Email: [email protected]
Contact: 0721913790
Computer Programming introduction
1GL or first-generation language was (and still is) machine language or the
level of instructions and data that the processor is actually given to work on.
2GL or second-generation language is assembler (sometimes called
"assembly") language.
3GL or third-generation language is a "high-level" programming language,
such as PL/I, C, or Java. A compiler converts the statements of a specific high-
level programming language into machine language.
4GL or fourth-generation language is designed to be closer to natural
language than a 3GL language. Languages for accessing databases are often
described as 4GLs.
5GL or fifth-generation language is programming that uses a visual or
graphical development interface to create source language that is usually
compiled with a 3GL or 4GL language compiler.
Microsoft, Borland, IBM, and other companies make 5GL visual programming
products for developing applications in Java, for example.
Visual programming allows you to easily envision object-oriented
Programming paradigms /Languages
2. Assembly Language
Sometimes referred to as assembly or ASL, assembly language is a low-level programming language used to
interface with computer hardware.
Assembly language uses structured commands as substitutions for numbers allowing humans to read the code
easier than looking at binary
Although easier to read than binary, assembly language is a difficult language and is usually substituted for a
higher language such as C.
Programming paradigms /Languages
3. Low-level Languages
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free
and can be used to edit and debug C code.
We will use Code::Blocks in our tutorial, which we believe is a good place to start.
Terminal Decision /
(Start or Stop Process to be
Compariso
of program performed
n
flow) Operation
Input / Output
Direction
operation
Example of a
Flow chart
Problem: Find the total /average of two numbers
Assignments: Draw flow chart of each problem
1. Input the length L and the breadth B, calculate and output the area of a
rectangle.
2. User inputs radius and flowchart calculates and shows the area of a circle
3. Print the number from 1 to 100 (Hint: use a counter & loop)
4. Enter 20 marks and print their average.
5. Ask a person for a number between 1 and 100, ask again if they give you a
number outside that range
6. Input 40 marks. Count and print how many marks are below 50.
7. Input M and print the square of M if it is between 1 and 10.
8. Input a mark. Calculate and output a student's grade;
80 < A <= 100
60 < B <= 80
40 < C <= 60
0 <= U <= 40
Format of a C program
Preprocessor directive
Functions
Variables
Statements & Expressions
Comments
Example
/* First C program: Hello World */ Comment
#include <stdio.h> //Preprocessor directive
Data types refer to an extensive system used for declaring variables or functions of
different types before its use. The value of a variable can be changed any time.
The type of a variable determines how much space it occupies in storage and how
the bit pattern stored is interpreted.
C has the following 4 types of data types
Basic Types:
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
Enumerated types:
They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.
The type void:
The type specifier void indicates that no value is available.
Derived types:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types,
and (e) Function types.
VARIABLES
A variable is a name given to a storage area that our programs can manipulate.
All the variables must be declared prior to use in a program
When a variable is given a value, that value is actually placed in the memory space assigned
to the variable.
All variables must be declared before they can be used.
Declaration purposes:
It associates a type and an identifier (or name) with the variable
it allows the compiler to decide how much storage space to allocate for storage of the value
associated with the identifier and to assign an address for each depending with type.
The syntax to declare a new variable is to write the specifier of the desired data type (like int,
bool, float...) followed by a valid variable identifier. For example:
int x; //declares a variable of type int with the identifier x
Float myage; // declares a variable of type float with the identifier myage
Once declared, the variables x and myage can be used within the rest of their scope in the
program.
To declare more than one variable of the same type, can be declared all of them in a single
statement by separating their identifiers with commas. For example:
Example
// operating with variables
#include <stdio.h>
int main ()
{
int a, b; // declaring variables:
int result; // declaring variables:
a = 5; // process:
b = 2; // process:
a = a + 1; // process:
result = a - b; // process:
printf("Result %d \n",result);// print out the result:
return 0; // terminate the program:
}
C – printf and scanf
1. printf() is used to display the output and scanf() is used to read the inputs.
2. printf() and scanf() functions are declared in “stdio.h” header le in C library.
3. All syntax in C language including printf() and scanf() functions are case sensitive.
Use printf() function with %d format specifies to display the value of an integer
variable.
Ampersand (&)is used before variable name in scanf() statement
& variable name is used to point to the variable.
Example of format specifies
%c is used to display character
%f for float variable
%s for string variable
%lf for double
%x for hexadecimal variable
\n got replaced by a newline
A C program consists of various tokens and a token is either a keyword, an
Example of format specifies
#include <stdio.h>
int main()
{
int number = 45;
char character= 'Y';
char charstring[20]= "cprogramming";
float gravity = 9.8;
double pi=3.142;
printf("number is %d\n", number);
printf("character is %c\n", character);
printf("charstring is %s\n", charstring);
printf("float is %f\n", gravity);
printf("double is %lf\n", pi);
return 0;
}
Operator
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations
C++ is rich in built-in operators and are mainly keywords
Generally, there are six type of operators:
Arithmetical operators
Relational operators,
Logical operators,
Assignment operators,
Conditional operators,
Arithmetic operators ( +, -, *, /, % )
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Modulus or remainder % is the operation that gives the remainder of a division of two
values. For example, if we write:
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11 between
3.
Relational operators
The relational operators are used to test the relation between two values.
All relational operators are binary operators and therefore require two
operands.
A relational expression returns zero when the relation is false and a non-zero
when it is true.
Operator Meaning Example
Returns TRUE if first value is smaller than second value otherwise 10 < 5 is
<
returns FALSE FALSE
Returns TRUE if first value is larger than second value otherwise returns 10 > 5 is
>
FALSE TRUE
Returns TRUE if first value is smaller than or equal to second value 10 <= 5 is
<=
otherwise returns FALSE FALSE
Returns TRUE if first value is larger than or equal to second value 10 >= 5 is
>=
otherwise returns FALSE TRUE
10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE
10 != 5 is
!= Returns TRUE if both values are not equal otherwise returns FALSE
TRUE
Logical operators ( !, &&, || )
The Operator ! is the C++ operator to perform the Boolean operation NOT,
It produces false if its operand is true and true if its operand is false.
Basically, it returns the opposite Boolean value of evaluating its operand
Expression Meaning
!(5 == 5) evaluates to false because the
expression at its right (5 == 5)
is true.
!(6 <= 4) evaluates to true because (6 <=
4) would be false.
!true evaluates to false
!false evaluates to true
Logical operators ( AND i.e &&, || i.e
OR)
The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
The operator && corresponds with Boolean logical operation AND.
This operation results true if both its two operands are true, and false
otherwise
The operator || corresponds with Boolean logical operation OR.
This operation results true if either one of its two operands is true, thus
being false only when both operands are false themselves.
a b a && b a b a||b
true true true true true true
true false false true false true
false false false false true true
+= A+=2 A=A+2
-= A-=2 A=A- 2
%= A % =2 A=A%2
/= A /= 2 A=A/2
*= A *= 2 A=A*2
Increment and Decrement Operators
incrementing and decrementing the value of a variable by 1
Increment and decrement operators each have two forms, pre and
post
In Prefix form first variable is first incremented/decremented, then
evaluated
In Postfix form first variable is first evaluated, then incremented /
decremented.
%f Float Printf
LOGIC/SEMANTICS ERRORS
Occurs when a program follows a faulty algorithm. The only sign of a logic error may be
an incorrect output.
Eg. Omitting & in the scan f
Eg. Enter two values and find their sums
Scan f ( “ % d % d ”, first, second);
Control Structures
Control structures allows to control the flow of program’s execution based on certain
conditions C supports following basic control structures:
Conditional structure
if and if else statements
Iteration structures (loops)
The while loop
The do while loop
The for loop
The selective structure
switch statement
Jump statements
The break statement
The continue statement
The goto statement
if and if else statements
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
Example
#include <stdio.h>
int main()
{
/* local variable definition */
int x = 100;
/* check the boolean condition */
if (x == 100)
{
printf("print value %d\n", x );
}
return 0;
}
If else // Program to evaluate a wage
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
switch Statement
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch case.
The following rules apply to a switch statement:
The expression used in a switch statement must have an integral or enumerated type,
You can have any number of case statements within a switch.
Each case is followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch.
The default case can be used for performing a task when none of the cases is true. No break is
needed in the default case.
syntax
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
cout << "x is 2"; }
break; else {
default: cout << "value of x
cout << "value of x unknown"; unknown" }
}
Iteration structures (loops)
#include <stdio.h>
int main ()
{ int n;
for (n=10; n>0; n--) {
printf(" %d ", n);
}
printf("FIRE!\n");
return 0;
}
The while loop
executes a target statement as long as a given condition is true.
functionality is simply to repeat statement while the condition
set in expression is true.
while(condition)
{
statement(s);
}
Example
// additional using while
#include <stdio.h>
1. User assigns a value to n
2. The while condition is checked (n>0).
At this point there are two posibilities:
int main () { * condition is true: statement is executed
/* local variable definition */ (to step 3)
int a = 10; * condition is false: ignore statement and
/* while loop execution */
continue after it (to step 5)
3. Execute statement: cout << n << ", ";
while( a < 20 ) {
--n; (prints the value of n on the screen
printf("value of a: %d\n", a); and decreases n by 1)
a++; 4. End of block. Return automatically to
} step 2
return 0; 5. Continue the program right after the
block: print FIRE! and end program.
}
The do-while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed
to execute at least one time.
The conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again.
This process repeats until the given condition becomes false.
}while( condition );
Example
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
Nested Loops loop inside another
Theloop
syntax for a nested for loop statement }
for ( init; condition; increment ) statement(s);
{ }
for ( init; condition; increment )
{ The syntax for a nested do...while loop
statement
statement(s);
}
do
statement(s);
{
}
statement(s);
do
The syntax for a nested while loop statement
{
while(condition)
statement(s);
{
}while( condition );
while(condition)
{statement(s);
Nested for loop
// nested for loop to find the prime numbers from 2 to 100
#include <stdio.h>
int main () {
/* local variable definition */
int i, j;
for(i = 2; i<100; i++) {
break;
}
}
return 0;
CONTINUE STATEMENT IN C
Works somewhat like the break statement.
Instead of forcing termination, it forces the next
iteration of the loop to take place, skipping any code
in between.
For the for loop, continue statement causes the
conditional test and increment portions of the loop to
execute.
For the while and do...while loops, continue statement
causes the program control to pass to the conditional
tests.
Syntax
The syntax for a continue statement in C is as follows
-continue;
C FUNCTIONS
A function is a group of statements that together perform a task. Every C program has at least one
function,which is main function.
A function is known with various names like a method or a sub-routine or a procedure etc.
Functions are used to provide modularity to a program. Creating an application using function
makes it easier to understand, edit, check errors etc.
Syntax of Function/Defining a Function
return-type function-name (parameters)
{
// function-body
}
return-type : suggests what the function will return. It can be int, char, some pointer or even a class
object.
There can be functions which does not return anything, they are mentioned with void.
Function Name : is the name of the function, using the function name it is called.
Parameters : are variables to hold values of arguments passed while function is called. When a
function is invoked, you pass a value to the parameter. This value is referred to as actual parameter
or argument.
A function may or may not contain parameter list.
Declaring, Defining and Calling Function
Function declaration, is done to tell the compiler
about the existence of the function.
printf( "Max value is : %d\n", ret );
A function declaration has the following parts -
return 0;
return_type function_name( parameter list );
}
Function's return type, its name & parameter list is
/* function returning the max between two numbers */
mentioned.
int max(int num1, int num2) /* function definition*/
Function body is written in its definition.
{
#include <stdio.h>
/* local variable declaration */
/* function declaration */
int result;
int max(int num1, int num2);
int main () {
if (num1 > num2)
/* local variable definition */
result = num1;
int a = 100;
else
int b = 200;
result = num2;
int ret;
/* calling a function to get max value */
return result;
ret = max(a, b);
}
Calling Function
To use a function, it must be called or invoked.
When a program calls a function, program control is transferred to the called function
While creating a C function, you give a definition of what the function has to do
A called function performs defined task and when it’s return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main function
To call a function, you simply need to pass the required parameters along with function name, and if function
returns a value, then you can store returned value.
ret = max(a, b);
Functions are called by their names. If the function is without argument, it can be called directly using its
name.
But for functions with arguments, we have two ways to call them,
1. Call by Value
This method copies the actual value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.
2. Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.
Call by Value
In this calling technique we pass the values of swap(a, b);
arguments which are stored or copied into the
printf("After swap, value of a : %d\n", a );
formal parameters of functions.
printf("After swap, value of b : %d\n", b );
Hence, the original values are unchanged only
the parameters inside function changes. return 0;
Calling the function swap by passing actual }
values as in the following example – it will produce the following result -
#include <stdio.h> Before swap, value of a :100
/* function declaration */ Before swap, value of b :200
void swap(int x, int y); After swap, value of a :100
int main () { After swap, value of b :200
/* local variable definition */
int a = 100; So the variable inside main() doesn’t change
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
Call by reference
In this we pass the address of the variable as
arguments.
In this case the formal parameter can be taken as a
/* function definition to swap the
reference or a pointer, values */
in both the case they will change the values of the
original variable.
void swap(int *x, int *y) /* declare the
The call by reference method of passing arguments
function parameters as pointer types
to a function copies the address of an argument into */
the formal parameter.
The address is used to access the actual argument
{
used in the call.
int temp;
It means the changes made to the parameter affect
the passed argument. temp = *x; /* save the value at
To pass a value by reference, argument pointers are address x */
passed to the functions just like any other value.
So accordingly you need to declare the function
*x = *y; /* put y into x */
parameters as pointer types as in the following
function swap,
*y = temp; /* put temp into y */
which exchanges the values of the two integer return;
variables pointed to, by their arguments.
}
Calling the function swap by passing values by reference
#include <stdio.h> */
/* function declaration */ swap(&a, &b);
void swap(int *x, int *y);
printf("After swap, value of a : %d\n", a );
int main () { printf("After swap, value of b : %d\n", b );
/* local variable definition */
int a = 100; return 0;
int b = 200; }
printf("Before swap, value of a : %d\n", a ); Produce the following result -
printf("Before swap, value of b : %d\n", b ); Before swap, value of a :100
Before swap, value of b :200
/* calling a function to swap the values. After swap, value of a :200
* &a indicates pointer to a ie. address of After swap, value of b :100
variable a and
It shows that the change has reflected outside the
* &b indicates pointer to b ie. address of function as well, unlike call by value where the
variable b. changes do not reflect outside the function.
Arrays in C
An array is a data structure which allows a collective name to be given to a group of
elements which all have the same type.
An individual element of an array is identified by its own unique index (or subscript).
C provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
An array can be thought of as a collection of numbered boxes each containing one data
item.
The number associated with the box is the index of the item.
The index must be an integer and indicates the position of the element in the array.
Thus the elements of an array are ordered by the index.
Declaration of Arrays
To declare an array in C++, the programmer specifies the type of the elements and
the number of elements required by an array as follows -
type arrayName [ arraySize ];
This is called a single-dimension array.
The arraySize must be an integer constant greater than zero and type can be any
valid C++ data type.
For example data on the average temperature over the year in Britain for each of
the last 100 years could be stored in an array declared as follows:
float annual_temp[100];
This declaration will cause the compiler to allocate space for 100 consecutive float
variables in memory.
The number of elements in an array must be fixed at compile time.
It is best to make the array size a constant and then, if required, the program can
be changed to handle a different size of array by changing the value of the
constant,
Initialisation of arrays
An array can be initialised in a similar manner as variables.
The initial values are given as a list enclosed in curly brackets.
For example initialising an array to hold the first few prime numbers could be
written as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
# #include <stdio.h> }
int main () { return 0;
}
int n[ 10 ]; /* n is an array of 10 integers */ Output
int i,j; Element[0] = 100
Element[1] = 101
/* initialize elements of array n to 0 */ Element[2] = 102
for ( i = 0; i < 10; i++ ) { Element[3] = 103
n[ i ] = i + 100; /* set element at location i to i Element[4] = 104
+ 100 */ Element[5] = 105
} Element[6] = 106
/* output each array element's value */ Element[7] = 107
for (j = 0; j < 10; j++ ) { Element[8] = 108
printf("Element[%d] = %d\n", j, n[j] ); Element[9] = 109
C MULTI-DIMENSIONAL ARRAYS; Two-Dimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional
array declaration - type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array - int threedim[5]
[10][4];
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of
size x,y, you would write something as follows -
type arrayName [ x ][ y ];
two-dimensional array can be think as a table, which will have x number of rows and y number of
columns.
A 2-dimensional array a, which contains three rows and four columns can be shown as below –
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
Initializing & Accessing Two-Dimensional Arrays
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example -
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the
array. For example - int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above diagram.
Example
#include <stdio.h> When the above code is compiled and executed, it
produces the following result -
a[0][0]: 0
int main () {
a[0][1]: 0
a[1][0]: 1
/* an array with 5 rows and 2 columns*/
a[1][1]: 2
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},
{4,8}}; a[2][0]: 2
int i, j; a[2][1]: 4
/* output each array element's value */ a[3][0]: 3
for ( i = 0; i < 5; i++ ) { a[3][1]: 6
a[4][0]: 4
for ( j = 0; j < 2; j++ ) { a[4][1]: 8
printf("a[%d][%d] = %d\n", i,j, a[i][j] ); As explained above, you can have arrays with any
number of dimensions, although it is likely that
}
most of the arrays you create will be of one or two
} dimensions.
return 0;}
C – ARRAY OF STRINGS
Strings are actually one-dimensional array of characters terminated by a null character '\
0'.
Thus a null terminated string contains the characters that comprise the string followed by
a null.
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello"; you do not place the null character at the end of a string
constant.
The C compiler automatically places the '\0' at the end of the string when it initializes the
array.
Following is the memory presentation of the above defined string in C/C++ -
Example
#include <stdio.h>
int main () {
Every variable is a memory location and every produces the following result -
memory location has its address defined which Address of var1 variable: 22fe4c
can be accessed using ampersand & operator, Address of var2 variable: 22fe40
which denotes an address in memory.
How to Use Pointers?
a pointer variable, assign the address of a ip = &var; /* store address of var in pointer
variable to a pointer
variable*/
Finally access the value at the address
available in the pointer variable. printf("Address of var variable: %x\n", &var );
This is done by using unary operator * /* address stored in pointer variable */
that returns the value of the variable
located at the address specified by its printf("Address stored in ip variable: %x\n", ip );
operand.
/* access the value using the pointer */
The following example makes use of these
operations printf("Value of *ip variable: %d\n", *ip );
return 0;
#include <stdio.h>
}
int main ()
Address of var variable: bffd8b3c
{
Address stored in ip variable: bffd8b3c
int var = 20; /* actual variable declaration */
Value of *ip variable: 20