PROGRAMMING
This book is a guide on how you
can write a program based on the principles of program writing, the book has no
additional information unless it is written in the program only with a few
details. Drawings that are physical diagrams are drawn to show how the program
works.
Used C ++ compiler where a
challenge may arise if you copy this program to another compiler but the
program code will remain the same
This book does not have any reference unless it tries to show how the program is written and that is why it does not have any information to put it in referen
Table of Contents
THREE BY THREE
DIMENSION ARRAY
THREE BY THREE DIMENSION ARRAY
STYLES FOR
WRITING FUNCTION NAMES
FUNCTION PARAMETERS AND NON PARAMETERS
GLOBAL AND LOCAL FUNCTION DEFINITION
CONDITIONAL
STATEMENTS VS SWITCH CASE
NESTED IF INSIDE BOTH IF AND ELSE
IF INSIDE IF GRADING SYSTEM PROGRAM
FILE HANDILING CREATE FILE MANUAL
CREATE FILE MANUAL 2 DISPLAY NAMES
CREATE FILE MANUAL
ARRAY AND FUNCTION
CREATE FILE
USER INPUT AND OUTPUT
CREATE FILE CREATE ACCOUNT AND LOGIN
GENERAL CONCEPTS
v VARIABLE DECLARATION
v VARIABLE INITILIZATION
v FLOW OF CONTROL
v WHILE LOOP
v FOR LOOP
v DO WHILE LOOP
v SWITCH CASE
v POINTER
v ARRAY
v 1 DIMENSION ARRAY
v 2 DIMENSIONS ARRAY
v 3 DIMENSION ARRAY
v ARRAY WITH IF CONDITION
v ARRAY WITH LOOP
v FUNCTION
v FUNCTION TYPES
v FUNCTION PARAMETERS
v PARAMETER CATEGORIES
v IF CONDITION
v DYNAMIC MEMORY ALLOCATION
v
DYNAMIC
MEMORY DE ALLOCATION
v
RAM
DIAGRAMS
ARRAY DIMENSIONS
THREE BY THREE
DIMENSION ARRAY
THREE DIMENSIONS,
TWO ROWS, TWO COLUMNS
PROGRAM 1 NON USER
INPUT
#include<fstream> using namespace std; int main() {
for(int a=0;a<3;a++) { { cout<<arr[a][b][c]<<endl; } } } } |
PROGRAM 1 PHYSICAL TABLE
INDEX 1 INDEX 0
INDEX 0 |
1st DIMENSION INDEX 0 |
||
INDEX 1 |
|
INDEX 0 INDEX 1
INDEX 0 |
2ND DIMENSION INDEX 1 |
||
INDEX 1 |
8 |
INDEX 0 INDEX 1
INDEX 0 |
3RD DIMENSION INDEX 2 |
||
INDEX 1 |
23 |
PROGRAM 2 USER INPUT
#include<iostream> #include<fstream> using namespace std; int main() { int arr[3][2][2]
; cout<<"enter elements"; for(int i=0;i<3;i++) { for(int j=0;j<2;j++) { for(int
x=0;x<2;x++) { cin>>arr[i][j][x]; } } } for(int a=0;a<3;a++) { for(int b=0;b<2;b++) { for(int
c=0;c<2;c++) { cout<<arr[a][b][c]<<endl; } } } } |
PROGRAM 2 PHYSICAL TABLE
INDEX 1 INDEX 0
INDEX 0 |
1st DIMENSION INDEX 0 |
||
INDEX 1 |
|
INDEX 0 INDEX 1
INDEX 0 |
2ND DIMENSION INDEX 1 |
||
INDEX 1 |
8 |
INDEX 0 INDEX 1
INDEX 0 |
3RD DIMENSION INDEX 2 |
||
INDEX 1 |
23 |
THREE BY THREE DIMENSION ARRAY
THREE
DIMENSIONS, THREE ROWS, THREE COLUMS PROGRAM 3
PRINT INITILIZED CHARACTERS |
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
string
arrai[3][3][3]= {
{{"a","b","c"},{"d","e","f"},{"g","h","i"}},
{{"j","k","l"},{"m","n","o"},{"p","q","r"}},
{{"s","t","u"},{"v","w","x"},{"y","z","jina
lako ni"}}
};
cout<<arrai[2][2][2]<<endl;
cout<<arrai[2][0][0];
cout<<arrai[0][2][1];
cout<<arrai[0][0][0];
cout<<arrai[1][1][0];
cout<<arrai[0][2][2];
cout<<arrai[1][2][2] ;}
PROGRAM 3 PHYSICAL TABLE
string
arrai[3][3][3]= {
{{"a","b","c"},{"d","e","f"},{"g","h","i"}},
{{"j","k","l"},{"m","n","o"},{"p","q","r"}},
0 1 2 column
a |
b |
c |
d |
e |
f |
g |
h |
i |
0 1 2 row
1st DIMENSION INDEX 0
0 1 2 column
j |
k |
l |
m |
n |
o |
p |
q |
r |
2ND DIMENSION INDEX 1 0 1 2 column 0 1 2 row
s |
t |
u |
v |
w |
x |
y |
z |
jina lako ni |
3RD DIMENSION INDEX 2 0 1 2 row
PROGRAM 3 OUTPUT ANALYSIS
[2] =index 2
dimension [2] =row no: 2 [2] =column no: 2 =jina lako ni
[2] =index 2
dimension [0] =row no: 0 [0] =column no: 0 =S
[0] =index 0
dimension [2] =row no: 2 [1] =column no: 1 =H
cout<<arrai[0][2][1];
[0] =index 0
dimension [0] =row no: 0 [0] =column no: 0 =A
cout<<arrai[0][0][0];
[1] =index 1
dimension [1] =row no: 1 [0] =column no: 0 =M
[0] =index 0
dimension [2] =row no: 2 [2] =column no: 2 =I
cout<<arrai[0][2][2];
[1] =index 1
dimension [2] =row no: 2 [2] =column no: 2 =R
cout<<arrai[1][2][2] ;
PROGRAM 4 PRINT USER ENTERED
PROGRAM
THAT PRINTS ALL ALPHABET ENTERED BY
USER INPUT UNSPECIFIED
SIZE THREE
BY THREE DIMENSION ARRAY |
User enters characters until they meet maximum array size
3x3x3=27 characters specified default in
array size declaration
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
cout<<"enter
character";
char
arrai[3][3][3];
for (int a=0;a<3;a++)
{
for
(int b=0;b<3;b++)
{
for
(int c=0;c<3;c++)
{
cin>>arrai[a][b][c];
}
}}
PROGRAM 4 PHYSICAL TABLE
char arrai[3][3][3];
suppose user input
A to Z how would loop round to
display outputs ?
a |
b |
c |
d |
e |
f |
g |
h |
i |
0 1 2 row
1st DIMENSION INDEX 0
0 1 2 column
j |
k |
l |
m |
n |
o |
p |
q |
r |
0 1 2 row 2ND DIMENSION INDEX 1 0 1 2 column
s |
t |
u |
v |
w |
x |
y |
z |
A |
0 1 2 row 3RD DIMENSION INDEX 2
PROGRAM 4 INPUT
ANALYSIS
DIMENSION 0 1ST
ROW
A in
DIMENSION [0] ROW [0] COLUMN [0] will be saved
B in
DIMENSION [0] ROW [0] COLUMN [1] will be saved
for (int b=0;b<3;b++)
C in
DIMENSION [0] ROW [0] COLUMN [2] will be saved
for (int c=0;c<3;c++)
DIMENSION 0 2ND
ROW
cin>>arrai[a][b][c];
E in
DIMENSION [0] ROW [1] COLUMN [1] will be saved F in
DIMENSION [0] ROW [1] COLUMN [2] will be saved G in
DIMENSION [0] ROW [2] COLUMN [0] will be saved I in
DIMENSION [0] ROW [2] COLUMN [2] will be saved K in
DIMENSION [1] ROW [0] COLUMN [1] will be saved L in
DIMENSION [1] ROW [0] COLUMN [2] will be saved N in
DIMENSION [1] ROW [1] COLUMN [1] will be saved DIMENSION 1 2ND
ROW P in
DIMENSION [1] ROW [2] COLUMN [0] will be saved R in
DIMENSION [1] ROW [2] COLUMN [2] will be saved Z in
DIMENSION [2] ROW [2] COLUMN [1] will be saved DIMENSION 2 2ND
ROW W in
DIMENSION [2] ROW [1] COLUMN [1] will be saved DIMENSION 2 1ST
ROW T in
DIMENSION [2] ROW [0] COLUMN [1] will be saved DIMENSION 2 3ND
ROW S in
DIMENSION [2] ROW [0] COLUMN [0] will be saved U in
DIMENSION [2] ROW [0] COLUMN [2] will be saved V in
DIMENSION [2] ROW [1] COLUMN [0] will be saved X in
DIMENSION [2] ROW [1] COLUMN [2] will be saved Y in
DIMENSION [2] ROW [2] COLUMN [0] will be saved A in
DIMENSION [2] ROW [2] COLUMN [2] will be saved DIMENSION 1 3ND
ROW Q in
DIMENSION [1] ROW [2] COLUMN [1] will be saved M in
DIMENSION [1] ROW [1] COLUMN [0] will be saved 0 in
DIMENSION [1] ROW [1] COLUMN [2] will be saved J in
DIMENSION [1] ROW [0] COLUMN [0] will be saved DIMENSION 1 1ST
ROW DIMENSION 0 3ND
ROW H in
DIMENSION [0] ROW [2] COLUMN [1] will be saved D in
DIMENSION [0] ROW [1] COLUMN [0] will be saved
PROGRAM 4
INPUT/OUTPUT TABLE
a |
b |
c |
d |
e |
f |
g |
h |
i |
0 1 2 row
1st DIMENSION INDEX 0
0 1 2 column
j |
k |
l |
m |
n |
o |
p |
q |
r |
2ND DIMENSION INDEX 1 0 1 2 column 0 1 2 row
s |
t |
u |
v |
w |
x |
y |
z |
jina lako ni |
3RD DIMENSION INDEX 2 0 1 2 row
SINGLE DIMENSION ARRAY
PROGRAM 5
·
PRINTS ONLY USER NAME ·
ENTERED BY USER INPUT ·
SPECIFIED SIZE ·
ACCORDING TO NAME SIZE ·
USER CHOOSE SIZE OF HIS NAME |
#include<iostream> #include<fstream> using namespace std; int main() { int size; cout<<"enter
size"; cin>>size; string
names[size]; cout<<"enter
char"; for(int
a=0;a<size;a++) { cin>>names[a]; } cout<<"your
names"<<endl; for(int a=0;a<size;a++) { cout<<names[a]; } } |
TWO BY TWO DIMENSION
·
PROGRAM 6 ·
NON USER INPUT |
#include <iostream> #include <fstream> using namespace std; int main() { int array[2][3]={{1,2,3},{4,5,6}}; for(int a=0;a<2;a++) { for(int j=0;j<3;j++) { cout<<array[a][j]; } } } |
PROGRAM 6 PHYSICAL TABLE
int array[2][3]={{1,2,3},{4,5,6}}; 0 1 0
1 2
1 |
2 |
3 |
4 |
5 |
6 |
PROGRAM 6 OUTPUT
ANALYSIS
Index [0][0]
print 1 Index [0][1]
print 2 Index [0][2]
print 3 Index [1][0]
print 4 Index [1][1]
print 5 Index [1][2]
print 6
for(int a=0;a<2;a++)
{
for(int j=0;j<3;j++)
FLOW OF CONTROL
DYNAMIC MEMORY ALLOCATION
|
PROGRAM ONE WITHOUT
CONDITION
Memory allocation command using namespace std; { int size; Assigning variable “size” to pointer cout<<"how many tanzania
cities"<<endl; cin>>size; ptr=new string[size]; Loop, input one by one element according to size { Input pointer array to i cout<<"you have
entered"<<endl; for(int i=0;i<size;i++) cout<<ptr[i]; Loop, to output one by one element according to size Memory de allocation return 0; } |
v
PROGRAM
ONE ALGORITHIM
STEP 1: HOW MANY
TANZANIA CITIES
STEP 2: READ ARRAY
SIZE
STEP 3: ENTER ONE BY ONE CITY
STEP 3: ASSIGN
VARIABLE SIZE TO POINTER
STEP 4: ASSIGN I
TO ARRAY SIZE
STEP 5: READ/PRINT ONE
ONE CITY
v
PROGRAM
TWO WITH CONDITION
#include <iostream> using namespace std; int main() { int size; string *ptr=
NULL; cout<<"how
many tanzania cities"<<endl; cin>>size; ptr=new
string[size]; if(size>5) {// cout<<"enter
one by one cities"<<endl; for(int
i=0;i<size;i++) { cin>>ptr[i]; } cout<<"you
have entered"<<endl; for(int
i=0;i<size;i++) { cout<<ptr[i]; } }// else { cout<<"tanzania cities are not
less than 5"; } delete ptr; return 0; } |
PROGRAM TWO ALGORITHIM
STEP 1: HOW MANY
TANZANIA CITIES
STEP 2: READ ARRAY
SIZE IF >=5 CONTINUE
STEP 3: ENTER ONE BY ONE CITY
STEP 4: ASSIGN
VARIABLE SIZE TO POINTER
STEP 5: ASSIGN I
TO ARRAY SIZE
STEP 6: READ/PRINT ONE
ONE CITY
STEP 7: TANZANIA CITIES ARE NOT LESS THAN 5
FLOW OF CONTROL FUNDAMENTALS
·
FOR LOOP ·
PROGRAM THREE ·
INITILIZATION OUTSIDE THE LOOP |
#include <iostream> using namespace std; int main() int x=0; for(;
x<10 ; ) { cout<<x; ++x; } UPDATE v
UPDATE v
DECLARATION v
INITILIZATION v
DECLARATION v
INITILIZATION v
CONDITION v
UPDATE |
·
PROGRAM FOUR ·
INITILIZATION INSIDE THE LOOP ·
UPDATE OUTSIDE THE LOOP |
#include <iostream> using namespace std; INITILIZATION v
UPDATE for(int x=0; x<=10;) { cout<<x; ++x; }
|
#include <iostream> using namespace std; INITILIZATION v
UPDATE { cout<<x; } CONDITION |
X++
POST INCREMENTATION ++X
PRE INCREMENTATION x- -
POST DECREMENTATION -- x
PRE DECREMENTATION |
·
WHILE LOOP ·
PROGRAM FIVE |
using namespace std; int main() { int x=0; while(
x<=10) { cout<<x; ++x; } } |
#include <iostream> using namespace std; int main() { int x=0;
{ ++x; cout<<x; } while( x<=10); } |
#include <iostream> using namespace std; int main() { int year; for(int
x=3;x>=1;--x) { cout<<"enter current
year"<<endl; cin>>year; if(year==2020) { cout<<"correct"<<endl; break; } else { cout<<"incorrect"<<endl; cout<<"remain
retries="<<x<<endl; } } } |
·
SWITCH CASE ·
USER INPUT ·
PROGRAM EIGHT |
#include <iostream> using namespace std; int main() { char choice; cout<<"choose
character"<<endl; cin>>choice; switch(choice) { case
'a': cout<<"you
input a"; break; Character datatype use single ‘ ’ For string use “
“ cout<<"you
input b"; break; case
'd': cout<<"you
input d"; break; case
'e': cout<<"you
input e"; break; case
'f': cout<<"you
input f"; No break; on default cout<<"no
input"; } } |
#include <iostream>
int main() { char
choose_='udom'; switch(choose_) { case 'cive': cout<<"library"; break; case
'udom': cout<<"lab"; break; case
'humanities': cout<<"cafeteria"; break; default: cout<<"none"; } } |
FUNCTIONS
INTRODUCTION
For Any function to
declare, should follow standards
Return type function
name ()
{
}
Return type often returns the data type
There are two major types of return type
TYPES OF FUNCTIONS
v
Return functions
v
Non return functions
Those are described by keyword “return type”
1. RETURN FUNCTIONS
Is any function that returns value, the syntax is
Return type function
name ()
They should start with the following data types:
Float
Double
Int
String
Char
For example
Float addition () { } |
Returns float data
type Whenever variable
should relate with specified return type |
int addition () { } |
Returns int data
type Whenever declared
variables should relate with specified return type |
char register () { } |
Returns characters
data type Whenever declared
variables should relate with specified return type |
string register () { } |
Returns string data
type Whenever declared
variables should relate with specified return type |
2. NON RETURN FUNCTIONS
Is the type of function that does not return any value,
keyword void is used. Syntax
example:
Void addition() { } |
|
RULES FOR
DECLARING FUNCTIONS
v Does
not start with number. Example void
4c()
v Do
not use keywords. Example void for()
v No
space is allowed. Example void my name ()
STYLES FOR
WRITING FUNCTION NAMES
The name of function can be written in one among of the
following two ways:
v Camelcase
style
v British
style
1. THE CAMELCASE STYLE
Ø The
universal style that states that:
Ø Function
names should start with small letters
Ø But
when joining two words, first word in small and second name start with capital
letter
Examples:
Void myFunction() { } |
Void myFunctionOne() { } |
2. BRITISH STYLE
Declaration of
functions must follow rules otherwise small or capital letter does not matter
Example:
Void
MyfUnCtionoNe() { } |
FUNCTION PARAMETERS AND NON PARAMETERS
As we explain from above, that a function can return a kind
of data type (return function) or not (non return function).
Those types of functions, could be declared with parameters
or non parameters
CATEGORIES OF
FUNCTIONS
v
Passing
parameters
v
Non
Passing parameters
1. PASSING PARAMETER
Parameters are passed during function definition. Syntax is
Void (int x, int z) { Return(x+z); } |
or
Void (int , int ) { Int a,b; Return (a+b); } |
The differences between these two examples is that: when
you declare variable within parameter Void
(int x, int z) you will no need to declare variables within
the function
2. WITHOUT PASSING PARAMETER
No parameter is encountered or no variables are passed
within a parameter. Example
Void number() { } |
Wherever you pass parameters, relies on the following scope
TYPES OF PARAMETERS
v
Passing
by values
v
Passing
by reference
1. PASSING BY VALUES
Passing by values Return(a+b); } OR Void addition (int
, int ) { Int a,b; Return(a+b); } |
2. PASSING BY REFERENCE
Passing by reference when pointers is encountered Return(a+b); } OR Void addition (int
, int ) { Int &a, &b; Return(a+b); } |
GLOBAL AND LOCAL FUNCTION DEFINITION
1. GLOBAL FUNCTION
Accessed wherever within a program, is declared before
main function
#include
<iostream> #include<fstream> Global function void
addition(int a,int b) cout<<(a+b); } int main() { int x=10,z=5; addition(x,z); } |
2. LOCAL FUNCTION
Accessed wherever within a program, is declared before
main function
Local function is declared
within a main function |
EXAMPLE 1 WITHOUT
PASSING PARAMETER:
create a program to
perform addition,sub,mult and div divide
your program into four functions.
Consider
v without
passing parameter
v return
type =void
v
Declare variables v
Initialize values v
output #include<fstream> using namespace std; void addition() { int
a,b,answer; cout<<"enter
first number"<<endl; cin>>a; cout<<"enter
first second number"<<endl; cin>>b; answer=a+b; cout<<answer; //or //cout
(a+b); } void sub() { int
a,b,answer; cout<<"enter
first number"<<endl; cin>>a; cout<<"enter
first second number"<<endl; cin>>b; answer=a-b; cout<<answer; //or //cout
(a-b); } void mult() { int
a,b,answer; cout<<"enter
first number"<<endl; cin>>a; cout<<"enter
first second number"<<endl; cin>>b; answer=a*b; cout<<answer; //or //cout (a*b); } void div() { int
a,b,answer; cout<<"enter
first number"<<endl; cin>>a; cout<<"enter
first second number"<<endl; cin>>b; if(a>b) { answer=a/b; cout<<answer; //or //cout
(a/b); } else { answer=b/a; cout<<answer; //or //cout
(a/b); } } int main() { addition(); sub(); mult(); div(); } |
EXAMPLE 2 WITH
PASSING PARAMETER:
create a program to
perform addition,sub,mult and div divide
your program into four functions.
Consider
v passing
parameter
v return
type =void
when passing
parameter, all variables are declared within a parameter,
no data input is
allowed (CIN)
#include
<iostream> Its not necessary parameter variables to match with
main function variables using
namespace std; //when
passing parameters, cin key word is prohibited //initialization
is prohibited //declaration
is within parameter void
addition(int a, int b) { cout<<(a+b)
; } void
sub(int a, int b) { cout<<(a-b)
; } void
mult(int a, int b) { cout<<(a*b) ; } void
div(int a, int b) { cout<<(a/b) ; } int main() { int a1; int a2; cout<<"enter
first number"<<endl; cin>>a1; cout<<"enter
second number"<<endl; cin>>a2; addition(a1,a2); int b1; int b2; cout<<"enter
first number"<<endl; cin>>b1; cout<<"enter
second number"<<endl; cin>>b2; sub(b1,b2); int c1; int c2; cout<<"enter
first number"<<endl; cin>>c1; cout<<"enter
second number"<<endl; cin>>c2; mult(c1,c2); int d1; int d2; cout<<"enter
first number"<<endl; cin>>d1; cout<<"enter
second number"<<endl; cin>>d2; div(d1,d2); } |
1. RETURN FUNCTION WITHOUT PASSING PARAMETER
Return a value
Can be written either with passing parameter, on non
passing parameter
EXAMPLE 3.
Without passing parameter
Ø Note: do not use VOID void
addition() is example
Ø Do
not use COUT cout<<answer; otherwise you prompt user to enter data
Ø Only
needs: variable declaration and initialization
Ø Int,
float, double, char and string are
return type int addition(); is example
Ø In
main function to call specific function, use
cout<<function_name(); is example
create a program to perform addition, sub, mult and
div divide your program into four
functions. Consider
v Without
passing parameter
v return
type =int
#include
<iostream> #include<fstream> using
namespace std; int
addition() { int a; int b; cout<<"enter first
number"<<endl; cin>>a; cout<<"enter second
number"<<endl; cin>>b; return(a+b); } int sub() { int a; int b; cout<<"enter first
number"<<endl; cin>>a; cout<<"enter second
number"<<endl; cin>>b; return(a-b); } int mult() { int a; int b; cout<<"enter first
number"<<endl; cin>>a; cout<<"enter second
number"<<endl; cin>>b; return(a*b); } int div() { int a; int b; cout<<"enter first
number"<<endl; cin>>a; cout<<"enter second
number"<<endl; cin>>b; return(a/b); } int main() { cout<<addition(); cout<<sub(); cout<<mult(); cout<<div(); } |
2. RETURN FUNCTION WITH PARAMETER
#include
<iostream> #include<fstream> using
namespace std; { cout<<(a+b); } int sub(int
a , int b) { RETURN TYPE
WITH PARAMETER } int
mult(int a , int b) { cout<<(a*b); } int div(int
a , int b) { cout<<(a/b); } int main() { int a1,a2; cin>>a1; Call the fuction with variables to match the parameter cin>>a2; addition(a1,a2); int b1,b2; cout<<"enter first
no"<<endl; cin>>b1; cout<<"enter first
no"<<endl; cin>>b2; sub(b1,b2); int c1,c2; cout<<"enter first
no"<<endl; cin>>c1; cout<<"enter first
no"<<endl; cin>>c2; mult(c1,c2); int d1,d2; cout<<"enter first
no"<<endl; cin>>d1; cout<<"enter first
no"<<endl; cin>>d2; div(d1,b2); return 0; } |
POINTER
REFERENCE PROGRAM
#include<iostream> //also &
can be used to get memory address of a stored variable //reference
name mji to refer to the dodoma variable: int main() { string dodoma ="makulu"; string &mji= dodoma; cout<<dodoma; cout<< &mji; } |
VARIABLE ADDRESS
#include<iostream> using namespace std; int main() { //also &
can be used to get memory address of a stored variable //when variable
is created memory address stored to that variable //and when
assigning value to variable its also stored in this address string &mji= dodoma; cout<<dodoma; cout<<mji; } |
MODIFYING POINTER
#include <iostream> using namespace std; int main() { string
food="ugali"; string* ptr= &food; cout<< food; //results normal
variable"ugali" cout<< &food; //result memory address cout<< ptr; //result the memory address of
variable food *ptr="wali"; //change the value from
variable food to be wali cout<< *ptr; //shows the changed variable |
SINGLE DIMENSION ARRAY
ARRAY/ CALENDER
// A C++ Program to Implement a Calendar // of an year #include<bits/stdc++.h> using namespace std; /*A Function that returns the index of the day of the date- day/month/year For e.g- Index Day 0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday*/ int dayNumber(int day, int month, int year) { static int t[] = { 0, 3, 2,
5, 0, 3, 5, 1, 4, 6, 2,
4 }; year -= month < 3; return ( year + year/4 -
year/100 + year/400 +
t[month-1] + day) % 7; } /* A Function that returns the
name of the month with a given month number Month Number Name 0 January 1 February 2 March 3 April 4 May 5 June 6 July 7 August 8 September 9 October 10 November 11 December */ string getMonthName(int monthNumber) { string months[] =
{"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" }; return
(months[monthNumber]); } /* A Function to return the number of days in a month Month Number Name Number of Days 0 January 31 1 February 28 (non-leap) / 29 (leap) 2 March 31 3 April 30 4 May 31 5 June 30 6 July 31 7 August 31 8 September 30 9 October 31 10 November 30 11 December 31 */ int numberOfDays (int monthNumber, int year) { // January if (monthNumber == 0) return (31); // February if (monthNumber == 1) { // If the year is leap
then February has // 29 days if (year % 400 == 0 || (year % 4 == 0
&& year % 100 != 0)) return (29); else return (28); } // March if (monthNumber == 2) return (31); // April if (monthNumber == 3) return (30); // May if (monthNumber == 4) return (31); // June if (monthNumber == 5) return (30); // July if (monthNumber == 6) return (31); // August if (monthNumber == 7) return (31); // September if (monthNumber == 8) return (30); // October if (monthNumber == 9) return (31); // November if (monthNumber == 10) return (30); // December if (monthNumber == 11) return (31); } // Function to print the calendar of the given year void printCalendar(int year) { printf (" Calendar - %d\n\n", year); int days; // Index of the day from 0
to 6 int current = dayNumber (1,
1, year); // i --> Iterate through
all the months // j --> Iterate through
all the days of the // month - i for (int i = 0; i < 12;
i++) { days = numberOfDays (i,
year); // Print the current
month name printf("\n ------------%s-------------\n", getMonthName
(i).c_str()); // Print the columns printf(" Sun
Mon Tue Wed
Thu Fri Sat\n"); // Print appropriate
spaces int k; for (k = 0; k <
current; k++) printf(" "); for (int j = 1; j <=
days; j++) {
printf("%5d", j); if (++k > 6) { k = 0;
printf("\n"); } } if (k)
printf("\n"); current = k; } return; } // Driver Program to check above funtions int main() { int year = 2016; printCalendar(year); return (0); } |
CONDITIONAL STATEMENTS VS
SWITCH CASE
WHILE LOOP/ AGE DETERMINATION
#include <iostream> using namespace std; int main() { int attempt=0; do{ int years;int
age; cout<<"ingiza mwaka wa kuzaliwa"; //suppose is 1990 cin>>years; cout<<"ingiza umri wa sasa"; //suppose 30 cin>>age; //calculate 2020-1990 is answer 30 ?? if(2020-years==age) { cout<<"mwaka wa kuzaliwa
na umri ni sawa"; //if true stop here break; } //if false continue here else { cout<<"umri
na mwaka wa kuzaliwa haviendani"; //repeat
until birthyear and age matches attempt
++; cout<<"umejaribu
mara ya="<<attempt; } } //excute here condition while(attempt<3); //but if
number of tries limit is 3, then do this.... if(attempt=3) { //continue; cout<<"umefikia
ukomo kujaribu mara 3"; } } |
NESTED IF INSIDE BOTH IF AND ELSE
#include<iostream> using namespace std; int main() { int x=3; int y=4; int z=12; int ans; if (x>=y) { if
(x==y) { ans=x+y; cout<<ans; } else { cout<<"not
equal to y"<<endl; } } else { if(x<=y) { ans=x*y; cout<<ans<<endl; } else { cout<<"x
is not less than or equal to y"<<endl; } } } |
NESTED IF INSIDE ELSE BLOCK
#include<iostream> using namespace std; int main() { int x=10; int y=20; int z; if (x>y) { z=x+y; cout<<z; } else { if(x<y) { cout<<"x<y"; } else { cout<<"not
true"; } } } |
NESTED IF STATEMENT INSIDE IF
#include<iostream> using namespace std; int main() { float results; int x=14; int y=20; int z=12; if (x<=y) { if (x>z) { results=x*y; cout<<results; } else results=x/y; cout<<results; } else results=x*y/z; cout<<results; } |
IF INSIDE IF GRADING SYSTEM PROGRAM
//if statement inside if #include <iostream> using namespace std; int main () { int
sumMark,avMark,markGrade,subject1,subject2,subject3,subject4; string
studentLevel; cout<<"what
is the level of student?"<<endl; cin>>studentLevel; if
(studentLevel=="formsix"||studentLevel=="FORMSIX") { cout<<"welcome
to grading system enter marks for student"<<endl; cout<<"enter
GS marks"<<endl; cin>>subject1; cout<<"enter
chemistry marks"<<endl; cin>>subject2; cout<<"enter
physics marks"<<endl; cin>>subject3; cout<<"enter
mathematics marks"<<endl; cin>>subject4; cout<<"total
marks="; sumMark=subject1+subject2+subject3+subject4; cout<<sumMark<<endl; cout<<"avarage
marks="; avMark=sumMark/4; cout<<avMark<<endl; markGrade=avMark; cout<<"grade
is"; if
(markGrade>=0 &&markGrade<=20) { cout<<"F"; } else if
(markGrade>=21 &&markGrade<=29) { cout<<"E"; } else if
(markGrade>=30 && markGrade<=44) { cout<<"D"; } else if
(markGrade>=45 && markGrade<=60) { cout<<"c"; } else if
(markGrade>=61 && markGrade<=74) { cout<<"B"; } else if
(markGrade>=75 && markGrade<=100) { cout<<"A"; } else { cout<<"no
exam have been done"; } } else { cout<<"only
for form six"; } } |
SWITCH CASE INSIDE
SWITCH
#include <iostream> using namespace std; int main () { int password=10; int id=2020; switch
(password) { case
10: switch
(id) { case
2020: cout
<<"correctly"; break; } } default: cout<<"either
one incorrect"; } |
FILE HANDLING
FILE HANDILING CREATE FILE MANUAL
#include<iostream> #include <fstream> using namespace std; int main() { ifstream infile; infile.open("data.txt"); int x; int y; int z; infile>>x>>y>>z; cout
<<"your x data is"<<x<<endl<<"your y
data is"<<y; } |
CREATE FILE MANUAL 2 DISPLAY NAMES
#include <iostream> #include <fstream> #include<string> using namespace std; int main() { ifstream
majinayangu; majinayangu.open("mynames.txt"); //check if file "mynames" exist if
(majinayangu.fail()) { cerr<<"no
such file!!!!!!"; exit(1); } //end file check string
firstname,middlename,lastname; majinayangu>>firstname; majinayangu>>middlename; majinayangu>>lastname; cout<<"your
names
are"<<firstname<<endl<<middlename<<lastname; majinayangu.close(); } |
CREATE FILE
MANUAL ARRAY AND FUNCTION
//physical file named "data" value=2 #include <iostream> #include <fstream> #include<string> using namespace std; int jumlisha() { ifstream ongeza; ongeza.open("data.txt"); //check if file
exit if(ongeza.fail()) { cerr<<"no
such file"; exit(1); } int x; ongeza>>x; for ( x; x <=
5; x++) { cout<<x; } } int main() { int jumlisha(); jumlisha(); } |
CREATE FILE MANUAL WHILE LOOP
#include<iostream> #include<fstream> #include<string> using namespace std; int main() { string majina; int count=0; //read until you have reached the end ifstream mikoa; mikoa.open("data.txt"); while (!mikoa.eof()) { mikoa>>majina; count++; cout<<count<<"your
instances are"<<endl; } } |
CREATE FILE
USER INPUT AND OUTPUT
#include<iostream> #include<fstream> #include<iostream> using namespace std; int a,b,c; int data1 () { ofstream data1; cout<<"input
two numbers"<<endl<<endl; cin>>a; cin>>b; data1.open("data.txt"); data1<<a<<b; cout<<"first_data
is"<<a<<endl; data1.close(); } int data2() { ifstream demo; demo.open("data.txt"); demo>>a>>b; cout<<"second_data
is"<<b<<endl; } int main() { data1(); data2(); } |
CREATE FILE CREATE ACCOUNT AND LOGIN
#include<iostream> #include<fstream> #include<iostream> using namespace std; int a,b,c; int data1 () { ofstream data1; cout<<"input
two numbers"<<endl<<endl; cin>>a; cin>>b; data1.open("data.txt"); data1<<a<<b; cout<<"first_data
is"<<a<<endl; data1.close(); } int data2() { ifstream demo; demo.open("data.txt"); demo>>a>>b; cout<<"second_data
is"<<b<<endl; } int main() { data1(); data2(); } |
SOLVING QUESTIONS
QUESTION
ONE.
(A)
Algorithm to display employee birth
year, retirement time and how many days remain. Imagine 55 years are minimal
retirement guarantee.
The operation is, the user enters current age, then
the age will be taken into considerations using arithmetic operations to calculate when he/she was born, how many
years left to retire and when retirement will begin
Step
1: start
Step
2 : enter your age say AGE
Step
3: RETIRE=55
Step
4: BIRTHYEAR = 2020-AGE
Step
5: REMAINYEARS= RETIRE-AGE
Step
6: YEAR_TO_RETIRE =2020+AGE
Step
7: display “your birth year is” BIRTHYEAR
Step
8: display “it remains to retire”
YEAR_TO_RETIRE
Step
9: display “you will retire” YEAR TO RETIRE
Step
10: Stop.
---------------------------------------*******----------------------------------------------
(B). The flow
chart illustrates how the problem is solved
stop
start Enter age Retire =55 Birth year= 2020 - age Remain years=retire - age Year to retire =2020
+ age Print Birth year Print Remain years Print Year to retire
QUESTION
TWO:
(A). The following algorithm compare username and password whether they
meet with stored information, if both are correct, then will display “correct “
otherwise one of them is incorrect (the LOGICAL AND) is used for logical
comparison
Step
1:
enter username and password say
USERNAME,PASSWORD
Step
2:
USERNAME = CIVE, PASSWORD = 2020
Step
3:
if USERNAME ==CIVE and PASSWORD==2020 then
Print correct details
Else
Print either username or password mismatch
End if
start
Enter username and password Username= CIVE Password = 2020 if username== CIVE and
password= =2020 Correct details incorrect details stop true false B. The flow chart illustrates how
the problem is solved
QUESTION
3
start
Enter marks If marks >=90 Print A If marks >=80 Print B If marks >=70 Print C If marks >=50 Print D Print F yes no yes no yes no yes else stop
---------------------------------------*******----------------------------------------------
(B). Algorithm
illustrates how the problem is solved
Step
1: start
Step
2: enter your marks say MARKS
Step
3: if MARKS >=90 then
Print A
else if MARKS >=80 then
Print B
else if MARKS >=70 then
Print C
else if MARKS >=50 then
Print D
Else
Print F
End if
Step
4: stop
QUESTION 4
(A). Create algorithm to display numbers form 0 to
100 using looping repetition (for loop)
Step
1:
start
Step
2:
character i=0
Step
3:
for i < = 100
Display i
The flow chart illustrates how the
problem is solved
Step
4: i++
Step
5: stop
start i=0 Print i i ++ For i < = 100 stop false true
QUESTION
5
(B). Create algorithm to display numbers form 0 to
100 using looping repetition (while
loop)
Step
1: start
Step
2: character i=0
Step 3:
do
print i
i++
Step
5: while
i<=100
Step
6: end loop
Step
7: stop
---------------------------------------*******----------------------------------------------
The flow chart illustrates how the problem is solved
start i=0 Read i Print i i++ i<=100 stop False True ?
RAM DIAGRAM VS
PHYSICAL MODEL
Simple program adding
integer numbers by function
#include <iostream>
using namespace std;
int addition(int namba1,int namba2)
{
int result=namba1+namba2;
return result;
}
int main()
{
int
value1,value2;
cin>>value1>>value2;
cout
<<addition (value1,value2);
return
0;
}
(A)
RAM DIAGRAM ILLUSTRATION
RESERVED |
RESERVED |
FREE |
FREE |
3 |
2 |
5 |
3 |
2 |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
FREE |
Value2 Value1 results Namba2 Value22 results Namba2 Namba1 Value1 Namba1
(B)
PHYSICAL MODEL
(i)
Memory
status before variable declaration:
(ii)
Variable
reservation
Value 2 Namba1 Namba2 result Value1
(iii)
Data
feeding
Value 2 Namba1 Namba2 result Value1
(iv)
Data
processing
Value 2 Namba1 Namba2 result Value1
ARRAY
FILE HANDLING
FUNCTIONS
LOOP
RAM
DIAGRAMS
#include <iostream> #include <string> #include <fstream> using namespace std; //array in global declaration int arraymoja [7]; int numbermoja=0; //file handle function to store data
in array int filehandling() { ofstream myfile; myfile.open("myfile.html"); cout<<"enter number for
loop"; while(numbermoja<=6)
{
cin>>arraymoja[numbermoja];
myfile<<arraymoja[numbermoja]; numbermoja++; } } //function to display greating string salamu() { string
greating="hellow"; cout<<greating; } int main() { int filehandling(); filehandling(); string salamu(); salamu(); } |
VARIABLE /ARRAY RESERVATION
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
ARRAYMOJA NUMBERMOJA
DATA FEEDING
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
0 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 8 WILL BE
STORED IN INDEX 0
8 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
1 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 44 WILL BE
STORED IN INDEX 1
8 |
44 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
2 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 50 WILL BE
STORED IN INDEX 2
8 |
44 |
50 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
3 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 100 WILL BE
STORED IN INDEX 3
8 |
44 |
50 |
100 |
RESERVED |
RESERVED |
RESERVED |
4 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 22 WILL BE
STORED IN INDEX 4
8 |
44 |
50 |
100 |
22 |
RESERVED |
RESERVED |
5 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 26 WILL BE
STORED IN INDEX 5
8 |
44 |
50 |
100 |
22 |
26 |
RESERVED |
6 |
ARRAYMOJA NUMBERMOJA
SUPPOSE USER ENTER 9 WILL BE
STORED IN INDEX 6
8 |
44 |
50 |
100 |
22 |
26 |
9 |
7 |
ARRAYMOJA COMPLETE MODEL NUMBERMOJA
|
44 |
50 |
100 |
22 |
26 |
|
|
HELLOW |
ARRAYMOJA GREETING NUMBERMOJA
//simple program for adding three integers #include <iostream> using namespace std; int main() { int udom, ud,
mou; cin>>ud
>>mou; udom=ud+mou; cout<<udom
<<endl; return 0; } |
v RAM DIAGRAM ILLUSTRATION
RESERVED |
2 |
4 |
FREE |
6 |
2 |
4 |
FREE |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
FREE |
UDOM MOU UD UDOM MOU UD MOU UD UDOM
v PHYSICAL MODEL ILLUSTRATION
Memory status before variable declaration:
Memory status after variable
declaration/ labeling
Three spaces
are reserved for variable UDOM, UD, MOU
MOU UD UDOM
Memory status after data feeding/ data
input
MOU UD UDOM
Memory status after data processing
MOU UD UDOM
v A SIMPLE PROGRAM FOR INTEGERS SUBTRACTION
#include
<iostream> using namespace std; int main() { int num1, num2, output; cin>>num1 >>num2; output=num1-num2; cout<<output<<endl; return 0; } |
v RAM DIAGRAM ILLUSTRATION
2 |
RESERVED |
4 |
FREE |
2 |
-2 |
4 |
FREE |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
FREE |
OUTPUT NUM2 OUTPUT NUM2 OUTPUT NUM1 NUM2 NUM1 NUM1
v PHYSICAL MODEL ILLUSTRATION
Memory status before variable declaration:
Memory status after variable
declaration/ labeling
Three spaces
are reserved for variable NUM1, NUM2, OUTPUT
NUM1 OUTPUT NUM2
Memory status after data feeding/ data
input
NUM2 NUM1 OUTPUT
Memory status after data processing
NUM1 NUM2 OUTPUT
v A SIMPLE PROGRAM TO CALCULATE THE AREA OF RECTANGLE:
#include
<iostream> using namespace std; int main() { int area, lenght, width; lenght=14; width=6; area= lenght*width; cout <<lenght <<
"cm"; } |
v RAM DIAGRAM ILLUSTRATION
RESERVED |
14 |
6 |
FREE |
42 |
14 |
6 |
FREE |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
FREE |
AREA WIDTH LENGHT LENGHT AREA WIDTH AREA WIDTH LENGHT
PHYSICAL MODEL ILLUSTRATION
Memory status before variable declaration:
Memory status after variable
declaration/ labeling
Three spaces
are reserved for variable NUM1, NUM2, OUTPUT
AREA LENGHT WIDTH
Memory status after data feeding/ data
input
WIDTH AREA LENGHT
OUTPUT NUM2 NUM1
v A SIMPLE PROGRAM THAT FINDS THE AREA OF TRIANGLE WHERE BASE=16, HEIGHT=14
#include
<iostream> using namespace std; int main() { float A, height, base; height=14; base=16; A= 0.5*height*base; cout <<A <<
"cm"; } |
v RAM DIAGRAM ILLUSTRATION
RESERVED |
14 |
16 |
FREE |
112 |
14 |
16 |
FREE |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
FREE |
HEIGHT A BASE A BASE HEIGHT A BASE HEIGHT
v PHYSICAL MODEL ILLUSTRATION
Memory status before variable declaration:
Memory status after variable
declaration/ labeling
HEIGHT BASE A
Memory status after data feeding/ data
input
HEIGHT BASE A
Memory status after data processing
A BASE HEIGHT
v A SIMPLE CALCULATOR PROGRAM
#include
<iostream> using namespace std; int main() { float num1, num2,answer; string opareta; cout<<"choose
operator e.g +or -or /or X"<<endl; cin>> opareta; cout<<"enter two operands"<<endl; cin>>num1; cin>>num2; if (opareta=="+") { answer=num1+num2; cout<<answer; } else if
(opareta=="-") { answer=num1-num2; cout<<answer; } else if
(opareta=="*") { answer=num1*num2; cout<<answer; } else if (opareta=="/") { cout<<"note:
numerator should be greater than denominator"<<endl; answer=num1/num2; cout<<answer; } else { cout
<<"invalid input"; } } |
v CODE MODIFICATION USING SWITCH STATEMENT OF THE ABOVE CALCULATOR PROGRAM
# include
<iostream> using namespace std; int main() { char x; float num1, num2,answer; cout << "Enter operator either
+ or - or * or /: "<<endl; cin >> x; cout << "Enter two
operands:"<<endl; cin >> num1 >> num2; switch(x) { case '+': answer=num1+num2; cout << answer; break; case '-': answer= num1-num2; cout <<answer; break; case '*': answer=num1*num2; cout <<answer; break; case '/': answer=num1/num2; cout << answer; break; default: cout << "Error!
operator is not correct"; break; } return 0; } |
RAM DIAGRAM to illustrate switch case
calculator program from above
When “+” operator is choosen
+ |
RESERVED |
RESERVED |
RESERVED |
+ |
2 |
4 |
6 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
answer Num2 answer Num2 Num1 x answer x Num1 x Num2 Num1
When “-” operator is choosen
- |
RESERVED |
RESERVED |
RESERVED |
- |
2 |
4 |
-2 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
answer Num2 answer Num2 Num1 x answer x Num1 x Num2 Num1
When “*” operator is choosen
* |
RESERVED |
RESERVED |
RESERVED |
* |
2 |
4 |
8 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
answer Num2 answer Num2 Num1 x answer x Num1 x Num2 Num1
When “/” operator is choosen
/ |
RESERVED |
RESERVED |
RESERVED |
/ |
4 |
2 |
2 |
RESERVED |
RESERVED |
RESERVED |
RESERVED |
FREE |
FREE |
FREE |
FREE |
answer Num2 answer Num2 Num1 x answer x Num1 x Num2 Num1
v THE PHYSICAL MODEL ILLUSTRATING ABOVE SWITCH CASE PROGRAM
Memory status before variable declaration:
Memory status after variable
declaration/ labeling
ANSWER x NUM2 NUM1
Memory status after data feeding/ data
input
X NUM2 NUM1
Memory status after data processing
+ ANSWER X NUM2 NUM1
Memory status after data processing
NUM1 NUM2 + ANSWER X
The same to
other operators /,-,and *
v
FOR LOOP PROGRAM TO COUNT 2010 UNTIL
2020
#
include <iostream> using
namespace std; int
main() { for(int year=2010;
year<=2020;year++) cout <<year<<endl; } |
v PHYSICAL MODEL DO ILLUSTRATE ABOVE LOOP
Memory status after variable
declaration/ labeling and data initialization
count count count
count count
v PHYSICAL MODEL DO ILLUSTRATE ABOVE LOOP
1 |
FREE |
FREE |
FREE |
2 |
FREE |
FREE |
FREE |
3 |
FREE |
FREE |
FREE |
count count count
4 |
FREE |
FREE |
FREE |
5 |
FREE |
FREE |
FREE |
count count
v DO WHILE PROGRAM
# include
<iostream> using namespace std; int main() { int count=1; do { cout<<count<<endl; count++; } while(count<=5); } |
v PHYSICAL MODEL FROM ABOVE LOOP
count count count count
count count
v PHYSICAL MODEL DO ILLUSTRATE ABOVE LOOP
FREE |
FREE |
FREE |
FREE |
1 |
FREE |
FREE |
FREE |
2 |
FREE |
FREE |
FREE |
count count count
3 |
FREE |
FREE |
FREE |
4 |
FREE |
FREE |
FREE |
5 |
FREE |
FREE |
FREE |
count count count
Sms: 0746 850755
@2020
Dodoma Tanzania
No comments:
Post a Comment