Introduction To Programming Tutorials
Introduction To Programming Tutorials
*********************************************************************
Basic Concepts of Programming
Program
Programming languages
Programmer
Software
Computer vs Human beings
Definitions:
or
The process of developing a program generally invloves six stages which are
referred
to as the program development life cycle and shown below:
1.Requirements specification:
-States the purpose/function of the program.
-Understand the problem or task: A program to compute the area of a rectangle
-It invloves the defination of inputs,
transformation, outputs and treatment of exceptional situations.
2.Program design:
This is where the programmer identifies the processing tasks required and the
precise
order in which they are to be carried out,that is the algorithm from which the
computer
program will be produced. The design process takes little or no account of the
programming
language to be used.
5.Documentation:
Having written and debugged the program. It must be documented. There are two main
types of
documentation.
a)User Guide: These are guides that are intended to help the user to use/operate
the program
with minimal or no guidance
b)Technical manuals: These are intended for the system analysts/programmers to
enable
maintenance and modification of the program design and code.
6.Implementation/Operation:
At this stage, the system designers will actually install the new system, create
data files
and train people to use the new system. A common practice is to run the new system
in
parallel with the old system to ensure that if something goes wrong, the business
doesn't
come to a grinding halt.
After a number of parallel runs,the old system will be abandoned and the new system
will
be fully be operational. At this point the system goes into the final stage off
monitoring
and review (or evaluation) where the performance of the system is evaluated with
reference to
the initial requirements.
1. ACCURACY
The program must do what it was supposed to do. The results/output should be
correct as per
specicificatins.
2.RELIABLITY
The program must always do what it was supposed to do and never crash.
3.ROBUSTNESS
The program should cope with invalid data without creating errors or stopping
without stopping
without indication of the cause.
4.USABILITY
To make sure that your program is easy to use,make sure that the flow of your
program is
logical
and provide a proper user guide/manual.
5.READABILTY
To make your code more readable, use the following rules/guidlines
a)Use Meaningful names: When coming up with the names for variables or constants,
use names that hint what the variable or constant holds e.g balance,tax,tax_rate,
etc
instead of using letters like a,b,c.
b)Use Comments: Use comments at the module level to explain the purpose of the
module
and within the code to explain complicated algorithms or highlight error prone
sections.
float length,width,area; //Declaration of variables
float length;
float width;
float area;
/* rhrhhhrjr ffjfjf
ddldldl fflflflf
kdlll fl;g;g;g;g */
c)Use Indentation: Lay your code neatly and make proper use of indentation to
reflect the logic
structure of the code.
#include<stdio.h>
main()
{
float length,width,area;
length=42.345;
width=31.344;
area=length*width;
length=42.345;
width=31.344;
area=length*width;
}
6.SIMPLICITY
The clarity and accuracy of a program are usually enhanced by keeping things
simple.
7.EFFICIENCY
Efficiency is concerned with execution speed and efficient memory utilization.
8.GENERALITY
Generality. A program should be as general as possible, within reasonable limits.
We may design a program to read in the values of certain key parameters rather that
placing
fixed values into the program.
#include<stdio.h>
#include<math.h>
main()
{
float number;
float answer;//This is the declaration of variables
ERROR: Is something that will make the program not to run or give erronious result.
TYPES OF ERRORS:
a)SYNTAX ERRORS - Are caused when you violate the rules of a programming language.
Causes
i)Missing semicolon to terminate a statement
ii)Mispelled reserved word
iii)A reserved word consisting of a capital letter.
iv) { without corresponding } or ( without corresponding )
v) " without corresponding "
vi)Use of wrong expressions float x; area=l*w; Error: l*w=area;
vii)Use of undeclared identifiers
viii)Failure to include the appropriate header file.
float x,y,z;
a=23;
Causes
i)Division by zero
ii)Computing the square root of a negative number
iii)Endless loops
i)Wrong formula
ii)Failure to initialize variables
iii)Testing wrong conditions in loops
data_type identifier;
int x;
int height=2;
d)LINKING ERROR
The computer is not able to get the intermidiate programs required
by the program.
1.DESK CHECKING:
After writing the program, the programmer goes through the program on paper to
pick up any error that would cause extra work at a later stage
After keying in the program,it is checked using the translator to detect any syntax
errors. The programmer corrects the errors and re-submits the programs until an
error
free listing is obtained.
As part of the "Acceptance Trials" new programs are usually run in parallel with
the existing
system for a short while so that results can be comapred and adjustments made. The
system
run using actual data.
solution:
#include<stdio.h>
main()
{
float num1,num2,sum;
sum=num1+num2;
printf("%f\n",sum);
printf("The answer = %f\n",sum);
printf("The sum of %f and %f is %f\n",num1,num2,result);
printf("%f is the sum of %f and %f\n",result,num1,num2);
There are various techniques that are usually recommended to be used by the
programmer when coding
a program to ensure that the program produced are of good quality. They include the
following:
i)Documentation lines:
Are lines to explain what the instructions of a program are doing.They help one
to be able to read
and understand the program. They also make the program easy to write and modify
because another
programmer can understand the code easier. They are also known as comment lines.
There are two types:
ii)Line spacing
Leaving empty lines between sections of codes so as to visibly distinguish among
the individual
sections.
#include<iostream>
#include<math.h>
using namespace std;
main()
{
float number,result;
result=sqrt(number);
70-100 A
60-69 B
50-59 C
40-49 D
0-39 E
int mk1,mk2,mk3,mk4,total,avg;
char grade, regNumber[20], studentName[40];
mk1=45
mk2=50
mk3=78
mk4=56
total=mk1+mk2+mk3+mk4
avg=total/4
Syntax:
data_type identifier;
65.999
-char
volume=PI*r*r*h
data_type identifier;
int x;
float basic_salary;
float basicsalary;
int customer_account_number;
int customeraccountnumber;
int customerAccountNumber;
float basic_salary;
float num1,_num2;
clb 102
Clb 102
conventions
1.Identifiers should be short.
2.Identifiers should be descriptive and meaningful.
3.Variables should be in small letters.
4.Constant variables should be written in capital.
int x;
x=23;
x=90;
x=78;
Syntax:
vol=PI*3*3*5
Format of a C program
#include<stdio.h>//preprocessor directive
#include<math.h>//mathematical functions
#include<string.h>//Manipulating characters
#define PI 3.14
main()
{
wee jjjj
#include<stdio.h>
#include<math.h>
main()
{
float principle,amount,rate;
int t,n;
principle=1500.00;
rate=0.043;
t=6;
n=4;
amount=principle*pow(1+rate/n,n*t);
pow(x,y);
dddddd ggggggggg gggg
#include<stdio.h>
main()
{
float num1,num2,sum;
scanf("%f",&num1);
scanf("%f",&num2);
sum=num1+num2;
printf("%f",sum);
#include<stdio.h>
main()
{
float num1,num2,sum;
scanf("%f",&num1);
scanf("%f",&num2);
sum=num1+num2;
printf("%f",sum);
#include<stdio.h>
main()
{
char x;
x=getchar();
putchar(x);
#include<stdio.h>
main()
{
char x[40];
input - scanf(),gets()
output - printf(),puts()
Format of a C program
}
printf()
scanf()
Example 1:
#include <stdio.h>
main()
{
printf("Programming in C is easy.");
printf("I will try to pass.\n");
}
CodeBlocks
Example 2: A program that adds 23 and 45
#include <stdio.h>
main()
{
int num1;
int num2;
int result;
num1=23;
num2=45;
result=num1+num2;
printf("%d\n",result);
printf("The sum is %d\n",result);
#include <stdio.h>
main()
{
int num1;
int num2;
int result;
result=num1+num2;
printf("%d\n",result);
printf("The sum is %d\n",result);
#include <stdio.h>
main()
{
int marks;
if(marks>=50)
else
The answer is 68
%d or %i - int
%f or %lf - float
%e or %Lf - double
%c - char
%s string
num1=23;
num2=45;
result=num1+num2;
scanf("%d",&num1);
#include <stdio.h>
main()
{
int num1,num2,result;
result=num1+num2;
#include <stdio.h>
int num1,num2;
float result;
main()
{
int num1,num2;
float result;
result=num1/num2;
printf("The quotient of %d and %d is %f\n",num1,num2,result);
}
data_type identifier;
int x;
char x;
Array of characters
data_type identifier[SIZE];
char x[50];
JKC-B08-0001-2015
Problem:
#include<stdio.h>
main()
{
int mathematics,english,physics,geography,total_score,average_marks;
char name[50],regNumber[20];
total_score=mathematics+english+physics+geography;
average_marks=total_score/4;
printf("English: %d\n",english);
printf("Mathematics: %d\n",mathematics);
printf("Physics: %d\n",physics);
printf("Geography: %d\n",geography);
printf("Total Score: %d\n",total_score);
}
Example 2:
Suppose a, b and c are integer variables assigned the value a =8, b=3 and c= 5.
Write a program to determine the value for the expression: a*(c%b)+c.
Clearly show your work.
#include<stdio.h>
main()
{
int a,b,c,answer;
a =8;
b=3;
c= 5;
answer=a*(c%b)+c;
#include<stdio.h>
#include<math.h>
main()
{
float monthly_payment,p,rate,amount;
int n;
p=100000.00;
rate=0.05/12;
n=180;
monthly_payment=p*(((rate*pow(1+rate,n)))/(pow(1+rate,n)-1));
#include<stdio.h>
#include<math.h>
main()
{
float monthly_payment,p,rate,amount,r;
int n,t;
rate=(r/100)/12;
n=t*12;
monthly_payment=p*(((rate*pow(1+rate,n)))/(pow(1+rate,n)-1));
#include<stdio.h>
#include<math.h>
main()
{
float num1,num2,sum;
num1=25.36;
num2=34.56;
sum=num1+num2;
printf("%.2f \n",sum);
printf("The sum is %.2f\n",sum);
printf("The sum of %.2f and %.2f is %.2f\n",num1,num2,sum);
printf("%.2f is the sum of %.2f and %.2f\n",sum,num1,num2);
}
#include <stdio.h>
main()
{
float num1,num2,result;
result=num1+num2;
#include<stdio.h>
main()
{
float num1,num2,sum;
sum=num1+num2;
printf("%.2f \n",sum);
printf("The sum is %.2f\n",sum);
printf("The sum of %.2f and %.2f is %.2f\n",num1,num2,sum);
printf("%.2f is the sum of %.2f and %.2f\n",sum,num1,num2);
}
#include<stdio.h>
#include<math.h>
main()
{
float monthly_payment,p,rate,amount,r;
int n,t;
rate=(r/100)/12;
n=t*12;
monthly_payment=p*(((rate*pow(1+rate,n)))/(pow(1+rate,n)-1));
#include <stdio.h>
main()
{
float height,radius,volume;
#include<stdio.h>
main()
{
int num1,num2,add,sub,div,mult;
add=num1+num2;
sub=num1-num2;
mult=num1*num2;
div=num1/num2;
printf("SUM = %d\n",add);
printf("DIFFERENCE = %d\n",sub);
printf("PRODUCT = %d\n",mult);
printf("QUOTIENT = %d\n",div);
return 0;
}
#include<stdio.h>
main()
{
char name;
char letter;
name='A';
#include<stdio.h>
main()
{
char name;
name='A';
printf("The character is %c\n",name);
return 0;
}
#include<stdio.h>
main()
{
char name[50];
puts(name);
return 0;
}
int x;
char x;
char name;
float y;
Array of character
-------------------
syntax:
datatype identifier[SIZE];
int x[10];
char name[40];
#include<stdio.h>
main()
{
char name[40];
sqrt(x);
cos(x);
tan(x);
#include<stdio.h>
#include<math.h>
main()
{
float number, answer;
printf("Enter any number: ");
scanf("%f",&number);
answer=sqrt(number);
pow(x,y)
#include<stdio.h>
#include<math.h>
main()
{
float num1,num2, answer;
printf("Enter base: ");
scanf("%f",&num1);
answer=pow(num1,num2);
Example:
An amount of $1,500.00 is deposited in a bank
paying an annual interest rate of 4.3%,
compounded quarterly. What is the balance after
6 years?
#include<stdio.h>
#include<math.h>
main()
{
float prin,rate,total_amount;
int t,n;
prin=1500;
rate=0.043,
n=4;
t=6;
total_amount=(prin*pow(1+rate/n,n*t));
printf("The balance after 6 years = Kshs. %f\n",total_amount);
return 0;
}
The first credit card that you got charges 12.49 % interest to its customers and
compounds that interest monthly. Within one day of getting your first credit card,
you max out the credit limit by spending $1,200.00 . If you do not buy anything
else on the card and you do not make any payments, how much money would you owe the
company after 6 months?
#include<stdio.h>
#include<math.h>
main()
{
float prin,rate,total_amount,t;
int n;
prin=1200;
rate=0.1249,
n=12;
t=0.5;
total_amount=(prin*pow(1+rate/n,n*t));
return 0;
}
#include<stdio.h>
#include<math.h>
main()
{
float prin,n,rate,total_amount;//declaration of variable
total_amount = prin*(pow(1+rate/100,n));
return 0;
}
p(1+r/100)^n = a
x^y
pow(base,power);
pow(1+r/100,n)
x=-b+ or -
#inlcude<stdio.h>
#include<math.h>
main()
{
int a,b,c,x1,x2;
printf("Enter the value of a: ");
scanf("%d",&a);
if((b*b-4*a*c)>=0)
{
x1=(-b+sqrt(b*b-4*a*c))/2*a;
x2=(-b-sqrt(b*b-4*a*c))/2*a;
printf("x1 = %d\n",x1);
printf("x2 = %d\n",x2);
}
else
{
printf("No possible roots");
}
}
#include<stdio.h>
main()
{
float basic_salary,tax,h_allow, t_allow, gross_income,
net_salary;
h_allow=20.0/100.0*basic_salary;
t_allow=15.0/100.0*basic_salary;
tax=20.0/100*gross_income;
net_salary = gross_income- tax;
return 0;
}
Assignment one
Question I:
[5 marks]
Question II:
i)The sum of 5.0 and 3 is 8.00 printf("The sum of %.1f and %.0f is
%.2f\n",a,b,sum);
ii)8.0 is the sum of 5.00 and 3.000 printf("%.1f is the sum of and %.2f and
%.3f\n",sum,a,b,);
[5 marks]
QUESTION III
The first credit card that you got charges 12.49 % interest to its customers and
compounds that interest monthly. Within one day of getting your first credit card,
you max out the credit limit by spending $1,200.00. If you do not buy anything else
on the card and you do not make any payments, write a program that would calculate
how much money would you owe the company after 6 months? [5 marks]
Question IV:
You decide to buy a home that�s appraised at Kshs.1, 000,000, so you pay a down
payment of Kshs. 400,000 and the balance you take aloan, with an interest rate of
3.5%. Let�s take a look at the 30-year loan. Write a program that will calculate
the monthly payment.
Assignment one
Question I:
#include<stdio.h>
main()
{
int a,b,c,answer;
a=8;
b=3;
c=5;
answer= (a*(c%b)+c);
Question II:
#include<stdio.h>
main()
{
float m,n,sum;
m=5;
n=3;
sum=m+n;
printf("The sum of %.0f and %.0f is %.0f\n",m,n,sum);
printf("%.0f is the sum of %.0f and %.0f\n",sum,m,n);
QUESTION III
The first credit card that you got charges 12.49 % interest to its customers and
compounds that interest monthly. Within one day of getting your first credit card,
you max out the credit limit by spending $1,200.00. If you do not buy anything else
on the card and you do not make any payments, write a program that would calculate
how much money would you owe the company after 6 months?
[5 marks]
Question IV:
You decide to buy a home that�s appraised at Kshs.1, 000,000, so you pay a down
payment of Kshs. 400,000 and the balance you take aloan, with an interest rate of
3.5%. Let�s take a look at the 30-year loan. Write a program that will calculate
the monthly payment. [5 marks]
#include<stdio.h>
#include<math.h>
main()
{
float monthly_payment,principle_amount,rate,amount,purchase_price,down_payment;
int number_of_years,total_months;
purchase_price=1000000;
down_payment=400000;
number_of_years=30;
principle_amount=purchase_price-down_payment;
rate=0.035/12;
total_months=number_of_years*12;
monthly_payment=principle_amount*(((rate*pow(1+rate,total_months)))/
(pow(1+rate,total_months)-1));
#include<stdio.h>
main()
{
char productName[50];
float unitPrice,totalPrice,MoneyPaid,changeGivenBack,tax,totalPurchasePrice;
int ProductCode,quantity;
printf("Product Name: ");
gets(productName);
5+8=13
int x,y,sum;
x=23;
y=34;
sum = x+y - THIS IS AN EXPRESSION
ASSIGNMENT(=)
6%4==2
6/4==1
EXAMPLE 1:
#include<stdio.h>
main()
{
int x,y,mod,div;
x=9;
y=5;
div=x/y;
mod=x%y;
printf("The division = %d\n",div);//The division=1
printf("The modulus = %d\n",mod);//The modulus = 4
return 0;
}
#include<stdio.h>
main()
{
int num1,num2,add,sub,div,mult,mod;
add=num1+num2;
sub=num1-num2;
mult=num1*num2;
div=num1/num2;
mod=num1%num2;
printf("SUM = %d\n",add);
printf("DIFFERENCE = %d\n",sub);
printf("PRODUCT = %d\n",mult);
printf("QUOTIENT = %d\n",div);
printf("MODULUS = %d\n",mod);
return 0;
}
EXAMPLE 2:
#include<stdio.h>
main()
{
int mins,hours,minutes;
hours=minutes/60;
mins=minutes%60;
return 0;
}
int x,y,sum;
x=78;
y=45;
sum==x+y;
COMPARISION/RELATIONAL OPERATORS
age=34;
if(age>=18)
you can vote
else
you can't vote
#include<stdio.h>
main()
{
int marks;
if(marks>=50)
printf("Marks: %d is a pass\n",marks);
else
printf("Marks: %d is a fail\n",marks);
return 0;
}
#include<stdio.h>
main()
{
int marks;
printf("Marks: %d is a pass\n",marks);
printf("Marks: %d is a fail\n",marks);
return 0;
}
#include<stdio.h>
main()
{
int marks;
while(marks<0 || marks>100)
{
printf("\n %d is invalid\n",marks);
printf("Please Re-Enter the marks: ");
scanf("%d",&marks);
}
if(marks>=50)
printf("Marks: %d is a pass\n",marks);
else
printf("Marks: %d is a fail\n",marks);
return 0;
}
marks>=50
MARKS>50
OR
MARKS==50
LOGICAL OPERATORS
AND &&
OR ||
NOT !
OR TRUE FALSE
TRUE TRUE TRUE
FALSE TRUE FALSE
= assignment
70-100 A
60- 69 B
50- 59 C
40- 49 D
0- 39 E
MARKS = 65
x=20, y=30,z=40
!(x>y||x<z)
false 0
true 1
#include<stdio.h>
main()
{
int x,y,z,ans;
x=20, y=30,z=40;
ans=!(x>y||x<z);
printf("The answer = %d\n",ans);
return 0;
}
#include<stdio.h>
main()
{
int x,y,z,ans;
x=10, y=20,z=30;
ans=x<10||z>10 ;
printf("The answer = %d\n",ans);
return 0;
}
0||1
#include<stdio.h>
main()
{
int x,y,z,ans;
x=10, y=20,z=30;
ans=!((x==y)&&(x!=y))&&(x<y||y<x) ;
printf("The answer = %d\n",ans);
return 0;
}
LOGICAL OPERATORS
! NOT
&& AND
|| OR
!1||0&&1
4+5*7
#include<stdio.h>
main()
{
int marks;
marks= !((1||0)&&1);
printf("Marks = %d\n",marks);
return 0;
}
OTHERS
++ INCREMENT
-- DECREMENT
= ASSIGNMENT
#include<stdio.h>
main()
{
int marks,i,n;
for(i=1;i<=n;i++)
{
printf("\nEnter the marks for student %d: ",i);
scanf("%d",&marks);
while(marks<0 || marks>100)
{
printf("\n %d is invalid\n",marks);
printf("Please Re-Enter the marks: ");
scanf("%d",&marks);
}
if(marks>=50)
printf("Marks: %d is a pass\n",marks);
else
printf("Marks: %d is a fail\n",marks);
}
return 0;
}
int x;
x=10;
x=x+10
x=x-10
x+=10
x-=10
+=
-=
*=
/=
x=10;
++x;
x++;
printf("X = %d\n",x);
--x;
x++;
printf("X = %d\n",x);
+=
-=
*=
/=
#include<stdio.h>
main()
{
int x;
x=5;
printf("x = %d\n",x);
x++;
++x;
printf("x = %d\n",x);
x--;
--x;
printf("x = %d\n",x);
return 0;
}
#include<stdio.h>
main()
{
int x;
x=5;
printf("x = %d\n",x);//x=5
x++;
++x;
printf("x = %d\n",x);//x=7
x--;
--x;
printf("x = %d\n",x);//x=5
return 0;
}
x=6
y=++x
y=x++
#include<stdio.h>
main()
{
int x,y;
x=30;
y=34;
printf("x = %d\n",x);
printf("y = %d\n",y);
x++;
x=x+1; // OR x+=1
x=y;
printf("x = %d\n",x);
printf("y = %d\n",y);
y = x--;
printf("x = %d\n",x);33
printf("y = %d\n",y);34
y= ++x;
printf("x = %d\n",x);
printf("y = %d\n",y);
return 0;
}
#include<stdio.h>
main()
{
int x,y;
x=33;
x++;
x--;
--x;
printf("X= %d\n",x);
y=x++;
printf("X= %d\n",x);
printf("Y= %d\n",y);
y=++x;
printf("X= %d\n",x);
printf("Y= %d\n",y);
return 0;
}
#include<stdio.h>
main()
{
int x,y;
x=36;
y=45;
x++;
x--;
y=x;
printf("X= %d\n",x);
printf("Y= %d\n",y);
x=y++;
printf("X= %d\n",x);
printf("Y= %d\n",y);
y=++x;
printf("X= %d\n",x);
printf("Y= %d\n",y);
return 0;
}
x=6
x++
x=x+1
x=x+8
x+=8 x=x+8
X-=8 x=x-8
X*=8 x=x*8
X/=8 x=x/8
#include<stdio.h>
main()
{
int x,y;
x=45;
y=50;
x+=7;
x--;
y=x;
printf("X= %d\n",x);
printf("Y= %d\n",y);
y-=10;
x=y++;
printf("X= %d\n",x);
printf("Y= %d\n",y);
x-=13;
y=++x;
printf("X= %d\n",x);
printf("Y= %d\n",y);
return 0;
}
#include<stdio.h>
main()
{
int x,y;
x=36;
x+=7;
x=x+7;
printf("X= %d\n",x);
= ASSIGNMENT
X=7;
CONTROL STRUCTURES:
*******************
THESE ARE STRUCTURES THAT ARE USED TO CONTROL THE FLOW
OF A PROGRAM OR HOW A PROGRAM EXECUTES
FOR EXAMPLE:
STATEMENT A;
STATEMENT B;
STATEMENT C;
STATEMENT D;
#include<stdio.h>
main()
{
int mins,hours,minutes,secs;
return 0;
}
PASSED AVG>=50
FAIL AVG<50
DECLARE VARIABLES
MATHS = 40
ENGLISH = 59
GEOGRAPHY =60
STEPS
40+59+60 = 159
159/3=53
AVG=53
IF AVG>=50
PASSED
IF AVG<50
FAILED
IF AVG>=50
PRINT PASS
ELSE
PRINT FAIL
ENDS
main()
{
int mk1,mk2,mk3,total,avg;
total=mk1+mk2+mk3;
avg=total/3;
SYNTAX
******
if(condition)
{
statement(s) to execute when true;
}
else
{
statement(s) to execute when false;
}
#include<stdio.h>
main()
{
int mark1,mark2,mark3,total,avg;
char name[50],regNumber[30];
printf("Enter full name: ");
gets(name);
total=mark1+mark2+mark3;
avg=total/3;
printf("RESULT SLIP FOR DECEMBER 2020 EXAMINATION\n");
printf("------------------------------------------\n");
printf("Registration Number: %s\n",regNumber);
printf("Full Name: %s\n",name);
printf("Mathematics: %d\n",mark1);
printf("Geography: %d\n",mark2);
printf("Chemistry: %d\n",mark3);
}
else
{
printf("RESULT: FAIL\n");
printf("Rewind the stage\n");
}
return 0;
}
ax^2 +bx+c=0
#include<stdio.h>
#include<math.h>
main()
{
float a,b,c,x1,x2;
if((b*b-4*a*c)>=0)//discriminant>=0
{
x1= (-b+sqrt(b*b-4*a*c))/(2*a);
x2= (-b-sqrt(b*b-4*a*c))/(2*a);
printf("root1 = %f\n",x1);
printf("root2 = %f\n",x2);
}
else
{
printf("No possible roots\n");
}
You win the lottery and get $1,000,000. You decide that
you want to invest all of the money in a savings account.
However, your bank has two different plans.
Write a program that will determine in 5 years
from now, which plan will provide you with more money
Plan 1
Plan 2
[6 marks]
#include<stdio.h>
main()
{
float p,r1,r2,t,n1,n2,plan1,plan2;//Declaration of variable
p=1000000;
r1=0.06;
r2=0.12;
t=5;
n1=12;
n2=6;
plan1=p*(pow(1+r1/n1,n1*t));
plan2=p*(pow(1+r2/n2,n2*t));
if(plan1>plan2)
{
printf("\nTHEREFORE PLAN 1 is the best option at Kshs. %.2f\n",plan1);
}
else if(plan1==plan2)
{
printf("Any plan is ok!!!\n");
}
else
{
printf("\nTHEREFORE PLAN 2 is the best option at Kshs. %.2f\n",plan2);
}
}
#include<stdio.h>
main()
{
float basic,trans_allow,h_allow,gross,net,tax;
if(basic>=50000)
{
trans_allow=25.0/100*basic;
h_allow=30.0/100*basic;
}
else
{
trans_allow=20.0/100*basic;
h_allow=15.0/100*basic;
}
gross = basic+trans_allow+h_allow;
if(gross>=30000)
{
tax=16.0/100*gross;
}
else
{
tax=0;
}
net=gross-tax;
return 0;
}
printf("The sum of %.1f and %.1f is %.1f\n",m,n,sum); The sum of 5.0 and 3.0 is 8.0
printf("%.1f is the sum of %.1f and %.1f\n",sum,m,n); 8.0 is the sum of 5.0 and 3.0
25.0/100==0
0.25
int/int ==int
float/int==float
int/float==float
float/float==float
#include<stdio.h>
main()
{
float basic,trans_allow,h_allow,gross,net,tax;
if(basic>=50000)
{
trans_allow=basic*30/100;
h_allow=basic*25/100;
}
else
{
trans_allow=basic*20/100;
h_allow=basic*15/100;
}
gross = basic+trans_allow+h_allow;
tax=gross*16/100;
net=gross-tax;
printf("Salary details\n");
printf("****************\n");
return 0;
}
EXAMPLE 3:
#include<stdio.h>
main()
{
int number;
if(number%2==0)
{
printf("%d is even\n",number);
}
else
{
printf("%d is odd\n",number);
}
return 0;
}
THE TERNARY STRUCTURE
if(condition)
{
statement(s)-true;
}
else
{
statement(s)-false;
}
expression1?expression2:expression3;
condition?statement(s)-true:statement(s)-false;
#include<stdio.h>
main()
{
int number;
return 0;
}
i.e expression1 is evaluated, if it is true, then expression2 is evaluated and
becomes the value of the whole expression. Otherwise, expression3 is evalauted and
becomes the value of the whole expression.
Example 1:
int a,b;
a=10;
b=15;
x=(a>b)?a:b;
#inlcude<stdio.h>
main()
{
int a,b;
a=10;
b=15;
if(a>b)
{
printf("%d is bigger than %d\n",a,b);
}
else
{
printf("%d is bigger than %d\n",b,a);
}
}
#include<stdio.h>
main()
{
int a,b;
if(a>b)
printf("%d is bigger than %d\n",a,b);
else
printf("%d is bigger than %d\n",b,a);
}
#inlcude<stdio.h>
main()
{
int a,b,bigger;
a=10;
b=15;
if(a>b)
bigger=a;
else
bigger=b;
printf("%d is the biggest",bigger);
}
#inlcude<stdio.h>
main()
{
int a,b,bigger;
a=10;
b=15;
bigger=a>b?a:b;
printf("%d is the biggest",bigger);
}
#inlcude<stdio.h>
main()
{
int num1,num2,bigger;
printf("Enter first number: ");
scanf("%d",&num1);
if(num1>num2)
printf("%d is bigger than %d\n",num1,num2);
else
printf("%d is bigger than %d\n",num2,num1);
#include<stdio.h>
main()
{
int num1,num2,bigger;
printf("Enter first number: ");
scanf("%d",&num1);
Variable x attains the value of b i.e. 15. This is because the condition (a>b)
fails and therefore the value of the expression b becomes the value of the
expression ((a>b)?a:b)
Note that the above example of a ternary statement is equivalent to the following
if...else block.
if(a>b)
x=a;
else
x=b;
a>b?printf("%d",a):printf("%d",b);
x=(a>b)?a:b;
prinf("%d",x);
Example 2:
Write the outputs of the following codes:
(iii) int m;
m=(5<8 && 3>9)?7:5;
printf("%d",m);
(iv) printf("%d",(4>3)||3>8)?6:8);
Answers
(i)positive
(ii)Negative
(iii)5
(iv)6
SYNTAX
if(condition)
{
statement(s);
}
else if(condition)
{
statement(s);
}
else if(condition)
{
statement(s);
}
......
else
{
statement(s);
}
1,2,3......n
For example, we want to print a remark about a student based on his secured marks.
Following is the situation -
Assume given marks are x for a student:
If given marks are less than 95 and more than 30, then
Student is average
#include <stdio.h>
int main() {
int x;
printf("Enter marks: ");
scanf("%d",&x);
#include <stdio.h>
int main() {
int x;
printf("Enter marks: ");
scanf("%d",&x);
else
{
printf("Marks invalid!!!\n");
}
}
EXAMPLE
A PROGRAM IS REQUIRED THAT ACCEPT THE MARKS A STUDENT
GETS IN THREE SUBJECTS AND THEN GRADE THE STUDENT USING
THE FOLLOWING GRADING SYSTEM
#include<stdio.h>
main()
{
int mark1,mark2,mark3,total,avg;
char grade,name[40];
total=mark1+mark2+mark3;
avg=total/3;
}
else if(avg>=60 && avg<70)
{
grade='B';
}
else if(avg>=50 && avg<60)
{
grade='C';
}
else if(avg>=40 && avg<50)
{
grade='D';
}
else
{
grade='X';
}
printf("Name: %s\n",name);
printf("Total marks: %d\n",total);
printf("Average Marks = %d\n",avg);
printf("Grade: %c\n",grade);
if(avg>=50)
{
printf("RESULT: PASS\n");
printf("Proceed to next stage\n");
}
else
{
printf("RESULT: FAIL\n");
printf("Rewind the stage\n");
}
return 0;
}
EXAMPLE
The income earned by a salesman is computed as shown
below.
Fixed allowance: kshs. 5000.00
Required:
Write a program that will allow the user to input
the sales
of a salesmen and compute the net income.
#include<stdio.h>
main()
{
float income,tax,sales,commission,net;
const float FIXED_ALLOWANCE=5000.00;
if(sales>=50000)
{
commission=12.0/100*sales;
}
else if(sales>=20000 && sales<50000)
{
commission=9.0/100*sales;
else
{
commission=0.0;
}
income = commission+FIXED_ALLOWANCE;
if(income>=10000)
{
tax=10.0/100*income;
}
else
{
tax=0;
}
net=income-tax;
printf("Salary details\n");
printf("****************\n");
return 0;
}
#include<stdio.h>
main()
{
float tax,bs,ha,gross,net;
const float TA =5000;
tax=10.0/100*bs;
ha=20.0/100*bs;
gross=bs+ha+TA;
net=gross-tax;
return 0;
Example 4:
? Name of customer
? Address
? Telephone Number
? Previous meter reading 100
? Current meter reading 400
cons=c_reading-p_reading;
if(cons>350)
{
bill=cons*1.65;
}
else if(cons>200 && cons<=350)
{
bill=cons*1.90;
}
else
{
bill=0;
}
printf("Address: %s\n",address);
return 0;
}
The overtime rate is Ksh. 300 per hour for the first 50 hours
an employee has worked overtime. Any extra overtime hour
is paid at Ksh. 350 per hour.
The computer then determines the PAYE amount payable from the
gross pay. Finally the employee�s net pay is calculated using
the formula:
GROSS PAY
PAYE AMOUNT
NET PAY
Example
#include<stdio.h>
#define NSSF 80.00
#define NHIF 180.00
main()
{
float gross,basic,net,paye,deductions;
int extra_hours,hours,emp_number,overtime,extra_overtime;
char firstname[30],lastname[30],position[30];
if(hours<=50)
{
overtime=hours*300;
}
else
{
extra_hours= hours-50;
extra_overtime=extra_hours*350;
overtime=15000+extra_overtime;
}
gross=basic+overtime;
if(gross>=50000)
{
paye=14.0/100*gross;
}
else if(gross>=40000 &&gross<50000)
{
paye=12.0/100*gross;
}
else if(gross>=35000 &&gross<40000)
{
paye=11.0/100*gross;
}
else if(gross>=25000 &&gross<35000)
{
paye=8.0/100*gross;
}
else if(gross>=16000 &&gross<25000)
{
paye=5.0/100*gross;
}
else if(gross>=9500 &&gross<16000)
{
paye=3.0/100*gross;
}
else
{
paye=0.0/100*gross;
}
deductions=paye+NSSF+NHIF+SERVICE_CHARGE;
net=gross-(paye+(NSSF+NHIF+SERVICE_CHARGE));
Gross Tax
<2000 0%
2001-3000 5%
3001-4000 7%
4001-5000 9%
>5000 11%
v) Net pay = Gross pay � Tax
Hourly rate(Ksh.1500) and lunch allowance are constant values.
The number of hours worked should be read from the keyboard.
Write a program to implement the process.
#include<stdio.h>
main()
{
float gross,basic,net,tax;
const float LA=200,hourly_rate=2500;
int emp_number,hours;
char firstname[30],lastname[30],position[30];
printf("EMPLOYEE INFORMATION\n");
printf("************************");
printf("\nEnter the first name: ");
gets(firstname);
basic=hours*hourly_rate;
gross=LA+basic;
if(gross>2000)
tax=11.0/100*gross;
else if(gross>4000 && gross<=5000)
tax=9.0/100*gross;
}
Mr. Patel has 15 employees whose wages are paid at the end of each week. The basic
salary is obtained by multiplying the number of hours worked by the rate of pay
.Each employee gets daily lunch allowance of Kshs. 200. When added to basic pay the
gross is then deduced to obtain the net salary. You are required to write a program
which will process the salary for the 15 employees in Mr. Patel�s company.
Makelele Institute lecturers require a program that they will use for grading
students
at the end of each semester.
The program to be designed should input the student name, the results of
TWO Continuous Assessment Tests (CAT) for each of the four subjects,
namely Applications, Fundamentals, Communications and Mathematics,
and the results of the final examination in each subject.
The program will then compute the total and average mark for each subject.
Based on the average, the program will assign grades as follows:
The program will finally print out a transcript for the student.
#include<stdio.h>
main()
{
int mk1,mk2,mk3,mk4,cat1,cat2,avg;
printf("Application Programming\n");
printf("------------------------\n");
printf("CAT 1: ");
scanf("%d",&cat1);
printf("CAT 2: ");
scanf("%d",&cat2);
mk1=cat1+cat2;
avg=mk1/2;
printf("CAT 1: %d\n",cat1);
printf("CAT 2: %d\n",cat2);
printf("Total: %d\n",mk1);
printf("Average: %d\n",avg);
printf("Computer Fundamentals\n");
printf("------------------------\n");
printf("CAT 1: ");
scanf("%d",&cat1);
printf("CAT 2: ");
scanf("%d",&cat2);
mk2=cat1+cat2;
avg=mk2/2;
printf("CAT 1: %d\n",cat1);
printf("CAT 2: %d\n",cat2);
printf("Total: %d\n",mk2);
printf("Average: %d\n",avg);
printf("Communication Skills\n");
printf("------------------------\n");
printf("CAT 1: ");
scanf("%d",&cat1);
printf("CAT 2: ");
scanf("%d",&cat2);
mk3=cat1+cat2;
avg=mk3/2;
printf("CAT 1: %d\n",cat1);
printf("CAT 2: %d\n",cat2);
printf("Total: %d\n",mk3);
printf("Average: %d\n",avg);
printf("CAT 2: ");
scanf("%d",&cat2);
mk4=cat1+cat2;
avg=mk4/2;
printf("CAT 1: %d\n",cat1);
printf("CAT 2: %d\n",cat2);
printf("Total: %d\n",mk4);
printf("Average: %d\n",avg);
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
default:
code to be executed if n is different from both label1 and label3;
}
This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from running
into the next case automatically. The default statement is used if no match is
found.
Example
EXAMPLE
A PROGRAM IS REQUIRED THAT ACCEPT THE MARKS A STUDENT
GETS IN THREE SUBJECTS AND THEN GRADE THE STUDENT USING
THE FOLLOWING GRADING SYSTEM
Points GRADE
1 Distinction
2 Credit
3 Pass
4 Fail
Points Grade
70-100 Distinction
60-69 Credit
50-59 Pass
0-49 Fail
#include<stdio.h>
main()
{
int points;
printf("Enter the points: ");
scanf("%d",&points);
if(points==1)
{
printf("Distinction\n");
}
else if(points==2)
{
printf("Credit\n");
}
else if(points==3)
{
printf("Pass\n");
}
else if(points==4)
{
printf("Fail\n");
}
else
{
printf("Invalid points\n");
}
#include<stdio.h>
main()
{
int points;
printf("Enter the points: ");
scanf("%d",&points);
switch(points)
{
case 1:
printf("Distinction\n");
break;
case 2:
printf("Credit\n");
break;
case 3:
printf("Pass\n");
break;
case 4:
printf("Fail\n");
break;
default:
printf("Invalid points\n");
}
}
Example 2:
#include<stdio.h>
main()
{
int points;
printf("Enter the points: ");
scanf("%d",&points);
while(points<1 || points>4)
{
printf("Invalid points entered!!!\n");
printf("Re-nter the points: ");
scanf("%d",&points);
}
switch(points)
{
case 1:
printf("Distinction\n");
break;
case 2:
printf("Credit\n");
break;
case 3:
printf("Pass\n");
break;
case 4:
printf("Fail\n");
break;
default:
printf("Invalid points\n");
}
}
Points GRADE
A Distinction
B Credit
C Pass
D Fail
#include<stdio.h>
main()
{
char p, points;
printf("Enter the points: ");
scanf("%c",&p);
points=toupper(p);
switch(points)
{
case 'A':
printf("Distinction\n");
break;
case 'B':
printf("Credit\n");
break;
case 'C':
printf("Pass\n");
break;
case 'D':
printf("Fail\n");
break;
default:
printf("Invalid points\n");
}
}
#include<stdio.h>
main()
{
char p, points;
printf("Enter the points: ");
scanf("%c",&p);
points=toupper(p);
while(points>'E')
{
printf("Invalid points entered!!!\n");
printf("Re-nter the points: ");
scanf("%c",&p);
points=toupper(p);
}
switch(points)
{
case 'A':
printf("Distinction\n");
break;
case 'B':
printf("Credit\n");
break;
case 'C':
printf("Pass\n");
break;
case 'D':
printf("Fail\n");
break;
default:
printf("Invalid points\n");
}
}
#include<stdio.h>
main()
{
char name[40];
printf("Enter the name of your president: ");
gets(name);
/*while(points<1 || points>4)
{
printf("Invalid points entered!!!\n");
printf("Re-nter the points: ");
scanf("%d",&points);
}*/
switch(puts(name))
{
case 'UHURU':
printf("%s: IS THE PRESIDENT OF KENYA\n",name);
break;
case 'MUSEVENI':
printf("%s: IS THE PRESIDENT OF UGANDA\n",name);
break;
case 'KIKWETE':
printf("%s: IS THE PRESIDENT OF TANZANIA\n",name);
break;
case 'KAGAME':
printf("%s: IS THE PRESIDENT OF RWANDA\n",name);
break;
default:
printf("%s : IS NOT A PRESIDENT OF ANY COUNTRY\n",name);
}
}
1.for
2.while
3.do---while
while(condition)
{
statement(s);
}
do
{
statement(s);
}
while(condition);
for(initial_value;condition_to_test;increment/decrement)
{
statement_to_repeat;
}
#include <stdio.h>
int main() {
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
#include <stdio.h>
int main() {
int counter;
counter=1;
while(counter<=10)
{
printf( "Hello, World!\n");
counter++; //counter=counter+1;
}
return 0;
computers =3
while(computers>0)
{
pick a computer;
computers--;
Example:
#include<stdio.h>
main()
{
int number_of_computers;
number_of_computers=6;
while(number_of_computers>0)
{
printf("Pick a computer to proceed\n");
number_of_computers--;
}
printf("There are no more computers to be picked\n");
}
#include<stdio.h>
main()
{
int number_of_computers;
number_of_computers=6;
while(number_of_computers>0)
{
printf("You picked the %d computer\n",number_of_computers);
number_of_computers--;
}
printf("There are no more computers to be picked\n");
}
do
{
statement(s);
}
while(condition);
for(initial_value;condition_to_test;increment/decrement)
{
statement_to_repeat;
}
#include <stdio.h>
int main() {
int counter;
for(counter=1;counter<=10;counter++;)
{
printf( "Hello, World!\n");
}
return 0;
#include<stdio.h>
main()
{
int number_of_computers;
for(number_of_computers=6;number_of_computers>0;number_of_computers--)
{
printf("You picked the %d computer\n",number_of_computers);
}
printf("There are no more computers to be picked\n");
}
#include<stdio.h>
main()
{
int x1,x2,x3,x4,x5;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
printf("%d\n",x1);
printf("%d\n",x2);
printf("%d\n",x3);
printf("%d\n",x4);
printf("%d\n",x5);
#include<stdio.h>
main()
{
int x;
x=1;//initial value
while(x<=5)//condition
{
printf("%d\n",x);//statement
x++;//update
}
#include<stdio.h>
main()
{
int x,number,sum=0;
x=1;//initial value
while(x<=5)//condition
{
printf("Enter a number: ");
scanf("%d",&number);
sum=number+sum;
x++;
}
printf("%d\n",sum);
}
x=x+1
x=x+2 or x+=2
x=x+10 or x+=10
x=x-10 or x-=10
#include<stdio.h>
main()
{
int number;
number=1;
while(number<6)
{
printf("%d\n",number);
number++;
}
10
20
30
40
50
60
70
80
90
100
x=x+2
x+=2
main()
{
int number;
number=0;
while(number%3==0 && number<=100)
{
printf("%d\n",number);
number+=3;
}
#include<stdio.h>
main()
{
int number,answer;
number=1;
printf("NUMBER\t\t SQUARE\n");
printf("------------------------\n");
while(number<6)
{
answer=number*number;
printf("%d\t\t%d\n",number,answer);
number++;
}
while(condition)
{
statement(s);
}
#include<stdio.h>
main()
{
int number_of_computers;
number_of_computers=0;
while(number_of_computers>0)
{
printf("Pick a computer to proceed\n");
number_of_computers--;
}
printf("There are no more computers to be picked\n");
}
do
{
statement(s);
}
while(condition);
#include <stdio.h>
int main() {
int counter;
counter=20;
do
{
printf( "Hello, World!\n");
counter++;
}
while(counter<=10)
return 0;
#include<stdio.h>
main()
{
int number_of_computers;
number_of_computers=0;
do
{
printf("Pick a computer to proceed\n");
number_of_computers--;
}
while(number_of_computers>0);
#include<stdio.h>
main()
{
int number,answer;
number=0;
printf("NUMBER\t\t SQUARE\n");
printf("------------------------\n");
while(number<=100)
{
answer=number*number;
printf("%d\t\t%d\n",number,answer);
number+=2;
}
#include<stdio.h>
main()
{
int x1,x2,x3,x4,x5;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
printf("%d\n",x1);
printf("%d\n",x2);
printf("%d\n",x3);
printf("%d\n",x4);
printf("%d\n",x5);
#include<stdio.h>
main()
{
int x;
x=1;
printf("%d\n",x);
x++;
printf("%d\n",x);
x++;
printf("%d\n",x);
x++;
printf("%d\n",x);
x++;
printf("%d\n",x);
#include<stdio.h>
main()
{
int x;
x=2;
while(x<=100)
{
printf("%d\n",x);
x=x+2;
}
#include<stdio.h>
main()
{
int x;
x=0;
while(x<=27)
{
printf("%d\n",x);
x+=3;
}
}
print: 0,3,6,9,12,15,18,21,24,27
#include<stdio.h>
main()
{
int x;
x=27;
while(x>=0)
{
printf("%d\n",x);
x-=3;
}
27,24,21,18,15,12,9,6,3,0
#include<stdio.h>
main()
{
int x;
x=0;
while(x<=20)
{
printf("%d\n",x);
x+=2;
}
#include<stdio.h>
main()
{
int value;
value=1;//initial value
while(value<=5)
{
printf("%d\n",value);
value++;
}
x++
x--
x=x+1
x=x+2 x+=2
x=x+10 x+=10
#include<stdio.h>
main()
{
int value;
value=0;//initial value
while(value<=100)
{
printf("%d\n",value);
value+=2;
for(initial value;condition;update)
{
statement(s);
}
#include<stdio.h>
main()
{
int x;
x=27;
while(x>=0)
{
printf("%d\n",x);
x-=3;
}
#include<stdio.h>
main()
{
int x;
for(x=27;x>=0;x-=3)
{
printf("%d\n",x);
}
}
#include<stdio.h>
main()
{
int number,answer;
printf("NUMBER\t\t SQUARE\n");
printf("------------------------\n");
for(number=20;number>=0;number-=2)
{
answer=number*number;
printf("%d\t\t%d\n",number,answer);
}
}
while(condition)
{
statement(s);
}
do---while
syntax:
do
{
statement(s);
}
while(condition);
#include<stdio.h>
main()
{
int x;
x=27;
while(x<27)
{
printf("%d\n",x);
x-=3;
}
}
This will print nothing since the condition false
#include<stdio.h>
main()
{
int x;
x=27;
do
{
printf("%d\n",x);
x+=3;
}
while(x<27);
#include<stdio.h>
main()
{
int x;
for(x=27;x>=0;x-=3)
{
printf("%d\n",x);
#include<stdio.h>
main()
{
int value;
for(value=5;value<=5;value--)
{
printf("%d",value);
#include<stdio.h>
main()
{
int value;
value=0;//initial value
while(value<=100)
{
printf("%d\n",value);
//value+=2;
value=value+2;
}
5
4
3
2
1
0
#include<stdio.h>
main()
{
int value;
value=5;//initial value
while(value>=0)
{
printf("%d",value);
value--;
c=5/9(f-32)
#include<stdio.h>
main()
{
int f,c;
f=0;
while(f<=100)
{
c=5.0/9.0*(f-32);
printf("%d\t",f);
printf("%d\n",c);
f+=10;
}
#include<stdio.h>
main()
{
int fah,cel;
printf("FAHRENHEIT\t CELCIUS\n");
printf("---------------------------\n");
for(fah=0;fah<=100;fah+=10)
{
cel=5.0/9.0*(fah-32);
printf("%d\t\t|\t%d\n",fah,cel);
}
}
#include<stdio.h>
main()
{
float w,h,BMI;
printf("Enter the weight: ");
scanf("%f",&w);
BMI=w/(h*h);
printf("Weight = %f\n",w);
printf("height = %f\n",h);
printf("BMI = %f\n",BMI);
#include<stdio.h>
main()
{
float w,h,BMI;
int age;
if(age<=18 || age>=65)
{
printf("BMI doesn't apply\n");
}
else
{
printf("Enter the weight: ");
scanf("%f",&w);
BMI=w/(h*h);
printf("Weight = %f\n",w);
printf("height = %f\n",h);
printf("BMI = %f\n",BMI);
main()
{
int t,f(t);
if(t>=0)
{
ft=-3*t*t+5;
}
else
{
ft=-3*t*t-5;
ft=-3*pow(t,2)+5
#include<stdio.h>
main()
{
float p,r,n,t,amount;
p=10000;
r=0.08;
n=12;
t=15;
amount=p*pow(1+r/n,n*t);
}
amount=p(1+r/n)^nt
#include<stdio.h>
main()
{
float p,r,amount;
int n,t;
p=10000;
r=0.08;
n=12;
t=1;
while(t<=15)
{
amount=p*pow(1+r/n,n*t);
t++;
}
}
#include<stdio.h>
main()
{
float p,r,amount;
int n,t,count;
p=10000;
r=0.08;
n=12;
t=15;
count=1;
printf("Year\t\tAmount (Kshs.)\n");
printf("-------------------------------\n");
while(count<=t)
{
amount=p*pow(1+r/n,n*count);
count++;
}
}
#include<stdio.h>
main()
{
float p,r,amount;
int n,t,count;
p=10000;
r=0.08;
n=12;
t=15;
printf("Year\t\tAmount (Kshs.)\n");
printf("-------------------------------\n");
for(count=1;count<=t;count++)
{
amount=p*pow(1+r/n,n*count);
}
}
#include<stdio.h>
main()
{
float p,r,amount;
int n,t;
p=10000;
r=0.08;
n=12;
t=1;
do
{
amount=p*pow(1+r/n,n*t);
t++;
}
while(t>15);
for(initial value;condition;update)
{
#include<stdio.h>
main()
{
float p,r,amount;
int n,t;
p=10000;
r=0.08;
n=12;
for(t=1;t<=15;t++)
{
amount=p*pow(1+r/n,n*t);
}
}
do-----while
do
{
statements;
}
while(condition);
#include<stdio.h>
main()
{
int f,c;
for(f=0;f<=100;f+=10)
{
c=5/9*(f-32);
printf("%d \t\t\t %d\n",f,c);
#include<stdio.h>
main()
{
int f,c;
f=0;
printf("Fahrenhiet \t\t Degrees celcius\n" );
while(f<=100)
{
c=5.0/9.0*(f-32);
printf("%d\t\t%d\n",f,c);
f+=10;
#include<stdio.h>
#include<math.h>
main()
{
float p,r,t,n,amount;
p=1500;
r=0.043;
n=4;
t=6;
amount=p*(pow(1+r/n,n*t));
Solution:
Using the compound interest formula, we have that
P = 1500, r = 4.3/100 = 0.043, n = 4, t = 6.
#include<stdio.h>
#include<math.h>
main()
{
float p,r,total_amount;
int n,t;
p=1500;
r=0.043;
n=4;
t=1;
printf("Year\t\t Total Amount(Kshs.)\n");
while(t<=6)
{
total_amount=p*(pow(1+r/n,n*t));
t++;
}
}
#include<stdio.h>
#include<math.h>
main()
{
float p,r,t,n,amount;
p=1200;
r=0.1249;
n=12;
t=0.5;
amount=p*(pow(1+r/n,n*t));
#include<stdio.h>
#include<math.h>
main()
{
float p,r,total_amount;
int n,t;
p=1200;
r=0.1249;
n=12;
t=1;
t++;
}
}
#include<stdio.h>
main()
{
int marks;
printf("Enter the marks: ");
scanf("%d",&marks);
while(marks<0 ||marks>100)
{
printf("Marks is Invalid,re-enter: ");
scanf("%d",&marks);
}
if(marks>=50)
printf("VERDICT: Pass\n");
else
printf("VERDICT: Fail\n");
#include<stdio.h>
main()
{
float tax,bs,ha,gross,net;
int n;
const float TA =5000;
n=1;
while(n<=3)
{
printf("Enter details for employee: %d\n",n);
printf("--------------------------------\n")
printf("Enter the basic salary: Kshs. ");
scanf("%f",&bs);
tax=10.0/100*bs;
ha=20.0/100*bs;
gross=bs+ha+TA;
net=gross-tax;
n++;
}
return 0;
Example:
#include<stdio.h>
main()
{
int marks,n;
n=1;
while(n<=5)
{
printf("Enter the marks for student %d: ",n);
scanf("%d",&marks);
if(marks>=50)
{
printf("PASS\n");
printf("Proceed to next stage\n");
}
else
{
printf("FAIL\n");
printf("Rewind the stage\n");
}
n++;
}
}
x=1;//initial value
while(x<90)//condition to test
{
printf("X = %d\n",x);//statement to execute when
x++;//condition is true
}
90
80
70
60
int x;
x=90;
while(x<=90 || x>1)
{
printf("X = %d\n",x);//statement to execute when
x-=10;//condition is true
#include<stdio.h>
main()
{
int marks,i,n;
printf("Marks: %d\n",marks);
if(marks>=50)
{
printf("PASS\n");
printf("Proceed to next stage\n\n");
}
else
{
printf("FAIL\n");
printf("Rewind the stage\n\n");
}
EXAMPLE 2:
#include<stdio.h>
main()
{
int marks,i,n;
i=1;//iniatial value
printf("Enter the number of students: ");
scanf("%d",&n);
while(i<=n)//condition
{
printf("Enter marks for student %d\n",i);
printf("------------------------\n");
printf("Enter the marks: ");
scanf("%d",&marks);
printf("Marks: %d\n",marks);
if(marks>=50)
{
printf("PASS\n");
printf("Proceed to next stage\n\n");
}
else
{
printf("FAIL\n");
printf("Rewind the stage\n\n");
}
i++;//update
}
}
#include<stdio.h>
main()
{
int f,c;
f=0;//iniatial value
printf("Fahrenheit\t\tCelcius\n");
while(f<=100)//condition
{
c=5.0/9.0*(f-32);
printf("%d\t\t\t%d\n",f,c);
f+=10;
}
return 0;
}
EXAMPLE
The income earned by a salesman is computed as shown below.
Fixed allowance: kshs. 5000.00
Required:
Write a program that will allow the user to input the sales
of n salesmen and compute the net income.
if(sales>=50000)
{
commission=12.0/100*sales;
}
else if(sales>=20000 && sales<50000)
{
commission=9.0/100*sales;
else
commission=0.0/100*sales;
income = commission+FIXED_ALLOWANCE;
if(income>=10000)
{
tax=10.0/100*income;
}
else
tax=0;
net=income-tax;
printf("Salary details\n");
printf("****************\n");
initial value;
while(condition)
{
statement(s);
update;
}
#include<stdio.h>
main()
{
int marks,i,n;
printf("Enter the number of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)//condition
{
printf("Enter marks for student %d\n",i);
printf("------------------------\n");
printf("Enter the marks: ");
scanf("%d",&marks);
if(marks>=50)
{
printf("PASS\n");
printf("Proceed to next stage\n\n");
}
else
{
printf("FAIL\n");
printf("Rewind the stage\n\n");
}
}
}
#include<stdio.h>
main()
{
int marks,i,n;
printf("Enter the number of students: ");
scanf("%d",&n);
while(n<=0)
{
printf("Number of students can't be less than 0,Please renter: ");
scanf("%d",&n);
}
for(i=1;i<=n;i++)//condition
{
printf("Enter marks for student %d\n",i);
printf("------------------------\n");
printf("Enter the marks: ");
scanf("%d",&marks);
while(marks<0 || marks>100)
{
printf("Marks should be between 0 -100, Please renter: ");
scanf("%d",&marks);
}
if(marks>=50)
{
printf("PASS\n");
printf("Proceed to next stage\n\n");
}
else
{
printf("FAIL\n");
printf("Rewind the stage\n\n");
}
}
}
#include<stdio.h>
main()
{
float income,tax,sales,commission,net;
const float FIXED_ALLOWANCE=5000;
int n,i;
if(sales>=50000)
{
commission=12.0/100*sales;
}
else if(sales>=20000 && sales<50000)
{
commission=9.0/100*sales;
else
commission=0.0/100*sales;
income = commission+FIXED_ALLOWANCE;
if(income>=10000)
{
tax=10.0/100*income;
}
else
tax=0;
net=income-tax;
printf("Salary details\n");
printf("****************\n");
}
return 0;
}
do----while
Remember:
while(condition)
{
statement(s);
}
syntax
*******
do
{
statements;
}
while(condition)
#include<stdio.h>
main()
{
int marks,i,n;
i=1;
printf("Enter the number of students: ");
scanf("%d",&n);
do
{
printf("Enter marks for student %d\n",i);
printf("------------------------\n");
printf("Enter the marks: ");
scanf("%d",&marks);
if(marks>=50)
{
printf("PASS\n");
printf("Proceed to next stage\n\n");
}
else
{
printf("FAIL\n");
printf("Rewind the stage\n\n");
}
i++;
}
while(i<=n);//condition
More Examples:
#include<stdio.h>
main()
{
int marks,counter,n;
char regNum[40],name[40];
printf("Enter the number students: ");
scanf("%d",&n);
counter=1;
do
{
printf("\nSTUDENT: %d\n ",counter);
printf("-------------\n ");
printf("Enter name: ");
getchar();
gets(name);
if(marks>=50)
{
printf("Verdict: Passed\n");
printf("Proceed to the next class\n");
}
else
{
printf("Verdict: Failed\n");
printf("Rewind the semester\n");
}
counter++;
}
while(counter<=n);
Nested Loops
A loop can be included inside another loop to form an outer loop and an inner
loop.This implies that for every outer loop,the inner loop is repeated as
determined by its own condition.
Example:
Consider the following code and try to identify two loops, one inside the other,
each loop having a body, a counter initialization, condition testing and counter
increment. The outer loopis controlled by the counter a, while the inner loop is
controlled by the counter b.
#include<stdio.h>
int main()
{
int a,b;
a=0;
while(a<3)
{
b=0;
printf("Loop %d\n",(a+1));
while(b<4)
{
printf("Loop\n");
b++;
}
a++;
printf("\n");
}
}
Solution
Loop 1
Loop
Loop
Loop
Loop
Loop 2
Loop
Loop
Loop
Loop
Loop 3
Loop
Loop
Loop
Loop
The outer loop and the inner loop in the immediate above code can be illustrated as
below
while(a<3)
{
statements;
a++;
printf("\n");
}
When executed, the code will output the text "Loop" 12 times on different lines.
This is because the outer loop runs 3 times(for values 0,1,2 of a), and for each of
these three times, the inner loop runs four times( for values 0,1,2,3 of b).
i) do...while loops
#include<stdio.h>
int main()
{
int a,b;
a=0;
do{
b=0;
printf("Loop %d\n",(a+1));
do{
printf("Loop\n");
b++;
}
while(b<4);
a++;
printf("\n");
}
while(a<3);
}
ii) for loops
#include<stdio.h>
int main()
{
int a,b;
for(a=0;a<3;a++)
{
printf("Loop %d\n",(a+1));
for(b=0;b<4;b++)
{
printf("Loop\n");
printf("\n");
}
}
Example:
Determine the output of the following code fragments:
i)
#include<stdio.h>
int main()
{
int a,b;
for(a=0;a<3;a++)
{
for(b=0;b<=3;b++)
{
printf("%d\t",b);
}
}
}
ii)
#include<stdio.h>
int main()
{
int a,b;
for(a=0;a<3;a++)
{
for(b=0;b<=3;b++)
{
printf("%d\t",a);
}
}
}
iii)
#include<stdio.h>
int main()
{
int a,b;
for(a=0;a<3;a++)
{
for(b=0;b<=3;b++)
{
printf("%d\t",b);
}
printf("\n");
}
}
iv)
#include<stdio.h>
int main()
{
int a,b;
for(a=0;a<=4;a++)
{
for(b=0;b<=a;b++)
{
printf("%d\t",b);
}
printf("\n");
}
}
v)
#include<stdio.h>
int main()
{
int a,b;
for(a=1;a<=4;a++)
{
for(b=1;b<=a;b++)
{
printf("%d\t",a);
}
printf("\n");
}
}
i)
0 1 2 3 0 1 2 3 0 1 2
3
Process returned 2 (0x2) execution time : 0.449 s
Press any key to continue.
ii)
0 0 0 0 1 1 1 1 2 2 2
2
Process returned 2 (0x2) execution time : 1.430 s
Press any key to continue.
iii)
0 1 2 3
0 1 2 3
0 1 2 3
iv)
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
v)
1
2 2
3 3 3
4 4 4 4
Example:
#include<stdio.h>
int main()
{
int row,col,n;
printf("\t");
for(row=1;row<=5;row++)
{
printf("%d\t",row);
}
printf("\n");
for(row=1;row<=5;row++)
{
printf("%d\t",row);
for(col=1;col<=5;col++)
{
printf("%d\t",(row*col));
}
printf("\n");
}
}
Example:
Write a program to input n and output the a multiplication table of size n(where n
is any number).
#include<stdio.h>
int main()
{
int row,col,n;
printf("\t");
for(row=1;row<=n;row++)
{
printf("%d\t",row);
}
printf("\n");
for(row=1;row<=n;row++)
{
printf("%d\t",row);
for(col=1;col<=n;col++)
{
printf("%d\t",(row*col));
}
printf("\n");
}
}
Algorithms
***********
Computer problem solving is the use of computers to solve problems.
Most of the problems that the computers can solve will involve collection,
storage and manipulation of information.
To a developer, the problem is viewed from a developmental perspective.
The problem is to develop a computer based system or write a computer program
Defination:
Representing algorithms:
Pseudo codes are mixture of English statements and terms that are used
in programming. The programming terms may include: START, BEGIN, END, STOP, IF,
THEN, WHILE, ENDWHILE, REPEAT, FOR, UNTIL, DISPLAY, WRITE, READ, etc.
Algorithm Examples:
#include<stdio.h>
main()
{
int variable_A,variable_B,variable_temp;
variable_A=0;
variable_B=0;
variable_temp=0;
printf("Before swapping\n");
printf("******************\n");
printf("Value of variable A: %d\n",variable_A);
printf("Value of variable B: %d\n",variable_B);
variable_temp=variable_A;
variable_A=variable_B;
variable_B=variable_temp;
printf("After swapping\n");
printf("******************\n");
printf("Value of variable A: %d\n",variable_A);
printf("Value of variable B: %d\n",variable_B);
}
Track the number of times reading is done by setting up a counter.
When 6 numbers have been read, stop.
Algorithm
Start
Setup variables: Number, Count
Initialize variables: Number:=0; Count:=0;
Read Number
Display Number
Increase Count by 1
If Count<6 Repeat from 4
Stop
#include<stdio.h>
main()
{
int count,number;
count=0;
number=0;
do
{
printf("Enter number: ");
scanf("%d",&number);
count++;
}
while(count<6);
}
while(condition)
{
statements;
#include<stdio.h>
main()
{
int count,number;
count=0;
number=0;
while(count<6)
{
printf("Enter number: %d",count+1);
scanf("%d",&number);
count++;
}
}
while(condition)
{
statement(s);
}
do
{
statement(s);
}
while(condition);
#include<stdio.h>
main()
{
int count,number;
number=0;
for(count=0;count<6;count++)
{
printf("Enter number %d: ",count+1);
scanf("%d",&number);
#include<stdio.h>
main()
{
int count,number,sum;
count=0;
number=0;
sum=0;
while(count<6)
{
printf("Enter number %d: ",count+1);
scanf("%d",&number);
#include<stdio.h>
main()
{
int count,number,sum,number_of_items;
count=0;
number=0;
sum=0;
while(count<number_of_items)
{
printf("Enter number %d: ",count+1);
scanf("%d",&number);
printf("The number is: %d\n",number);
count++;
sum=sum+number;
FUNCTIONS
#include<stdio.h>
main()
{
int x,y,sum,diff,mult,div;
x=89;
y=36;
sum=x+y;
diff=x-y;
mult=x*y;
div=x/y;
Defination:
It is a sub program that is called to perform
a particular task. The task can be simple or complex.
Include:sqrt(),pow(),sin(),tan(), printf(),scanf(),gets(),
puts(),strcpy(),strcat(),stcmp() etc
#include<stdio.h>
main()
{
char name[30];
#include<stdio.h>
main()
{
char name[30];
SYNTAX
return_data_type function_name(arg1,arg2,..)
{
//function body
}
where:
1. return_data_type can be int,float,double,char,
void(valueless)
2. function_name is any valid identifier
3. arg1,arg2... etc are values that the function requires to
perform the task. They are optional.
if returning int,float,double,char
float function_name(arg1,arg2,..)
{
//function body
return value;
}
c=sum(a,b);
printf("The answer = %d\n",c);
return 0;
}
main()
{
int a,b;
sum(a,b);
return 0;
}
#include<stdio.h>
float volume(float r, float h)
{
float vol;
vol=3.14*r*r*h;
return vol;
}
main()
{
int rad,height,vol;
vol=volume(rad,height);
printf("The answer = %d\n",vol);
return 0;
}
sum(a,b);
return 0;
}
void sum(int x, int y)
{
int z;
z=x+y;
printf("The answer = %d\n",z);;
}
DEFINATIONS:
1.FUNCTION PROTOTYPE
- IT IS A STATEMENT THAT TELLS THE MAIN PROGRAM THE NAME
OF THE SUB PROGRAM(FUNCTION),IT'S ARGUMENTS AND ITS
RETURN TYPE.
IT MUST BE TERMINATED BY A SEMICOLON
2. FUNCTION CALL
-IT IS THE STATEMNT THAT IS USED BY THE CALLER
(CALLING PROGRAM) TO CALL THE SUB PROGRAM(FUNCTION)
3. FUNCTION HEADING/HEADER
-THIS IS THE HEADING OF THE FUNCTION
#include<stdio.h>
float volume(float r, float h);//function prototype
main()
{
int rad,height,vol;
vol=volume(rad,height);//function call
printf("The answer = %d\n",vol);
return 0;
}
EXAMPLE 1:
#include<stdio.h>
int volume(int r, int h);//function prototype
main()
{
int rad,height,vol;
printf("Enter the radius: ");
scanf("%d",&rad);
vol=volume(rad,height);//function call
vol=3.14*r*r*h;
return vol;
//STATEMENT 1,2,3- FUNCTION BODY
}
CALL(PASS) BY REFERENCE
SYNTAX
and
return_data_type function_name(int &x, int &y)
{
}
#include<stdio.h>
int volume(int &r, int &h);//function prototype
main()
{
int rad,height,vol;
vol=volume(rad,height);//function call
vol=3.14*r*r*h;
return vol;
//STATEMENT 1,2,3- FUNCTION BODY
}
SUMMARY
1.DEFINATION A FUNCTION
2.ADVANTAGES AND DISADVANTAGES OF A FUNCTION
3.SYNTAX OF A DEFINING A FUNCTION
4.FUNCTINAL CALL
5.FUNCTION PROTOTYPE
6.ACTUAL AND FORMAL PARAMETERS/ARGUMENTS
7.FUNCTION HEADER
8.FUNCTION DEFINATION(IMPLEMENTATION)
9.VOID AND NON-VOID FUNCTION
10. CALL(PASS) BY VALUE
11. CALL(PASS) BY REFERENCE
EXERCISE
A FUNCTION IS REQUIRED THAT ACCEPT THE AVERAGE MARKS A
STUDENT GETS BASED ON FOUR UNITS AND THEN GRADE THE STUDENT
USING THE FOLLOWING GRADING TABLE BELOW.
#include<iostream>
using namespace std;
char get_grade(int avg)
{
char grade;
if(avg>=70 && avg<=100)
grade='A';
else
grade='E';
return grade;
}
main()
{
int mk1,mk2,mk3,total,avg;
char grd,name[40],regNum[25];
cout<<"English: ";
cin>>mk2;
cout<<"Chemistry: ";
cin>>mk3;
total=mk1+mk2+mk3;
avg=total/3;
grd=get_grade(avg);
cout<<"Results slip for May - August 2020 Examination"<<endl;
cout<<"------------------------------------------------"<<endl;
cout<<"Registration Number: "<<regNum<<endl;
cout<<"English: "<<mk2<<endl;
cout<<"Chemistry: "<<mk3<<endl;
EXAMPLE 1:
#include<iostream>
using namespace std;
main()
{
show_grade();
return 0;
}
int input()
{
int mk1,mk2,mk3,mk4,sum;
sum=mk1+mk2+mk3+mk4;
int compute()
{
int avg,sum;
sum=input();
avg=sum/4;
char grade()
{
char grd;
int avg;
avg=compute();
else
grd='E';
return grd;
}
void show_grade()
{
char grd;
grd=grade();
cout<<"\nGrade : "<<grd<<endl;
}
EXAMPLE 2:
#include<iostream>
using namespace std;
//function prototype
void compute();
float get_mean(float,float,float);
char get_grade(float);
float validate();
void show(float,char);
//main function
main()
{
compute();
}
float validate()
{
float marks;
cin>>marks;
while(marks<0 || marks>100)
{
cout<<"Invalid marks entered. Try again: ";
cin>>marks;
}
return marks;
}
else
grade='E';
return grade;
void compute()
{
float math,eng,comp,mean;
char grade;
mean=get_mean(math,eng,comp);
grade=get_grade(mean);
show(mean,grade);
}
/*A PROGRAM TO INPUT MARKS OBTAINED BY EACH STUDENT
IN THREE SUBJECTS AND THEN COMPUTE THE GRADE OF EACH
STUDENT*/
#include<iostream>
using namespace std;
//Functions prototype
void compute();
float get_mean(float mk1, float mk2, float mk3);
char get_grade(float avg);
float input();
void show(float avg, char grade);
//main function
int main()
{
int count, number;
for(count=0; count<number;count++)
{
cout<<"\nEnter marks for student: "<<count+1<<endl;
cout<<"-----------------------"<<endl;
compute();
}
//Function to do computations
void compute()
{
//declarations
float maths,english,computer,mean;
char grade;
//input each mark
mean=get_mean(maths,english,computer);
grade=get_grade(mean);
show(mean,grade);
mean_marks=(mk1+mk2+mk3)/3;
return mean_marks;
}
else
grd='E';
return grd;
float input()
{
float marks;
cin>>marks;
//while mark is invalid,try inputting again
while(marks<0 || marks>100)
{
cout<<"\n Invalid marks. Try again: ";
cin>>marks;
}
return marks;
}
void and non-void functions
}
scenario 1(non-void function)
float accountant(var money)
{
float total;
count the money;
total=sum of the money;
return total;
}
main()
{
declare sum;
collect the money;
sum=accountant(money);
cout<<total money = sum
main()
{
float money;
I collect the money;
accountant(money);
}
void accountant()
{
collect the money;
count the money;
total=sum of the money;
cout<<The total is total;
}
main()
{
accountant();
Example 1:
A function that accept length and width, computes
the area and return the area to the caller;
#include<iostream>
using namespace std;
main()
{
float l,w,ar;
cout<<"Enter the length: ";
cin>>l;//10
#include<iostream>
using namespace std;
main()
{
float avg;
char grade;
cout<<"Enter the average marks: ";
cin>>avg;
grade=get_grade(avg);
cout<<"The average marks: "<<avg<<endl;
cout<<"The grade is: "<<grade<<endl;
return 0;
}
return grd;
}
#include<iostream>
using namespace std;
float rect(float *l,float *w);
main()
{
float length,width, area;
cout<<"Enter the length: ";
cin>>length;
rect(&length,&width);
}
float rect(float *l,float *w)
{
//float area;
*l=*l+10;
*w=*w+20;
cout<<"Inside the function call: "<<endl;
cout<<"Length = "<<*l<<endl;
cout<<"Width = "<<*w<<endl;
#include<iostream>
using namespace std;
main()
{
show_grade();
return 0;
}
int input()
{
int mk1,mk2,mk3,mk4,sum;
sum=mk1+mk2+mk3+mk4;
int compute()
{
int avg,sum;
sum=input();
avg=sum/4;
char grade()
{
char grd;
int avg;
avg=compute();
else
grd='E';
return grd;
}
void show_grade()
{
char grd;
grd=grade();
cout<<"\nGrade : "<<grd<<endl;
}
#include<iostream>
using namespace std;
//function prototype
void compute();
float get_mean(float,float,float);
char get_grade(float);
float validate();
void show(float,char);
//main function
main()
{
compute();
}
float validate()
{
float marks;
cin>>marks;
while(marks<0 || marks>100)
{
cout<<"Invalid marks entered. Try again: ";
cin>>marks;
}
return marks;
}
else
grade='E';
return grade;
}
void compute()
{
float math,eng,comp,mean;
char grade;
mean=get_mean(math,eng,comp);
grade=get_grade(mean);
show(mean,grade);
ARRAY:
OBJECTIVES:
Students should be able to know ,understand, demonstrate how to:
1.Declaring Arrays
2.Initializing Arrays
3.Accessing Array Elements
4.Arrays in C
Create variable
Syntax:
datatype identifier;
int x;
Initialization of variables:
int x=23;
int x1,x2,x3,x4,x5;
int x[5];
char name[40];
float numbers[5];
Defination:
C/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.
Declaring Arrays
To declare an array in C/C++, the programmer specifies the type of the elements
and the number of elements required by an array as follows:
DECLARING ARRAYS
SYNTAX:
EXAMPLE:
int x1,x2,x3,x4,x5;//not using arrays
int x[5];//using arrays
double balance[10];
Initializing Arrays
You can initialize C/C++ array elements either one by one or using a single
statement as follows:
You will create exactly the same array as you did in the previous example.
datatype identifier;
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0.
Array with 4th index will be 5th, i.e., last element because all arrays have 0 as
the index of their first element which is also called base index. Following is the
pictorial representation of the same array we discussed above:
An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For
example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value
to salary variable. Following is an example, which will use all the abovementioned
three concepts viz. declaration, assignment and accessing arrays:
int x1,x2,x3,x4,x5;
x1=4;
x2=5;
x3=6;
x4=7;
x5=9;
int x[5];
scanf(�Enter value 1: %d\n�,x[0]);
scanf(�Enter value 2: %d\n�,x[1]);
scanf(�Enter value 3: %d\n�,x[2]);
scanf(�Enter value 4: %d\n�,x[3]);
scanf(�Enter value 5: %d\n�,x[4]);
#include<stdio.h>
main()
{
int x[5];
x[0]=14;
x[1]=15;
x[2]=16;
x[3]=17;
x[4]=18;
printf(�Value 1: %d\n�,x[0]);
printf(�Value 2: %d\n�,x[1]);
printf(�Value 3: %d\n�,x[2]);
printf(�Value 4: %d\n�,x[3]);
printf(�Value 5: %d\n�,x[4]);
#include<stdio.h>
main()
{
double balance[5]={1000.0, 2.0, 3.4, 7.0, 50.0};
balance[0]=1200.00;
balance[1]=36.45;
balance[2]=96.35;
balance[3]=58.25;
balance[4]=45.00;
printf("Second display from the assigned values\n");
printf("--------------------------------------\n");
printf("First value = %0.2Lf\n",balance[0]);
printf("Second value = %0.2lf\n",balance[1]);
printf("Third value = %0.2lf\n",balance[2]);
printf("Fourth value = %0.2lf\n",balance[3]);
printf("Fifth value = %0.2lf\n",balance[4]);
#include<stdio.h>
main()
{
double balance[5]={1000.0, 2.0, 3.4, 7.0, 50.0};
int index;
printf("First display from the initial values\n");
printf("--------------------------------------\n");
for(index=0; index<5;index++)
{
printf("The value = %0.2Lf\n",balance[index]);
}
balance[0]=1200.00;
balance[1]=36.45;
balance[2]=96.35;
balance[3]=58.25;
balance[4]=45.00;
printf("Second display from the assigned values\n");
printf("--------------------------------------\n");
for(index=0; index<5;index++)
{
printf("The value = %0.2Lf\n",balance[index]);
}
}
#include<stdio.h>
main()
{
double balance[5]={1000.0, 2.0, 3.4, 7.0, 50.0};
int index;
printf("First display from the initial values\n");
printf("--------------------------------------\n");
for(index=0; index<5;index++)
{
printf("The value %d = %0.2Lf\n",index+1,balance[index]);
}
balance[0]=1200.00;
balance[1]=36.45;
balance[2]=96.35;
balance[3]=58.25;
balance[4]=45.00;
printf("Second display from the assigned values\n");
printf("--------------------------------------\n");
for(index=0; index<5;index++)
{
printf("The value %d = %0.2Lf\n",index+1,balance[index]);
}
for(index=0; index<5;index++)
{
printf("Enter the value %d: ",index+1);
scanf("%lf",&balance[index]);
}
#include<stdio.h>
main()
{
int x[500];
printf("value 1: ");
scanf("%d",&x[0]);
printf("value 2: ");
scanf("%d",&x[1]);
printf("value 3: ");
scanf("%d",&x[2]);
printf("value 4: ");
scanf("%d",&x[3]);
printf("value 5: ");
scanf("%d",&x[3]);
printf("Value 1: %d\n",x[0]);
printf("Value 2: %d\n",x[1]);
printf("Value 3: %d\n",x[2]);
printf("Value 4: %d\n",x[3]);
printf("Value 5: %d\n",x[4]);
}
#include<stdio.h>
main()
{
int x[500],total,avg;
printf("value 1: ");
scanf("%d",&x[0]);
printf("value 2: ");
scanf("%d",&x[1]);
printf("value 3: ");
scanf("%d",&x[2]);
printf("value 4: ");
scanf("%d",&x[3]);
printf("value 5: ");
scanf("%d",&x[4]);
total=x[0]+x[1]+x[2]+x[3]+x[4];
avg=total/5;
printf("Value 1: %d\n",x[0]);
printf("Value 2: %d\n",x[1]);
printf("Value 3: %d\n",x[2]);
printf("Value 4: %d\n",x[3]);
printf("Value 5: %d\n",x[4]);
#include<stdio.h>
main()
{
int x[5],i,total=0,avg;
for(i=0;i<5;i++)
{
printf("Value %d: ",i+1);
scanf("%d",&x[i]);
}
for(i=0;i<5;i++)
{
printf("Value %d: %d\n", i+1,x[i]);
}
#include<stdio.h>
main()
{
int x[5],i,total;
printf("STUDENT MARKS\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("Marks %d: ",i+1);
scanf("%d",&x[i]);
total=total+x[i];
}
printf("\nSTUDENT TRANSCRIPT FOR MAY SEMESTER\n");
printf("*************************************\n");
for(i=0;i<5;i++)
{
printf("Marks %d: %d\n", i+1,x[i]);
}
#include<stdio.h>
main()
{
int x[5],i,total=0,avg;
printf("STUDENT MARKS\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("Marks %d: ",i+1);
scanf("%d",&x[i]);
total=total+x[i];
}
avg=total/5;
printf("\nSTUDENT TRANSCRIPT FOR MAY SEMESTER\n");
printf("*************************************\n");
for(i=0;i<5;i++)
{
printf("Marks %d: %d\n", i+1,x[i]);
}
#include<stdio.h>
main()
{
int x[5],i,total=0,avg;
char grade;
printf("STUDENT MARKS\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("Marks %d: ",i+1);
scanf("%d",&x[i]);
total=total+x[i];
}
avg=total/5;
}
else if(avg>=60 && avg<70)
{
grade='B';
}
else if(avg>=50 && avg<60)
{
grade='C';
}
else if(avg>=40 && avg<50)
{
grade='D';
}
else
{
printf("Invalid marks!!!!");
printf("Grade: %c\n",grade);
if(avg>=50)
{
printf("RESULT: PASS\n");
printf("Proceed to next stage\n");
}
else
{
printf("RESULT: FAIL\n");
printf("Rewind the stage\n");
}
}
int x[5];
x[0]=7;
x[1]=5;
x[2]=6;
x[3]=8;
x[4]=9;
for(initial value;condition;update)
{
statement(s)
}
#include<stdio.h>
main()
{
int marks[5],i;
printf("Enter marks obtained\n");
printf("********************\n");
for(i=0;i<5;i++)
{
printf("marks %d: ",i+1);
scanf("%d",&marks[i]);
printf("Marks obtained\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("marks %d: %d\n",i+1,marks[i]);
return 0;
}
Example 2: A program that inputs and outputs 5 marks and compute
the sum of the 5 marks
#include<stdio.h>
main()
{
int marks[5],i,sum=0;
printf("Enter marks obtained\n");
printf("********************\n");
for(i=0;i<5;i++)
{
printf("marks %d: ",i+1);
scanf("%d",&marks[i]);
sum=sum+marks[i];
printf("\nMarks obtained\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("marks %d: %d\n",i+1,marks[i]);
}
printf("The total marks = %d\n",sum);
return 0;
#include<stdio.h>
main()
{
int marks[5],i,sum=0,avg;
printf("Enter marks obtained\n");
printf("********************\n");
for(i=0;i<5;i++)
{
printf("marks %d: ",i+1);
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
avg=sum/5;
printf("\nMarks obtained\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("marks %d: %d\n",i+1,marks[i]);
}
printf("The total marks = %d\n",sum);
printf("The avearge marks = %d\n",avg);
return 0;
}
Example 3: A program that inputs 5 marks obtained in an
exam compute the sum and average and then outputs.
the sum of the 5 marks plus the grade
#include<stdio.h>
main()
{
int marks[5],i,sum=0,avg;
char grade;
printf("Enter marks obtained\n");
printf("********************\n");
for(i=0;i<5;i++)
{
printf("marks %d: ",i+1);
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
avg=sum/5;
else
grade='E';
printf("\nMarks obtained\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("marks %d: %d\n",i+1,marks[i]);
}
printf("The total marks = %d\n",sum);
printf("The avearge marks = %d\n",avg);
printf("The grade = %c\n",grade);
return 0;
#include<stdio.h>
main()
{
int marks[5],i,sum=0,avg;
char grade;
printf("Enter marks obtained\n");
printf("********************\n");
for(i=0;i<5;i++)
{
printf("marks %d: ",i+1);
scanf("%d",&marks[i]);
while(marks[i]<0 || marks[i]>100)
{
printf("The marks must be btn 0 - 100\n");
printf("Please renter marks %d: ",i+1);
scanf("%d",&marks[i]);
}
sum=sum+marks[i];
}
avg=sum/5;
else
grade='E';
printf("\nMarks obtained\n");
printf("*************\n");
for(i=0;i<5;i++)
{
printf("marks %d: %d\n",i+1,marks[i]);
}
printf("The total marks = %d\n",sum);
printf("The avearge marks = %d\n",avg);
printf("The grade = %c\n",grade);
return 0;
EXAMPLE:
#include<iostream>
using namespace std;
main()
{
int x[5],i,sum=0,avg;
char grade;
cout<<"EXAMS DONE"<<endl;
cout<<"------------"<<endl;
for(i=0;i<5;i++)
{
avg=sum/5;
}
cout<<"The sum: "<<sum<<endl;
cout<<"The average: "<<avg<<endl;
cout<<"Grade: "<<grade<<endl;
return 0;
datatype identifier;
int x;
int num1,num2;
int num1,num2,num3,num4,num5,sum;
int num1,num2,num3,......num20,sum;
#include<stdio.h>
main()
{
int num1,num2,num3,num4,num5,sum;
sum=num1+num2+num3+num4+num5;
Syntax:
data_type identifier[SIZE];
where:
int number[5];
number[0]=10;
number[1]=20;
number[2]=30;
number[3]=40;
number[4]=50;
#include<stdio.h>
main()
{
int num[5],sum;
sum=num[0]+num[1]+num[2]+num[3]+num[4];
for(initial value;condition;update)
{
statement(s);
}
for(index=0;index<5;index++)
{
printf("Enter a number: ");
scanf("%d",num[index]);
}
#include<stdio.h>
main()
{
int num[5],index,sum;
for(index=0;index<5;index++)
{
printf("Enter a number: ");
scanf("%d",&num[index]);
}
sum=num[0]+num[1]+num[2]+num[3]+num[4];
#include<stdio.h>
main()
{
int num[5],index,sum;
for(index=0;index<5;index++)
{
printf("Enter number %d: ",index+1);
scanf("%d",&num[index]);
}
sum=num[0]+num[1]+num[2]+num[3]+num[4];
for(index=0;index<5;index++)
{
printf("Enter number %d: ",index+1);
scanf("%d",&num[index]);
sum=sum+num[index];
}
#include<stdio.h>
main()
{
int num[5],index,sum=0,avg;
for(index=0;index<5;index++)
{
printf("Enter number %d: ",index+1);
scanf("%d",&num[index]);
sum=sum+num[index];
}
}
avg=sum/5;
printf("The sum = %d\n",sum);
printf("The Average = %d\n",avg);
}
#include<stdio.h>
main()
{
int num[5],index,sum=0,avg;
for(index=0;index<5;index++)
{
printf("Enter number %d: ",index+1);
scanf("%d",&num[index]);
sum=sum+num[index];
}
}
avg=sum/5;
printf("The sum = %d\n",sum);
printf("The Average = %d\n",avg);
}
Structures:
Meaning of structs
Defining a struct
Defining Members
Accessing members
Solved Problem
Exercises
Main difference with an array is that it can hold data of different types. Structs
are also known as records in some programming languages because of their structure.
A part from storing data of different types, structs also store operations that can
be performed on that data. A struct therefore combines both data and operations
that
concern objects of its type.
Example:Assume the following details are stored for each person: Person's name,
salary and contacts. We can define a struct to store the above three details
syntax:
struct struct_name
{
members;
};
#include<stdio.h>
main()
{
float length,area;
int width;
length=4.5;
width=4;
area=length*width;
cout<<"Area = "<<area<<endl;
}
1.Create structure
2.Use the structure to declare a variable
3.Access the elements of the structure
use the (.) operator to access the elements of the structure
rect.length=4.5;
rect.width=4;
#include<stdio.h>
struct Rectangle
{
float length;
int width;
};
main()
{
struct Rectangle rect;
float area;
rect.length=4.5;
rect.width=4;
area=rect.length*rect.width;
Example:
#include<stdio.h>
struct Rectangle
{
float length
int width;
};
main()
{
struct Rectangle rect;
float area;
area=rect.l*rect.w;
Example 2:
#include<stdio.h>
struct Student
{
char name[40];
int age;
};
main()
{
struct Student s;
printf("Enter the name: ");
gets(s.name);
#include<stdio.h>
#include<string.h>
struct Student
{
char name[40];
int age;
};
main()
{
struct Student s;
strcpy(s.name,"Timothy Agevi");
s.age=19;
printf("The name: %s\n",s.name);
printf("The age: %d\n",s.age);
}
intance_name.member1=90;
instance_name.member2=89;
EXAMPLE 1:
#include<iostream>
struct student
{
int age;
char name[20];
char gender[10];
char regNumber[30];
};
main()
{
struct student stud;
stud.age=23;
strcpy(stud.name,"Timoth Agevi");
strcpy(stud.gender,"Male");
strcpy(stud.regNumber,"sct221-c002-0001/2019");
}
main
{
struct student stud,stud2,stud3;
cout<<"Age: %d\n",stud.age ;
cout<<"Name: %s\n",stud.name;
cout<<"Gender: %s\n",stud.gender;
cout<<"Reg Number: %s\n",stud.regNumber;
cout<<"Age: %d\n",stud2.age ;
cout<<"Name: %s\n",stud2.name;
cout<<"Gender: %s\n",stud2.gender;
cout<<"Reg Number: %s\n",stud2.regNumber;
cout<<"Age: %d\n",stud3.age ;
cout<<"Name: %s\n",stud3.name;
cout<<"Gender: %s\n",stud3.gender;
cout<<"Reg Number: %s\n",stud3.regNumber;
}
#include<stdio.h>
struct person
{
char name[30];
char contacts[30];
float salary;
};
main()
{
struct person pr;
pr.salary=pr.salary*70.00/100.00;
printf("\nUSER DETAILS ENTRY\n");
printf("*******************\n");
printf("Name: %s\n",pr.name);
printf("Contacts: %s\n",pr.contacts);
printf("Net Salary: Kshs. %.2f\n",pr.salary);
}
#include<stdio.h>
#include<string.h>
struct Product
{
int ProductCode;
char ProductDescription[50];
float UnitPrice;
};
main()
{
int quantity;
float totalPrice;
struct Product Sugar;
Sugar.UnitPrice=54.50;
Sugar.ProductCode=1;
strcpy(Sugar.ProductDescription,"Mumias Sugar");
totalPrice=quantity*Sugar.UnitPrice;
printf("-------------------------------------------------------------------------\n
");
printf("%d\t\t %s\t\t %.2f\t\t %d\t %.2f\t
\n",Sugar.ProductCode,Sugar.ProductDescription,Sugar.UnitPrice,quantity,totalPrice)
;
}
#include<stdio.h>
#include<string.h>
struct Product
{
int ProductCode;
char ProductDescription[50];
float UnitPrice;
};
main()
{
int quantity,quantity1;
float totalPrice,totalPrice2;
struct Product Sugar,Milk;
Sugar.ProductCode=1;
Sugar.UnitPrice=54.50;
Milk.ProductCode=2;
Milk.UnitPrice=45.50;
strcpy(Sugar.ProductDescription,"Mumias Sugar");
strcpy(Milk.ProductDescription,"Fresha Milk");
totalPrice=quantity*Sugar.UnitPrice;
totalPrice2=quantity1*Milk.UnitPrice;
printf("-------------------------------------------------------------------------\n
");
printf("%d\t\t %s\t\t %.2f\t\t %d\t %.2f\t
\n",Sugar.ProductCode,Sugar.ProductDescription,Sugar.UnitPrice,quantity,totalPrice)
;
printf("%d\t\t %s\t\t %.2f\t\t %d\t %.2f\t
\n",Milk.ProductCode,Milk.ProductDescription,Milk.UnitPrice,quantity1,totalPrice2);
}
EXAMPLE:
WE COULD INVENT A DATA TYPE CALLED GENDER WHICH CAN HAVE
TWO2 POSSIBLE VALUES - MALE OR FEMALE
SYNTAX:
enum enum_name
{
value1,
value2,
value3
};
Example:
enum gender
{
male,female
};
struct student
{
int age;
char name[20];
char regNumber[20];
enum gender g;
};
main
cout<<"Age: %d\n",stud.age ;
cout<<"Name: %s\n",stud.name;
cout<<"Gender: %d\n",stud.g;
ifstud.g==0
cout<<"You are a male\n";
else ifstud.g==1
cout<<"You are a female\n";
else
cout<<"Gender not known\n";
return 0;
}
#include<iostream>
enum emp_dept
{
assembly,
manufacturing,
accounts,
stores
};
struct employee
{
char name[30];
int age;
float basic_salary;
enum emp_dept department;
};
main
{
struct employee emp;
cout<<"EMPLOYEE DETAILS\n";
cout<<"-------------------\n ";
cout<<"Age: %d\n",emp.age ;
cout<<"Name: %s\n",emp.name;
cout<<"Basic salary: %d\n",emp.basic_salary;
cout<<"Department: %d\n",emp.department;
ifemp.department==0
cout<<"Department is assembly\n";
else if emp.department==1
cout<<"Department is manufacturing\n";
else if emp.department==2
cout<<"Department is accounts\n";
else if emp.department==3
cout<<"Department is stores\n";
TYPEDEF
*******
THIS IS A DATA TYPE THAT ALLOW USERS TO DEFINE NEW DATA TYPES
THAT ARE EQUIVALENT TO EXISTING DATA TYPES.ONCE A USER
DEFINE TYPE HAS BEEN ESTABLISHED, THE NEW VARIABLES, ARRAYS
ETC. CAN BE DECLARED IN TERMS OF THIS NEW DATA TYPE.
SYNTAX
int x;
age height;