0% found this document useful (0 votes)
413 views152 pages

Introduction To Programming Tutorials

The document provides definitions and explanations of key concepts in computer programming including: - A program is a set of step-by-step instructions for a computer to perform a task. Programming involves writing programs to solve problems. - Programming languages include rules and symbols to write programs. Examples are C, Java, and Python. - The programming process involves identifying a problem, designing an algorithmic solution, coding the program, testing it, and documenting it.

Uploaded by

Wangechi
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
413 views152 pages

Introduction To Programming Tutorials

The document provides definitions and explanations of key concepts in computer programming including: - A program is a set of step-by-step instructions for a computer to perform a task. Programming involves writing programs to solve problems. - Programming languages include rules and symbols to write programs. Examples are C, Java, and Python. - The programming process involves identifying a problem, designing an algorithmic solution, coding the program, testing it, and documenting it.

Uploaded by

Wangechi
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 152

BIT 2104/ICS 2102: Introduction to Computer programming and Algorithm

*********************************************************************
Basic Concepts of Programming

Program
Programming languages
Programmer
Software
Computer vs Human beings

Definitions:

PROGRAM: Is a set of step by step instructions written in a language that the


computer
can interpret and understand. They are used to guide a computer to perform a task
(simple or complex).

Programming Problem: - A task that requires a program to be written.

Programming language: - This is a program with a special role i.e. it enables us


to come up with other programs. Has instructions that enable us to write programs
or modify an existing program.C,C++,JAVA,PHP, JSP,C#,JAVASCRIPT ETC
Programming language: Rules and Symbols that are used to write a program

They have features of language


Grammar : SYNTAX
Vocabulary
Interpretation/ meaning: SEMANTICS

Programming:- This is the art of formulating a set of instructions to enable the


computer to perform certain tasks.

Programming Methodology - Various ways of formulating a program.

Software: - A program that has been debugged,tested,documented and ready to be


used.

Procedural programming language:

What is a procedural programming language?

A procedural language is a computer programming language that follows, in order, a


set of commands.
Examples of computer procedural languages are BASIC, C, FORTRAN, and Pascal.

or

Procedural programming is a list or set of instructions telling a computer what to


do step by step and
how to perform from the first code to the second code.

Procedural programming languages include C, Go, Fortran, Pascal, and BASIC.

What is the difference between procedural and object oriented programming?


One of the most important characteristics of procedural programming is that it
relies on procedures
that operate on data - these are two separate concepts. In object-oriented
programming, these two concepts are bundled into objects.
This makes it possible to create more complicated behavior with less code.

What is an object in object oriented programming?

In the object-oriented programming paradigm, "object" refers to a


particular instance of a class where the object can be a combination of
variables, functions, and data structures.

PROGRAM/SOFTWARE LIFE CYCLE(STAGES OF PROGRAM DEVELOPMENT)

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.

3.Coding the program:


Involves converting the design specification(the algorithm) into actual computer
instructions
in the computer language to be used.
If sufficient care has been taken at the design stage, coding is an almost
mechanical process
for an experienced programmer since most of the hard work of analyzing the problem
and breaking
it into a sequence of small, simple steps has already been done during the design
stage.

4.Testing and Debugging:


Debugging is the detection and correction of errors that may exist in the program.
The only
way of compltely confident that a program will behave as expected, under all
circumstances
that conceivably arise, is to test the program thoroughly before implementing it.
Program
testing includes creating test data designed to produce predictable output.

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.

7.Maintenance and Evaluation:

QUALITIES OF A GOOD PROGRAM

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;

printf("The area = %f\n",area);

d)Modularization: Split your program to make it easier to understand.This is always


achieved
by including functions in your program.Modularizing a program, reduces the effort
required
later to change the program since changes need only to be made to the module
whose
functinality changes or if a new feature os to be added then the new module can
be added.
Testing and debugging also becomes easier with small independent modules.
e)Spacing
#include<stdio.h>
main()
{
float length,width,area;

length=42.345;

width=31.344;

area=length*width;

printf("The area = %f\n",area);

}
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.

Good programming practice

a)Apply the computer problem solving steps:


-Identify and study problem
-Formulate and represent a solution to the problem (Algorithm)
-Use any convection to represent the algorithm
-Check that the algorithm works
-Write the code (program)
-Test and document code
-Run program
b)Plan the work
c)Document your work

#include<stdio.h>
#include<math.h>

main()
{
float number;
float answer;//This is the declaration of variables

printf("Enter any number: ");


scanf("%f",&number);

/* This is the part of processsing


or where the inputs are transformed into
output*/
answer=sqrt(number);

printf("The result is %.2f\n",answer);

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;

b)SEMANTIC ERRORS/RUNTIME ERRORS- Caused when the computer is not able to


understand
the meaning of a statement.And thus is not able to do what it is being instructed
to do.

Causes

i)Division by zero
ii)Computing the square root of a negative number
iii)Endless loops

c)LOGICAL ERRORS - The program is giving erronous result.


Causes

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.

PROGRAMMING TESTING STAGES


There are several stages in testing 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

2.TRANSLATOR SYSTEM CHECKING

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.

3.PROGRAM RUN WITH TEST DATA


Test data is created designed to produce predictable output. The program is then
run using
this data and its output is compared with the predictable output. Test data should
include
all important variations and extremes or including data errors to ensure that the
program
doesn't grind to an halt if incorrect data is read in.
4. DIAGNOSTIC PROCEDURES
For complex programs diagnostics procedures such as trace routines,may be used to
find logical errors.
A trace prints result at each processing step to enable errors to be detected
quickly. If a
trace routine is not available the programmer inserts instructions in the program
to print
results at key points.
Problem:

5. SYSTEM TEST WITH ACTUAL DATA

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.

Add any two numbers.

solution:

- Create a space in your brain


- Prompt the user to enter the numbers
- Enter the numbers
- Compute the sum
- Display the result

#include<stdio.h>
main()
{

float num1,num2,sum;

printf("Enter the first number: ");


scanf("%f",&num1);

printf("Enter the second number: ");


scanf("%f",&num2);

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);

Good Coding Techniques

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:

a)Line comments//bbbbbbbbb vbbb bbbbb


b)Block comments /*ffffffff
ggggggggg */

ii)Line spacing
Leaving empty lines between sections of codes so as to visibly distinguish among
the individual
sections.

iii) Indenting code

iv)Use of meaningful identifiers

01010110 sub 10100010

#include<iostream>
#include<math.h>
using namespace std;

main()
{
float number,result;

cout<<"Enter the number: ";


cin>>number;

result=sqrt(number);

cout<<"The number = "<<number<<endl;


cout<<"The result = "<<result<<endl;

A program is required that is supposed to grade


a student based on the average of 4 subjects obtained
in an exam. Use the following grading system to grade the student.

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

Variable and Data type


***********************
Variable is a memory space that hold or store
data temporarly.
Data type is the kind of data to be stored in
the main memory.
-numbers - whole numbers,numbers with decimal points.
-characters

Syntax:

data_type identifier;

Data type: Kind of value to be stored in a variable


-integer data - whole numbers, both -ve and +ve.
. int
. short int
. long int
. signed short int - both +ve and -ve whole numbers
. unsigned short int - for +ve whole numbers only
. signed long int - both +ve and -ve whole numbers
. unsigned long int - for +ve whole numbers only

In laymen's terms an unsigned int is an integer that can not


be negative and thus has a higher range of positive values that it can assume.
A signed int is an integer that can be negative but has a lower positive range
in exchange for more negative values it can assume

65.999

short int num;


num=65.999;

--- short int


------ int
------------ long int

floating numbers - numbers with decimal points


-float
-double - exponential form
56.699
character data

-char

volume=PI*r*r*h

Syntax for creating memory space

data_type identifier;

int x;

float basic_salary;
float basicsalary;

int customer_account_number;
int customeraccountnumber;

int customerAccountNumber;

int customer account number;


float num1;
float num2;

float basic_salary;

float num1,_num2;

Rules of naming identifiers


1. Can contain letters, digits, or _. Any other xter not allowed.
2. can only start with a letter or _
3. Spaces are not allowed

This identifier is wrong: float basic salary;

4. Keywords or reserved words can not be used as variable names


5. Case sensitive Example: a is not same as A
6. Identifier must be unique within a program.

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;

Constant variable is that space that holds or


store values that never change.

Syntax:

const datatype IDENTIFIER = value;

const float PI = 3.147;


PI=3.456;

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);

printf("The amount is Kshs. %.2f",amount);

printf("So,the balance after %d years is approximately $ %.2f.",t,amount);


}

pow(x,y);
dddddd ggggggggg gggg

#include<stdio.h>

main()
{

float num1,num2,sum;

printf("Enter the first number: ");

scanf("%f",&num1);

printf("Enter the second number: ");

scanf("%f",&num2);

sum=num1+num2;

printf("%f",sum);

printf("The sum is %f",sum);

printf("The sum of %f and %f is %f",num1,num2,sum);

#include<stdio.h>

main()
{

float num1,num2,sum;

printf("Enter the first number: ");

scanf("%f",&num1);

printf("Enter the second number: ");

scanf("%f",&num2);

sum=num1+num2;

printf("%f",sum);

printf("The sum is %f",sum);

printf("The sum of %f and %f is %f",num1,num2,sum);

#include<stdio.h>
main()
{
char x;
x=getchar();
putchar(x);

#include<stdio.h>
main()
{
char x[40];

printf("Enter your full names: ");


scanf("%c",&x);

printf("My full names are: %c\n",x);

INPUTTING AND OUTPUTTING

input - scanf(),gets()
output - printf(),puts()

Format of a C program

#include <stdio.h>//pre-processor directive or header file that contains files for


input/output
main()
{

}
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);

printf("The sum of %d and %d is %d\n",num1,num2,result);


}

#include <stdio.h>
main()
{
int num1;
int num2;
int result;

printf("Enter the first number: ");


scanf("%d",&num1);

printf("Enter the second number: ");


scanf("%d",&num2)

result=num1+num2;

printf("%d\n",result);
printf("The sum is %d\n",result);

printf("The sum of %d and %d is %d\n",num1,num2,result);


}

#include <stdio.h>
main()
{

int marks;

printf("Enter the marks: ");


scanf("%d",&marks);

if(marks>=50)

prinft("YOU PASSED!! CONGRATS\n")

else

printf("YOU FAILED!!! YOU ARE DOOMED!!\n);


}

The answer is 68
%d or %i - int
%f or %lf - float
%e or %Lf - double
%c - char
%s string

The sum of 23 and 45 is 68


#include <stdio.h>
main()
{
int num1,num2,result;

num1=23;
num2=45;

result=num1+num2;

printf("The sum of %d and %d is %d\n",num1,num2,result);


}

scanf("%d",&num1);

#include <stdio.h>
main()
{
int num1,num2,result;

printf("Enter the first number: ");


scanf("%d",&num1);

printf("Enter the second number: ");


scanf("%d",&num2);

result=num1+num2;

printf("The sum of %d and %d is %d\n",num1,num2,result);


}

#include <stdio.h>

int num1,num2;
float result;

main()
{
int num1,num2;
float result;

printf("Enter the first number: ");


scanf("%d",&num1);

printf("Enter the second number: ");


scanf("%d",&num2);

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:

Write a program that accept the marks a student gets in 4 subjects,


computes the sum and the average.The program should also
accept the student's name and registration number.

#include<stdio.h>
main()
{
int mathematics,english,physics,geography,total_score,average_marks;
char name[50],regNumber[20];

printf("Marksheet for May - August 2015 Semester\n");


printf("-----------------------------------------\n");

printf("Full names: ");


gets(name);

printf("Registration number: ");


gets(regNumber);

printf("Enter Mathematics score: ");


scanf("%d",&mathematics);

printf("Enter English score: ");


scanf("%d",&english);

printf("Enter Physics score: ");


scanf("%d",&physics);

printf("Enter Geography score: ");


scanf("%d",&geography);

total_score=mathematics+english+physics+geography;

average_marks=total_score/4;

printf("\nTRANSCRIPT FOR MAY - AUGUST 2015 SEMESTER\n");


printf("------------------------------------------\n");

printf("FULL NAMES: %s\n",name);


printf("REGISTRATION NUMBER: %s\n",regNumber);

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);

printf("Average score: %d\n",average_marks);

}
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;

printf("The answer is %d\n ",answer);


}

#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));

printf("The monthly payment is Kshs. %.2f ",monthly_payment);


}

#include<stdio.h>
#include<math.h>
main()
{
float monthly_payment,p,rate,amount,r;
int n,t;

printf("Enter the principle amount in Kshs. ");


scanf("%f",&p);

printf("Enter the rate: ");


scanf("%f",&r);

printf("Enter the number of years: ");


scanf("%f",&t);

rate=(r/100)/12;
n=t*12;

monthly_payment=p*(((rate*pow(1+rate,n)))/(pow(1+rate,n)-1));

printf("The monthly payment is Kshs. %.2f ",monthly_payment);


}

#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;

printf("Enter the first number: ");


scanf("%f",&num1);

printf("Enter the second number: ");


scanf("%f",&num2);

result=num1+num2;

printf("The sum of %.3f and %.3f is %.3f\n",num1,num2,result);


}

#include<stdio.h>
main()
{
float num1,num2,sum;

printf("Enter the first number: ");


scanf("%f",&num1);

printf("Enter the second number: ");


scanf("%f",&num2);

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;

printf("Enter the principle amount in Kshs. ");


scanf("%f",&p);

printf("Enter the rate: ");


scanf("%f",&r);

printf("Enter the number of years: ");


scanf("%d",&t);

rate=(r/100)/12;
n=t*12;

monthly_payment=p*(((rate*pow(1+rate,n)))/(pow(1+rate,n)-1));

printf("The monthly payment is Kshs. %.2f ",monthly_payment);


}

#include <stdio.h>
main()
{
float height,radius,volume;

printf("Enter the radius: ");


scanf("%f",&radius);

printf("Enter the height: ");


scanf("%f",&height);
volume=3.14*radius*radius*height;

printf("The volume of a cylinder of height %.2f and radius %.2f is


%.2f\n",height,radius,volume);
}

Example 1: A program that adds, subtract, divide and multiply


two numbers.

#include<stdio.h>
main()
{
int num1,num2,add,sub,div,mult;

printf("Enter the first number: ");


scanf("%d",&num1);

printf("Enter the second number: ");


scanf("%d",&num2);

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';

printf("Enter any character: ");


scanf("%c",&letter);

printf("The character is %c\n",name);


return 0;
}

#include<stdio.h>
main()
{
char name;

name='A';
printf("The character is %c\n",name);
return 0;
}

#include<stdio.h>

main()
{
char name[50];

printf("Enter your name: ");;


gets(name);

printf("THE NAME IS %s\n",name);

puts(name);
return 0;
}

int x;

char x;
char name;

float y;

Array of character
-------------------

syntax:
datatype identifier[SIZE];

where the SIZE is an integer.

int x[10];

char name[40];

#include<stdio.h>
main()
{
char name[40];

printf("Enter your name: ");


scanf("%s",name);

printf("Your name is: %s\n",name);


return 0;
}

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);

printf("The square root of %.2f is %.2f\n",number,answer);


return 0;
}
x^y

pow(x,y)
#include<stdio.h>
#include<math.h>
main()
{
float num1,num2, answer;
printf("Enter base: ");
scanf("%f",&num1);

printf("Enter power: ");


scanf("%f",&num2);

answer=pow(num1,num2);

printf("The power of %f raised to %f is %f\n",num1,num2,answer);


return 0;
}

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));

printf("The balance after 6 months = Kshs. %.2f\n",total_amount);

return 0;
}

Example 2: A program that accepts the deposit amount saved in


a bank for a period of n years at the rate of r% p.a.
How much money will the person get by the end of the
nth year.

#include<stdio.h>
#include<math.h>
main()
{
float prin,n,rate,total_amount;//declaration of variable

printf("Enter the principle amount: Kshs. ");


scanf("%f",&prin);

printf("Enter the rate: ");


scanf("%f",&rate);

printf("Enter the number of years: ");


scanf("%f",&n);

total_amount = prin*(pow(1+rate/100,n));

printf("The principle amount = Kshs. %.2f\n",prin);


printf("The rate = %.0f\n",rate);
printf("The period = %.0f\n",n);
printf("The total amount = Kshs. %.2f\n",total_amount);

return 0;
}

p(1+r/100)^n = a

x^y

pow(base,power);
pow(1+r/100,n)

Example 3: A program that computes the two possible roots


of a
a qudratic equation using ax^2 +bx+ c=0

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);

printf("Enter the value of b: ");


scanf("%d",&b);

printf("Enter the value of c: ");


scanf("%d",&c);

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");
}
}

Basic Salary: Kshs. 20000.00


House Allowance: Kshs. 1000.00
Transport allowance: kshs. 750.00
Gross salary: Kshs. 21750.00
Tax Amount: Kshs. 300
Net Salary : kshs. 21450.00

#include<stdio.h>
main()
{
float basic_salary,tax,h_allow, t_allow, gross_income,
net_salary;

printf("Enter the basic salary: Kshs. ");


scanf("%f",&basic_salary);

h_allow=20.0/100.0*basic_salary;
t_allow=15.0/100.0*basic_salary;

gross_income = basic_salary + h_allow + t_allow;

tax=20.0/100*gross_income;
net_salary = gross_income- tax;

printf("\nPAY SLIP FOR OCTOBER 2013\n");


printf("---------------------------\n");

printf("Basic salary: Kshs. %.2f\n",basic_salary);


printf("House allowance: Kshs. %.2f\n",h_allow);
printf("Trans allowance: Kshs. %.2f\n",t_allow);
printf("Gross Salary: Kshs. %.2f\n",gross_income);
printf("Taxable amount: Kshs. %.2f\n",tax);
printf("Net salary: Kshs. %.2f\n",net_salary);

return 0;
}
Assignment one

Question I:

Consider the expression below where a=8, b=3 and c= 5 ,


Write a program to determine the value for the expression. a*(c%b)+c

[5 marks]
Question II:

Assume a float � type variable m has a value 5, while


another float-type variable n has a value 3.
Assume you want to write statements to output the sum of
m and n using the format shown below. Using C programming
language write down the appropriate statement in each case.

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:

Consider the expression below where a=8, b=3 and c= 5 ,


Write a program to determine the value for the expression. a*(c%b)+c

#include<stdio.h>
main()
{

int a,b,c,answer;
a=8;
b=3;
c=5;
answer= (a*(c%b)+c);

printf("The value of the expression = %d\n",answer);


} [5 marks]

Question II:

Assume a float � type variable m has a value 5, while


another float-type variable n has a value 3.
Assume you want to write statements to output the sum of
m and n using the format shown below. Using C programming
language write down the appropriate statement in each case.

i)The sum of 5 and 3 is 8

ii)8 is the sum of 5 and 3 [5 marks]

#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);

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));

printf("The monthly payment is Kshs. %.2f ",monthly_payment);


}
Write a program that enters the name of the product, code of the product,
unit price of the product, the quantity purchased and the total price,
money given to cashier and change. print the reciept

Include VAT which is 16%

#include<stdio.h>

main()
{
char productName[50];
float unitPrice,totalPrice,MoneyPaid,changeGivenBack,tax,totalPurchasePrice;
int ProductCode,quantity;
printf("Product Name: ");
gets(productName);

printf("Product Code: ");


scanf("%d",&ProductCode);

printf("Product Unit Price: Kshs. ");


scanf("%f",&unitPrice);

printf("Quantity Purchased: ");


scanf("%d",&quantity);
printf("Total Money to Cashier: Kshs. ");
scanf("%f",&MoneyPaid);
totalPrice=quantity*unitPrice;
tax=16.0/100.0*totalPrice;
totalPurchasePrice=tax+totalPrice;
changeGivenBack=MoneyPaid-totalPurchasePrice;
printf("TUSKEYS SUPERMARKET - PURCHASE ORDER RECIEPT\n");
printf("---------------------------------------------\n");
printf("Product Name: %s\n",productName);
printf("Product Code : %d\n",ProductCode);
printf("Product Unit Price: Kshs. : %.2f\n",unitPrice);
printf("Quantity Purchased: %d\n",quantity);
printf("Total price before VAT:Kshs. %.2f\n",totalPrice);
printf("Value Added Tax (VAT): Kshs. %.2f\n",tax);
printf("Total Money to Cashier: Kshs. %.2f\n",MoneyPaid);
printf("Total Purchase price after VAT:Kshs. %.2f\n",totalPurchasePrice);
printf("Change: Kshs. %.2f\n",changeGivenBack);

OPERATORS AND OPERANDS


----------------------

OPERATOR -SYMBOL THAT ACT UPON A VALUE, A VARIABLE, CONSTANT,


ARRAY ETC
OPERAND -VARIABLE, CONSTANT, ARRAY ETC THAT ARE ACTED UPON BY
OPERATOR

5+8=13

int x,y,sum;
x=23;
y=34;
sum = x+y - THIS IS AN EXPRESSION
ASSIGNMENT(=)

CLASSIFIED INTO THE FOLLOWING

ARITHMETIC OPERATORS - USED FOR CALCULATION OR COMPUTATION


+ ADDITION
- SUBTRACTION
* MULTIPLICATION
/ DIVISION
% MODULUS(REMAINDER OPERATOR)

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;

printf("Enter the first number: ");


scanf("%d",&num1);

printf("Enter the second number: ");


scanf("%d",&num2);

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;

printf("Enter the time in minutes: ");


scanf("%d",&minutes);

hours=minutes/60;
mins=minutes%60;

printf("Hours in mins and seconds: %d hours %d mins\n",


hours, mins);

return 0;
}
int x,y,sum;

x=78;
y=45;

sum==x+y;

COMPARISION/RELATIONAL OPERATORS

THESE OPERATORS ARE USED FOR COMPARISION/SELECTION PURPOSES


> GREATER THAN
< LESS THAN
>= GREATER THAN OR EQUAL TO
<= LESS THAN OR EQUAL TO
== EQUAL TO
!= NOT EQUAL TO

PASS MARK >= 50


<50 FAIL
enter the age;

age=34;

if(age>=18)
you can vote

else
you can't vote

#include<stdio.h>
main()
{
int marks;

printf("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;
}

#include<stdio.h>
main()
{
int marks;

printf("Enter the marks: ");


scanf("%d",&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;

printf("Enter the marks: ");


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;
}
marks>=50

MARKS>50
OR
MARKS==50

LOGICAL OPERATORS

AND &&

OR ||

NOT !

if you are a kenyan and age>=18


You can vote
else
you can not vote

if you are a kenyan or age>=18


You can vote
else
you can not vote

AND TRUE FALSE


TRUE TRUE FALSE
FALSE FALSE FALSE

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

IF(MARKS>=70 && MARKS<=100)


A

IF(MARKS>=60 && MARKS<70)


B

IF(MARKS>=50 && MARKS<60)


C

IF(MARKS>=40 && MARKS<50)


D

IF(MARKS>=0 && MARKS<40)


E

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;

printf("Enter the number of students: ");


scanf("%d",&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 prefix increment


x++ postfix increment

--x prefix decrement


x-- postfix decrement

x++ same as x=x+1


x-- same as x=x-1

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;

AREA= LENGTH * WIDTH

CONTROL STRUCTURES:
*******************
THESE ARE STRUCTURES THAT ARE USED TO CONTROL THE FLOW
OF A PROGRAM OR HOW A PROGRAM EXECUTES

THERE ARE THREE TYPES OF PROGRAM FLOW OR CONTROL STRUCTURE


i. Sequence control structure
ii. Selection/Decision/Branching control structure
iii.Looping/Iteration/Repetation control structures

i. SEQUENCE CONTROL STRUCTURES - THIS IS WHERE A PROGRAM


EXECUTES IN A SPECIFIED ORDER.

FOR EXAMPLE:
STATEMENT A;
STATEMENT B;
STATEMENT C;
STATEMENT D;

#include<stdio.h>
main()
{
int mins,hours,minutes,secs;

printf("Enter the time in minutes: ");


scanf("%d",&minutes);
hours=minutes/60;
mins=minutes%60;

printf("Hours in mins and seconds: %d hours %d mins\n",


hours, mins);

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

2. SELECTION/BRANCHING/DECISION CONTROL STRUCTURE


THIS IS WHERE A COMPUTER NEEDS TO CHOOSE BETWEEN TWO OR
MORE THAN TWO OPTIONS

CONSIDER THE FOLLOWING PSEUDOCODE


START
DECLARE VARIABLES
ENTER MK1,MK2,MK3, MK4;
COMPUTE THE SUM
COMPUTE THE AVG

IF AVG>=50
PRINT PASS
ELSE
PRINT FAIL
ENDS

consider the following example:


#include<stdio.h>

main()
{
int mk1,mk2,mk3,total,avg;

printf("Enter marks for English: ");


scanf("%d",&mk1);
printf("Enter marks for Mathematics: ");
scanf("%d",&mk2);

printf("Enter marks for Geography: ");


scanf("%d",&mk3);

total=mk1+mk2+mk3;

avg=total/3;

printf("English Score: %d\n",mk1);

printf("Mathematics Score: %d\n",mk2);

printf("Geography Score: %d\n",mk3);

printf("The total marks: %d\n",total);

printf("The average marks: %d\n",avg);

printf("You Passed well!!! Congratulations\n");

printf("You Failed terribly!!!! Need to rewind");


}

1 CHOOSING BETWEEN TWO OPTIONS

SYNTAX
******
if(condition)
{
statement(s) to execute when true;
}
else
{
statement(s) to execute when false;
}

EXAMPLE 1: A program that grade students as pass or fail


based on three subjects. Assume the Pass>=50

#include<stdio.h>
main()
{
int mark1,mark2,mark3,total,avg;
char name[50],regNumber[30];
printf("Enter full name: ");
gets(name);

printf("Enter registration number: ");


gets(regNumber);
printf("Enter the mark1: ");
scanf("%d",&mark1);

printf("Enter the mark2: ");


scanf("%d",&mark2);

printf("Enter the mark3: ");


scanf("%d",&mark3);

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);

printf("Total Marks: %d\n",avg);


printf("Average marks: %d\n",avg);
printf("Verdict\n");
printf("-------\n");
if(avg>=50)
{
printf("Verdict: RESULT: PASS\n");
printf("Proceed to next stage\n");

}
else
{
printf("RESULT: FAIL\n");
printf("Rewind the stage\n");
}

return 0;
}

ax^2 +bx+c=0

Example: Computes the two roots of a quadratic equation

#include<stdio.h>
#include<math.h>
main()
{
float a,b,c,x1,x2;

printf("Enter the value of a: ");


scanf("%f",&a);

printf("Enter the value of b: ");


scanf("%f",&b);

printf("Enter the value of c: ");


scanf("%f",&c);

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

The bank gives you a 6% interest rate


and compounds the interest each month.

Plan 2

The bank gives you a 12% interest rate and


compounds the interest every 2 months.

[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));

printf("PLAN 1: Kshs. %.2f\n",plan1);


printf("PLAN 2: Kshs. %.2f\n",plan2);

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);
}
}

IF A PERSON EARNS kSHS. 50,000 AND ABOVE, HE OR SHE IS


A GIVEN A HOUSE ALLOWANCE OF 30% OF THE BASIC SALARY, 25%
TRANSPORT ALLOWANCE OTHERWISE AN EMPLOYEE GETS 20% HOUSE
ALLOWANCE AND 15% TRANSPORT ALLOWANCE OF THE BASIC SALARY
RESPECTIVELY. WRITE A PROGRAM THAT WILL ACCEPT THE BASIC
SALARY AND PROCESSES THE EMPLOYEE'S SALARY.

ALL EMPLOYEES MUST PAY 16% P.A.Y.E IF THE GROSS SALARY IS


ATLEAST KSHS. 30000
IT SHOULD INCLUDE
. BASIC SALARY
. TRANSPORT
. HOUSE ALLOWANCE
. GROSS SALARY
. TAX AMOUNT
. NET SALARY

#include<stdio.h>
main()
{
float basic,trans_allow,h_allow,gross,net,tax;

printf("Enter basic salary: Kshs. ");


scanf("%f",&basic);

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;

printf("Pay Slip for September 2020\n");


printf("****************\n");

printf("Basic Salary: Kshs. %.2f\n",basic);


printf("House Allow: Kshs. %.2f\n",h_allow);
printf("Trans Allow: Kshs. %.2f\n",trans_allow);
printf("Gross Salary: Kshs. %.2f\n",gross);
printf("Tax Amount: Kshs. %.2f\n",tax);
printf("Net Salary: Kshs. %.2f\n",net);

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;

printf("Enter basic salary: Kshs. ");


scanf("%f",&basic);

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");

printf("Basic Salary: Kshs. %.2f\n",basic);


printf("House Allow: Kshs. %.2f\n",h_allow);
printf("Trans Allow: Kshs. %.2f\n",trans_allow);
printf("Gross Salary: Kshs. %.2f\n",gross);
printf("Tax Amount: Kshs. %.2f\n",tax);
printf("Net Salary: Kshs. %.2f\n",net);

return 0;
}

EXAMPLE 3:

A PROGRAM IS REQUIRED THAT ACCEPT A NUMBER ENTERED


THROUGH THE KEY BOARD AND TEST WHETHER A NUMBER IS EVEN
OR ODD.

#include<stdio.h>
main()
{
int number;

printf("Enter the number to test: ");


scanf("%d",&number);

if(number%2==0)
{
printf("%d is even\n",number);
}
else
{
printf("%d is odd\n",number);
}

return 0;
}
THE TERNARY STRUCTURE

The ternary structure is just a simplification of the


if...else structure

if(condition)
{
statement(s)-true;
}
else
{
statement(s)-false;
}

Syntax: It takes the form:

expression1?expression2:expression3;

condition?statement(s)-true:statement(s)-false;

#include<stdio.h>
main()
{
int number;

printf("Enter the number to test: ");


scanf("%d",&number);

number%2==0?printf("%d is even\n",number):printf("%d is odd\n",number);


if(number%2==0)
{
printf("%d is even\n",number);
}
else
{
printf("%d is odd\n",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;

printf("Enter the first value: ");


scanf("%d",&a);

printf("Enter the second value: ");


scanf("%d",&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);

printf("Enter second number: ");


scanf("%d",&num2);

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);

printf("Enter second number: ");


scanf("%d",&num2);
if(num1>num2)
printf("%d is bigger than %d\n",num1,num2);
else
printf("%d is bigger than %d\n",num2,num1);

(num1>num2)?printf("%d is bigger than %d\n",num1,num2):printf("%d is bigger


than %d\n",num2,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:

(i) int c=6;


printf("%s",(c>0)?"positive":"negative");

(ii) int c=-6;


printf("%s",(c>0)?"positive":"negative");

(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

1 CHOOSING BETWEEN MORE THAN TWO OPTIONS

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 more than 95, then


Student is brilliant

If given marks are less than 30, then


Student is poor

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);

if( x > 95) {


printf( "Student is brilliant\n");
}
else if( x < 30) {
printf( "Student is poor\n");
}
else if( x < 95 && x > 30 ) {
printf( "Student is average\n");
}
else
{
printf("Marks invalid!!!\n");
}
}

#include <stdio.h>

int main() {
int x;
printf("Enter marks: ");
scanf("%d",&x);

if( x > 95 && x<=100) {


printf( "Student is brilliant\n");
}
else if( x > 30 && x < 95 ) {
printf( "Student is average\n");
}
else if( x>=0 && x < 30) {
printf( "Student is poor\n");
}

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

AVERAGE MARKS GRADE


70-100 A
60- 69 B
50- 59 C
40- 49 D
0- 39 E

#include<stdio.h>
main()
{
int mark1,mark2,mark3,total,avg;
char grade,name[40];

printf("Enter your name: ");


gets(name);

printf("Enter the mark1: ");


scanf("%d",&mark1);

printf("Enter the mark2: ");


scanf("%d",&mark2);

printf("Enter the mark3: ");


scanf("%d",&mark3);

total=mark1+mark2+mark3;

avg=total/3;

if(avg>=70 && avg<=100)


{
grade='A';

}
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 if(avg>=0 && avg<40)


{
grade='E';

}
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

Sales range(Kshs.) Commission in %


(based on sales amount)
Commission(%)
From 10,000 but less than 20,000 7
From 20,000 but less than 50,000 9
From 50,000 and above 12

Tax: 10% of income of at least 10,000

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;

printf("Enter sales amount: Kshs. ");


scanf("%f",&sales);

if(sales>=50000)
{
commission=12.0/100*sales;

}
else if(sales>=20000 && sales<50000)
{
commission=9.0/100*sales;

else if(sales>=10000 && sales<20000)


{
commission=7.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");

printf("Fixed Allowance: Kshs. %.2f\n",FIXED_ALLOWANCE);


printf("Sales Amount: Kshs. %.2f\n",sales);
printf("Commission: Kshs. %.2f\n",commission);
printf("Total Income: Kshs. %.2f\n",income);
printf("Tax Amount: Kshs. %.2f\n",tax);
printf("Net Salary: Kshs. %.2f\n",net);

return 0;
}

#include<stdio.h>
main()
{
float tax,bs,ha,gross,net;
const float TA =5000;

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;

printf("The net salary Kshs. %.2f\n",net);

return 0;

Example 4:

You have been asked to develop a program for printing out


a simple water bill. The program will input the following
details:

? Name of customer
? Address
? Telephone Number
? Previous meter reading 100
? Current meter reading 400

The program will calculate the number of units used,


and compute the bill charged using the following rates:

No. OF UNITS COST PER UNIT (Kshs)


> 0 and <= 100 2.50
>100 and <=200 2.25
>200 and <=350 1.90
>350 1.65

The program will then print out the bill details.


? Name of customer
? Address
? Telephone Number
? Previous meter reading
? Current meter reading
? Consumption
? Bill to pay
#include<stdio.h>
main()
{
char name[50],address[50],tel[50];
float p_reading,c_reading,cons,bill;
int meter_no;
printf("Nairobi Water Billing System\n");
printf("------------------------------\n");
printf("Enter the meter number: ");
scanf("%d",&meter_no);

printf("CUSTOMER DETAILS FOR METER N0. %d\n",meter_no);


printf("-----------------------------------\n");

printf("Enter name: ");


gets(name);

printf("Enter address: ");


gets(address);

printf("Enter telephone number: ");


gets(tel);

printf("Enter the previous meter reading: ");


scanf("%f",&p_reading);

printf("Enter the current meter reading: ");


scanf("%f",&c_reading);

cons=c_reading-p_reading;

if(cons>350)
{
bill=cons*1.65;
}
else if(cons>200 && cons<=350)
{
bill=cons*1.90;
}

else if(cons>100 && cons<=200)


{
bill=cons*2.25;
}

else if(cons>0 && cons<=100)


{
bill=cons*2.50;
}

else
{
bill=0;
}

printf("CUSTOMER DETAILS FOR METER N0. %d for Nov 2015\n",meter_no);


printf("-----------------------------------\n");
printf("Name: %s\n",name);

printf("Address: %s\n",address);

printf("Telephone number: %s\n",tel);

printf("Previous meter reading: %.2f\n",p_reading);

printf("Current meter reading: %.2f\n",c_reading);

printf("Consumption in cubic meters: %.2f\n",cons);

printf("Bill to pay in Kshs: %.2f\n",bill);

return 0;
}

Safaricom Company Ltd uses the following PAYE


(Pay As You Earn)
percentage tax rates for all its employees salary
categories

Gross Salary (Ksh.) Pay rate (%)


1. 50,000 and above 14
2. 40,000 � 50,000 12
3. 35,000 � 40,000 11
4. 25,000 � 35,000 8
5. 16,000 � 25,000 5
6. 9,500 � 16,000 3
7. Below 9500 0
(The rates are exclusive of the upper boundary salary
figures for categories 2, 3,4, 5 ,6)

The following standard deductions apply to all employees


N.S.S.F = Ksh. 80.00
N.H.I.F = Ksh. 200.00
Service charge = Ksh. 100.00

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.

At the end of the month, the payroll clerk runs a payroll


through which he enters each employee�s basic salary into the
computer and overtime hours worked as recorded in a claim form
filled by the employee. The computer in turn adds up the basic
salary and the overtime pay (if any) to get the gross pay.

The computer then determines the PAYE amount payable from the
gross pay. Finally the employee�s net pay is calculated using
the formula:

Net Pay = Gross pay � [PAYE + (N.S.S.F + N.H.I.F + Service charge)]


Required:
Write a program that performs the above mentioned payroll
activities for a single employee and outputs the following on
the screen:

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];

const float NSSF=80,NHIF=200,SERVICE_CHARGE=100;

printf("\nENTER EMPLOYEE DETAILS\n");


printf("----------------------\n");
printf("Enter the first name: ");
gets(firstname);

printf("Enter the last name: ");


gets(lastname);

printf("Enter employee number: ");


scanf("%d",&emp_number);

printf("Enter the basic salary: Kshs. ");


scanf("%f",&basic);

printf("Enter the position of employee: ");


gets(position);

printf("Enter overtime hours: ");


scanf("%d",&hours);

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));

printf("\nEMPLOYEE PAYSLIP FOR APRIL 2013\n");


printf("----------------------------------\n");
printf("Employee Number: %d\n",emp_number);
printf("First Name: %s\n",firstname);
printf("Last Name: %s\n",lastname);
printf("Position: %s\n",position);
printf("Basic Salary: Kshs. %.2f\n",basic);
printf("Hours Worked: %d hours\n",hours);
printf("Gross Salary: Kshs. %.2f\n",gross);
printf("Overtime Hours Worked: %d\n",hours);
printf("NSSF deductions: Kshs. %.2f\n",NSSF);
printf("NHIF contribution: Kshs. %.2f\n",NHIF);
printf("SERVICE CHARGE: Kshs. %.2f\n",SERVICE_CHARGE);
printf("Total deductions: Kshs. %.2f\n",deductions);
printf("PAYE: Kshs. %.2f\n",paye);
printf("Net Salary: Kshs. %.2f\n",net);

A program is required to calculate wages for employees of


Kamonjo Ltd. Using the following formulae
i) Basic salary = No of Hours * hourly rate
ii) Lunch Allowance = Kshs. 200.00
iii) Gross Salary = Basic Pay + Lunch Allowance
iv) Income Tax charged on gross pay as follows:

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);

printf("Enter the last name: ");


gets(lastname);

printf("\nEnter the position: ");


gets(position);

printf("Enter employee number: ");


scanf("%d",&emp_number);

printf("Enter the number of hours worked: ");


scanf("%d",&hours)

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;

else if(gross>3000 && gross<=4000)


tax=7.0/100*gross;

else if(gross>3000 && gross<=4000)


tax=5.0/100*gross;
else
tax=0;
net=gross-tax;

printf("\nEMPLOYEE PAYSLIP FOR APRIL 2013\n");


printf("----------------------------------\n");

printf("First Name: %s\n",firstname);


printf("Last Name: %s\n",lastname);
printf("Position: %s\n",position);
printf("Basic Salary: Kshs. %.2f\n",basic);
printf("Hours Worked: %d hours\n",hours);
printf("Gross Salary: Kshs. %.2f\n",gross);
printf("Tax: Kshs. %.2f\n",tax);
printf("Net Salary: Kshs. %.2f\n",net);

}
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:

AVERAGE MARK GRADE


75 - 100 Distinction
65 - 74 Credit
50 - 64 Pass
< 50 Fail

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);

if(avg>=75 && avg<=100)


{
printf("Grade: Distinction\n");
}
else if(avg>=65 && avg<75)
{
printf("Grade: Credit\n");
}
else if(avg>=50 && avg<65)
{
printf("Grade: Pass\n");
}
else
{
printf("Grade: Fail\n");
}

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);

if(avg>=75 && avg<=100)


{
printf("Grade: Distinction\n");
}
else if(avg>=65 && avg<75)
{
printf("Grade: Credit\n");
}
else if(avg>=50 && avg<65)
{
printf("Grade: Pass\n");
}
else
{
printf("Grade: Fail\n");
}

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);

if(avg>=75 && avg<=100)


{
printf("Grade: Distinction\n");
}
else if(avg>=65 && avg<75)
{
printf("Grade: Credit\n");
}
else if(avg>=50 && avg<65)
{
printf("Grade: Pass\n");
}
else
{
printf("Grade: Fail\n");
}

printf("Mathematics for Science\n");


printf("------------------------\n");
printf("CAT 1: ");
scanf("%d",&cat1);

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);

if(avg>=75 && avg<=100)


{
printf("Grade: Distinction\n");
}
else if(avg>=65 && avg<75)
{
printf("Grade: Credit\n");
}
else if(avg>=50 && avg<65)
{
printf("Grade: Pass\n");
}
else
{
printf("Grade: Fail\n");
}

SWITCH CONDITIONAL STRUCTURES

The switch structure is used to test if a variable equals


some constant values,
that must be an integer or character constant values.
For example,we can test if x eqauls a constant value,
then we do something,if
it equals another constant value,we do something else, and so on.

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);

}
}

LOOPING/ITERATION/REPETATION CONTROL STRUCTURES


************************************************
THESE STRUCTURES ARE USED TO EXECUTE SOME STATEMENTS SEVERAL
TIMES DEPENDING WHETHER THE CONDITION IS TRUE OR FALSE.

1.for
2.while
3.do---while

SYNTAX FOR 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

A program that prints numbers that are divisible by 3


main()
{
int number;
number=0;
while(number<100)
{
printf("%d\n",number);
number+=3;
}

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++;
}

The square of even numbers between 0 and 100;

1.initial value-starting value


2.condition
3.update (++ or --)
4.staments to execute when the condition is true

Write a program that display the following


numbers on the screen.
1
2
3
4
5

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);

printf("There are no more computers to be picked\n");


}

#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--;

Write a program that converts Fah (0-100) to Celcius


Fahrenheit Degrees celcius
0 -17
10 -12
20
30
40
50
60
70
80
90
100 37

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);
}
}

(j)A quantity known as body mass index (BMI) is used to


calculate the risk of weight related problems.
BMI is computed by the formula
BMI=w/h2
where w is the weight in kilograms and h is height in
meters. A BMI of about 18.5 and 24.9 is considered normal.
A BMI of about 25.0 or more is considered as not normal
ie. overweight
Write an application that accepts weight and height
(both integers) and outputs BMI with words �Normal� or
�Not Normal�
BMI applies to most adults btn 18 and 65 years

#include<stdio.h>
main()
{
float w,h,BMI;
printf("Enter the weight: ");
scanf("%f",&w);

printf("Enter the height: ");


scanf("%f",&h);

BMI=w/(h*h);

printf("Weight = %f\n",w);
printf("height = %f\n",h);
printf("BMI = %f\n",BMI);

if(BMI>=18.5 && BMI<=24.9)


{
printf("BMI is normal\n");
printf("You are not Overweight\n");
printf("You are not at risk/n");
}
else
{
printf("BMI is not normal\n");
printf("You are Overweight\n");
printf("You are at risk/n");
}
}

#include<stdio.h>
main()
{
float w,h,BMI;
int age;

printf("Enter your age: ");


scanf("%d",&age);

if(age<=18 || age>=65)
{
printf("BMI doesn't apply\n");
}
else
{
printf("Enter the weight: ");
scanf("%f",&w);

printf("Enter the height: ");


scanf("%f",&h);

BMI=w/(h*h);

printf("Weight = %f\n",w);
printf("height = %f\n",h);
printf("BMI = %f\n",BMI);

if(BMI>=18.5 && BMI<=24.9)


{
printf("BMI is normal\n");
printf("You are not Overweight\n");
printf("You are not at risk/n")
}
else
{
printf("BMI is not normal\n");
printf("You are Overweight\n");
printf("You are at risk/n")
}
}
}

In a scientific application the function f(t) is computed


as follows
f (t) = -3t^2+5 if t>=0
-3t^2-5 if t<0

Write a program to input t and then compute and output f(t).

main()
{

int t,f(t);

printf("Enter the value of t: ");


scanf("%d",&t);

if(t>=0)
{
ft=-3*t*t+5;
}

else
{
ft=-3*t*t-5;

printf("The value of t: %d\n ",t);


printf("The value of f(t): %d\n ",ft);

ft=-3*pow(t,2)+5

If you start a bank account with $10,000 and your


bank compounds the interest monthly at an interest
rate of 8%, write a program to compute how much money
you earn every year for 15 years? (Assume that you do not
add or withdraw any money from the account)

#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);

printf("The amount earned for 15 yrs: Kshs. %f\n",amount);

}
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);

printf("Year %d: Kshs. %f\n",t,amount);

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);

printf("%d\t\t Kshs. %.2f\n",count,amount);

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);

printf("%d\t\t Kshs. %.2f\n",count,amount);

}
}

#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);

printf("Year %d: Kshs. %f\n",t,amount);

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);

printf("Year %d: Kshs. %f\n",t,amount);

}
}

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;

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 p,r,t,n,amount;

p=1500;
r=0.043;
n=4;
t=6;
amount=p*(pow(1+r/n,n*t));

printf("The amount: Kshs. %f\n",amount);

Solution:
Using the compound interest formula, we have that
P = 1500, r = 4.3/100 = 0.043, n = 4, t = 6.

So, the balance after 6 years is approximately $1,938.84.

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 every year for 6 years?

#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));

printf("%d.\t\t Kshs. %.2f\n",t,total_amount);

t++;
}
}

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 p,r,t,n,amount;

p=1200;
r=0.1249;
n=12;
t=0.5;
amount=p*(pow(1+r/n,n*t));

printf("The amount: Kshs. %f\n",amount);

#include<stdio.h>
#include<math.h>
main()
{
float p,r,total_amount;

int n,t;
p=1200;
r=0.1249;
n=12;
t=1;

printf("Month\t\t Total Amount(Kshs.)\n");


while(t<=6)
{
total_amount=p*(pow(1+r/n,n*(t/12.0)));

printf("%d\t\t Kshs. %.2f\n",t,total_amount);

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;

printf("The net salary Kshs. %.2f\n",net);

n++;
}
return 0;

Example:

A prgram that accept the marks of 5 students and grade


them as pass or fail.

#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("Enter marks for student );


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");
}

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
}
}

Example: A program that converts fahrenheit to degress


centigrade

#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

Sales range(Kshs.) Commission


(based on sales amount)
Commission(%)
From 10,000 but less than 20,000 7
From 20,000 but less than 50,000 9
From 50,000 and above 12

Tax: 10% of income of at least 10,000

Required:

Write a program that will allow the user to input the sales
of n salesmen and compute the net income.

2000>=10000 && 2000<20000


sales
#include<stdio.h>
main()
{
float income,tax,sales,commission,net;
const float FIXED_ALLOWANCE=5000;
int n,counter;
counter=1;
printf("Enter the number of salemen: ");
scanf("%d",&n);
while(counter<=n)
{
printf("Salesman: %d\n",i);
printf("-----------------\n");
printf("Enter sales amount: Kshs. ");
scanf("%f",&sales);

if(sales>=50000)
{
commission=12.0/100*sales;

}
else if(sales>=20000 && sales<50000)
{
commission=9.0/100*sales;

else if(sales>=10000 && sales<20000)


{
commission=7.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");

printf("Fixed Allowance: Kshs. %.2f\n",FIXED_ALLOWANCE);


printf("Sales Amount: Kshs. %.2f\n",sales);
printf("Commission: Kshs. %.2f\n",commission);
printf("Total Income: Kshs. %.2f\n",income);
printf("Tax Amount: Kshs. %.2f\n",tax);
printf("Net Salary: Kshs. %.2f\n",net);
counter++;
}
return 0;
}

SYNTAX FOR THE FOR LOOP


***********************
for(initial value;condition;update)
{
statement(s);

Remember the while loop

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");
}
}
}

Example: Validating the number of students and marks


using while

#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;

printf("Enter the number of salemen: ");


scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Salesman: %d\n",i);
printf("-----------------\n");
printf("Enter sales amount: Kshs. ");
scanf("%f",&sales);

if(sales>=50000)
{
commission=12.0/100*sales;

}
else if(sales>=20000 && sales<50000)
{
commission=9.0/100*sales;

else if(sales>=10000 && sales<20000)


{
commission=7.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");

printf("Fixed Allowance: Kshs. %.2f\n",FIXED_ALLOWANCE);


printf("Sales Amount: Kshs. %.2f\n",sales);
printf("Commission: Kshs. %.2f\n",commission);
printf("Total Income: Kshs. %.2f\n",income);
printf("Tax Amount: Kshs. %.2f\n",tax);
printf("Net Salary: Kshs. %.2f\n",net);

}
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);

printf("Enter Registration number: ");


gets(regNum);
printf("Enter the marks: ");
scanf("%d",&marks);

printf("\nResults of examination of April 2021 Semester\n");


printf("----------------------------------------------\n");

printf("Registration Number: %s\n",regNum);


printf("Student Name: %s\n",name);
printf("Marks obtained: %d\n",marks);

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

Process returned 10 (0xA) execution time : 0.374 s


Press any key to continue.

The outer loop and the inner loop in the immediate above code can be illustrated as
below

The outer loop:

while(a<3)
{
statements;

a++;
printf("\n");
}

The inner loop:


while(b<4)
{
printf("Loop\n");
b++;
}

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).

Example: Rewrite the immediate above loop using

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

Process returned 10 (0xA) execution time : 0.373 s


Press any key to continue.

iv)

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

Process returned 10 (0xA) execution time : 0.357 s


Press any key to continue.

v)

1
2 2
3 3 3
4 4 4 4

Process returned 10 (0xA) execution time : 0.410 s


Press any key to continue.

Example:

Write a program to output the a multiplication table of size 5.

#include<stdio.h>
int main()
{
int row,col,n;

printf("\nMULTIPLICATION TABLE OF SIZE FROM 1 TO 5\n");


printf("\n=============================\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");
}
}

MULTIPLICATION TABLE OF SIZE FROM 1 TO 5


=========================================
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

Example:

Write a program to input n and output the a multiplication table of size n(where n
is any number).

Assume n=10; The output will be as follows:

Input the size: 10

#include<stdio.h>
int main()
{
int row,col,n;

printf("\n Input the size: ");


scanf("%d",&n);
printf("\n");

printf("\nMULTIPLICATION TABLE OF SIZE OF SIZE %d\n",n);


printf("=========================================\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");
}
}

MULTIPLICATION TABLE OF SIZE OF SIZE 10


=========================================
1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100

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

Steps in computer based problem solving

i)Identify the problem � decide on what the program should do.


ii)Formulate and represent a procedure for solving the problem without the use of a
computer (algorithm).
iii)Represent the algorithm using any acceptable convention (flowcharts or pseudo
codes).
iv)Check that the algorithm works.
v)Write a computer code from the algorithm.
vi)Test the computer code and complete its documentation (written material
explaining
the code and the program).
vii)Produce the final program.
viii)Run or use the computer program.

Defination:

An algorithm is the series of steps that are used to solve a programming


problem.
It may also be considered as a plan for solving a programming problem that
specifies the sequence of steps used in the solution.
The following are mandatory features that an algorithm must have:
.An algorithm must have a start and an end point.
.Every step must be doable or performable:-
-using a finite amount of effort;
-in a finite amount of time.

In summary an algorithm will consist of a series of steps solving a


problem. There must be a starting point and an ending point and each step
is something the computer can do and finish. So the format of an algorithm is:
start, step1, step2, , , , , stepn, stop. Generally the steps are numbered or
labeled from start to stop.

Representing algorithms:

The most common means of representing algorithms is by the use of flowcharts


or pseudo code.

Flowcharts consist of a set of conventional symbols

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("Enter the value of variable A: ");


scanf("%d",&variable_A);

printf("Enter the value of variable B: ");


scanf("%d",&variable_B);

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);

printf("The number is: %d\n",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);

printf("The number is: %d\n",number);

count++;
}
}

syntax for the for loop:


for(initial value;condition;update)
{
statement(s);

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);

printf("The number is: %d\n",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);

printf("The number is: %d\n",number);


sum=sum+number;
count++;
}
printf("The sum = %d\n",sum);
}

#include<stdio.h>
main()
{
int count,number,sum,number_of_items;
count=0;
number=0;
sum=0;

printf("How many items: ");


scanf("%d",&number_of_items);

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;

printf("The sum = %d\n",sum);


}

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;

printf("The sum = %d\n",sum);


printf("The difference = %d\n",diff);
printf("The product = %d\n",mult);
printf("The quotient = %d\n",div);
return 0;
}

Defination:
It is a sub program that is called to perform
a particular task. The task can be simple or complex.

They are two types of functions


1. Built-in functions
2. User defined functions
Built in functions:

These are subprograms that are predefined(already written)


and are called to perform some particular task. They are
stored under the Libary files.

Include:sqrt(),pow(),sin(),tan(), printf(),scanf(),gets(),
puts(),strcpy(),strcat(),stcmp() etc

#include<stdio.h>
main()
{
char name[30];

printf("Enter full name: ");


scanf("%s",&name);

printf("Full name: %s\n",name);


return 0;
}

#include<stdio.h>
main()
{
char name[30];

printf("Enter full name: ");


gets(name);

printf("Full name: %s\n",name);


puts(name);
return 0;
}

Both inbuilt and user defined can return a value or not


return a value.

Functions that return a value are refered to as non-void


function.

Functions that do not return a value are known as void


functions.

User defined functions:

These are functions or sub programs that are written by the


programmer

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;
}

EXAMPLE 1: RETURNING A VALUE(NON-VOID FUNCTION)


#include<stdio.h>
int sum(int x, int y)
{
int z;
z=x+y;
return z;
}
main()
{
int a,b,c;

printf("Enter first number: ");


scanf("%d",&a);

printf("Enter second number: ");


scanf("%d",&b);

c=sum(a,b);
printf("The answer = %d\n",c);
return 0;
}

EXAMPLE: NOT RETURNING A VALUE(VOID FUNCTION)


#include<stdio.h>
void sum(int x,int y)
{
int z;
z=x+y;
printf("The answer = %d\n",z);
}

main()
{
int a,b;

printf("Enter first number: ");


scanf("%d",&a);

printf("Enter second number: ");


scanf("%d",&b);

sum(a,b);
return 0;
}

EXAMPLE 3: RETURNING A VALUE(NON-VOID FUNCTION)

#include<stdio.h>
float volume(float r, float h)
{
float vol;
vol=3.14*r*r*h;
return vol;
}
main()
{
int rad,height,vol;

printf("Enter the radius: ");


scanf("%d",&rad);

printf("Enter the height: ");


scanf("%d",&height);

vol=volume(rad,height);
printf("The answer = %d\n",vol);
return 0;
}

EXAMPLE: NOT RETURNING A VALUE(VOID FUNCTION)


#include<stdio.h>
void sum(int , int );
main()
{
int a,b,c;

printf("Enter first number: ");


scanf("%d",&a);

printf("Enter second number: ");


scanf("%d",&b);

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

4. ARGUMENTS/PARAMETERS - THESE ARE VALUES THAT THE FUNCTION


CALL AND THE FUNCTION DEFINATION USES TO COMMUNICATE TO
COMMUNICATE WITH EACH OTHER.

ARGUMENTS IN THE FUNCTION CALL ARE REFERED TO AS ACTUAL


ARGUMENTS OR PARAMETERS

ARGUMENTS IN THE FUNCTION PROTOTYPE OR HEADER ARE KNOWN AS


FORMAL ARGUMENTS OR PARAMETERS

#include<stdio.h>
float volume(float r, float h);//function prototype
main()
{
int rad,height,vol;

printf("Enter the radius: ");


scanf("%d",&rad);

printf("Enter the height: ");


scanf("%d",&height);

vol=volume(rad,height);//function call
printf("The answer = %d\n",vol);
return 0;
}

float volume(float r, float h)//FUNCTION HEADER


{
float vol;
vol=3.14*r*r*h;
return vol;
//STATEMENT 1,2,3- FUNCTION BODY
}

FUNCTION HEADER + FUNCTION BODY = FUNCTION DEFINATION

CALL(PASS) BY VALUE AND CALL(PASS) BY REFERENCE

CALL BY VALUE IS WHERE A COPY OF THE VALUE IS PASSED TO


THE FUNCTION AND ANY CHANGE THAT IS MADE BY THE FUNCTION
DOESN'T AFFECT THE ORIGINAL VALUES.

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);

printf("Enter the height: ");


scanf("%d",&height);

printf("Before the functional call\n");


printf("---------------------------\n");
printf("Radius: %d\n",rad);
printf("Height: %d\n",height);

vol=volume(rad,height);//function call

printf("After the functional call\n");


printf("---------------------------\n");
printf("Radius: %d\n",rad);
printf("Height: %d\n",height);

printf("The answer = %d\n",vol);


return 0;
}

int volume(int r, int h)//FUNCTION HEADER


{
int vol;
r+=10;
h+=20;

printf("In the functional call\n");


printf("-------------------------\n");
printf("Radius: %d\n",r);
printf("Height: %d\n",h);

vol=3.14*r*r*h;
return vol;
//STATEMENT 1,2,3- FUNCTION BODY
}

CALL(PASS) BY REFERENCE

CALL BY REFERENCE IS WHERE THE VARIABLE CONTAINING THE


VALUES ARE PASSED TO FUNCTION AND ANY CHANGE
THAT IS MADE BY THE FUNCTION DO AFFECT THE ORIGINAL VALUES.
TO INDICATE THAT A FUNCTION IS CALL BY REFERENCE, USE THE
&(ADDRESS OF OPERATOR) BY PUTTING IT IN NEXT TO THE
PARAMETERS BOTH IN THE FUCTION PROTOTYPE AND THE FUNCTION
HEADER.

SYNTAX

return_data_type function_name(int &x, int &y);//prototype

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;

printf("Enter the radius: ");


scanf("%d",&rad);

printf("Enter the height: ");


scanf("%d",&height);

printf("Before the functional call\n");


printf("---------------------------\n");
printf("Radius: %d\n",rad);
printf("Height: %d\n",height);

vol=volume(rad,height);//function call

printf("After the functional call\n");


printf("---------------------------\n");
printf("Radius: %d\n",rad);
printf("Height: %d\n",height);

printf("The answer = %d\n",vol);


return 0;
}

int volume(int &r, int &h)//FUNCTION HEADER


{
int vol;
r+=10;
h+=20;

printf("In the functional call\n");


printf("-------------------------\n");
printf("Radius: %d\n",r);
printf("Height: %d\n",h);

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.

AVERAGE MARKS GRADE


70 - 100 A
60 - 69 B
50 - 59 C
40 - 49 D
0- 39 E

i. Write a function called get_grade() that accepts the


average marks and then returns the grade to the calling
program.

ii. write a function called grade()that accepts the


average marks and then prints the grade.

#include<iostream>
using namespace std;
char get_grade(int avg)
{
char grade;
if(avg>=70 && avg<=100)
grade='A';

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='E';
return grade;
}
main()
{
int mk1,mk2,mk3,total,avg;
char grd,name[40],regNum[25];

cout<<"Registration Number: ";


cin.getline(regNum,25);

cout<<"Student Name: ";


cin.getline(name,40);
cout<<"Mathematics: ";
cin>>mk1;

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<<"Student Name: "<<name<<endl;


cout<<"Mathematics: "<<mk1<<endl;

cout<<"English: "<<mk2<<endl;

cout<<"Chemistry: "<<mk3<<endl;

cout<<"Total Marks: "<<total<<endl;


cout<<"Average Marks: "<<avg<<endl;
cout<<"Grade: "<<grd<<endl;
}

EXAMPLE 1:

#include<iostream>
using namespace std;

main()
{
show_grade();

return 0;
}

int input()
{
int mk1,mk2,mk3,mk4,sum;

cout<<"Enter the marks for English: ";


cin>>mk1;

cout<<"Enter the marks for Physics: ";


cin>>mk2;

cout<<"Enter the marks for Chemistry: ";


cin>>mk3;

cout<<"Enter the marks for Geography: ";


cin>>mk4;

sum=mk1+mk2+mk3+mk4;

cout<<"\nRESULT OF STAGE I SEMESTER II"<<endl;


cout<<"------------------------------"<<endl;
cout<<"English: "<<mk1<<endl;
cout<<"Physics: "<<mk2<<endl;
cout<<"Chemistry:"<<mk3<<endl;
cout<<"Geography: "<<mk4<<endl;
return sum;
}

int compute()
{
int avg,sum;
sum=input();
avg=sum/4;

cout<<"\nTotal marks: "<<sum<<endl;


cout<<"\Average marks: "<<avg<<endl;
return avg;
}

char grade()
{
char grd;
int avg;

avg=compute();

if(avg>=70 && avg<=100)


grd='A';

else if(avg>=60 && avg<70)


grd='B';

else if(avg>=50 && avg<60)


grd='C';

else if(avg>=40 && avg<50)


grd='D';

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;
}

float get_mean(float mk1,float mk2, float mk3)


{
float avg;
avg=(mk1+mk2+mk3)/3;
return avg;
}

char get_grade(float avg)


{
char grade;

if(avg>=70 && avg<=100)


grade='A';

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='E';

return grade;

void show(float mean, char grade)


{
cout<<"The mean marks = "<<mean<<endl;
cout<<"The grade = "<<grade<<endl;
}

void compute()
{
float math,eng,comp,mean;
char grade;

cout<<"Enter marks for Maths: ";


math=validate();
cout<<"Enter marks for English: ";
eng=validate();

cout<<"Enter marks for Computer: ";


comp=validate();

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;

//input student size

cout<<"\n How many students? ";


cin>>number;

//compute for each student

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

cout<<"Enter marks for Mathematics: ";


maths=input();
cout<<"Enter marks for English: ";
english=input();

cout<<"Enter marks for Computer: ";


computer=input();

//get the mean mark

mean=get_mean(maths,english,computer);

//get the grade

grade=get_grade(mean);

//show mean mark and the grade

show(mean,grade);

//function to compute the mean


float get_mean(float mk1, float mk2, float mk3)
{
float mean_marks;

mean_marks=(mk1+mk2+mk3)/3;
return mean_marks;
}

//function to compute grade

char get_grade(float avg)


{
char grd;
if(avg>=70 && avg<=100)
grd='A';

else if(avg>=60 && avg<70)


grd='B';

else if(avg>=50 && avg<60)


grd='C';

else if(avg>=40 && avg<50)


grd='D';

else
grd='E';

return grd;

//function to input a valid marks

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;

//function to show the mean and the grade

void show(float mean,char grade)


{
cout<<"Mean Score: "<<mean<<endl;
cout<<"Grade: "<<grade<<endl;

}
void and non-void functions

return_data_type function_name(data_type par1,


data_typepar2,..)
{
//function body

}
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

scenario 2(void function)

void accountant(var money)


{
float total;
count the money;
total=sum of the money;
cout<<The total is total;
}

main()
{
float money;
I collect the money;
accountant(money);
}

scenario 3(void function)

void accountant()
{
collect the money;
count the money;
total=sum of the money;
cout<<The total is total;
}

main()
{

accountant();

scenario 4(non-void function)


float accountant()
{
float total
collect the money;
count the money;
total=sum of the money;
return total;
}
main()
{
float sum;
sum=accountant();
cout<<total money = sum

Example 1:
A function that accept length and width, computes
the area and return the area to the caller;

#include<iostream>
using namespace std;

float rectangle(float length,float width)


//function header or function defination
{
float area;
area=length*width;//function body
return area;
}
//function body + function header = function defination

main()
{
float l,w,ar;
cout<<"Enter the length: ";
cin>>l;//10

cout<<"Enter the width: ";


cin>>w;//5
ar=rectangle(l,w);//function call
cout<<"The area = "<<ar<<endl;

#include<iostream>
using namespace std;

char get_grade(float avg);

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;
}

char get_grade(float avg)


{
char grd;
if(avg>=70 && avg<=100)
grd='A';

else if(avg>=60 && avg<70)


grd='B';

else if(avg>=50 && avg<60)


grd='C';

else if(avg>=40 && avg<50)


grd='D';
else
grd='E';

return grd;
}

#include<iostream>
using namespace std;
float rect(float *l,float *w);
main()
{
float length,width, area;
cout<<"Enter the length: ";
cin>>length;

cout<<"Enter the width: ";


cin>>width;
cout<<"Before the function call: "<<endl;
cout<<"Length = "<<length<<endl;
cout<<"Width = "<<width<<endl;

rect(&length,&width);

cout<<"After the function call: "<<endl;


cout<<"Length = "<<length<<endl;
cout<<"Width = "<<width<<endl;

cout<<"The area = "<<area<<endl;

}
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;

void sum(int x, int y)


{
int z;
z=x+y;
printf("The result = %d\n",z);
}

#include<iostream>
using namespace std;

main()
{
show_grade();

return 0;
}

int input()
{
int mk1,mk2,mk3,mk4,sum;

cout<<"Enter the marks for English: ";


cin>>mk1;

cout<<"Enter the marks for Physics: ";


cin>>mk2;

cout<<"Enter the marks for Chemistry: ";


cin>>mk3;

cout<<"Enter the marks for Geography: ";


cin>>mk4;

sum=mk1+mk2+mk3+mk4;

cout<<"\nRESULT OF STAGE I SEMESTER II"<<endl;


cout<<"------------------------------"<<endl;
cout<<"English: "<<mk1<<endl;
cout<<"Physics: "<<mk2<<endl;
cout<<"Chemistry:"<<mk3<<endl;
cout<<"Geography: "<<mk4<<endl;
return sum;
}

int compute()
{
int avg,sum;
sum=input();
avg=sum/4;

cout<<"\nTotal marks: "<<sum<<endl;


cout<<"\Average marks: "<<avg<<endl;
return avg;
}

char grade()
{
char grd;
int avg;

avg=compute();

if(avg>=70 && avg<=100)


grd='A';

else if(avg>=60 && avg<70)


grd='B';

else if(avg>=50 && avg<60)


grd='C';

else if(avg>=40 && avg<50)


grd='D';

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;
}

float get_mean(float mk1,float mk2, float mk3)


{
float avg;
avg=(mk1+mk2+mk3)/3;
return avg;
}

char get_grade(float avg)


{
char grade;

if(avg>=70 && avg<=100)


grade='A';

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='E';

return grade;
}

void show(float mean, char grade)


{
cout<<"The mean marks = "<<mean<<endl;
cout<<"The grade = "<<grade<<endl;
}

void compute()
{
float math,eng,comp,mean;
char grade;

cout<<"Enter marks for Maths: ";


math=validate();

cout<<"Enter marks for English: ";


eng=validate();

cout<<"Enter marks for Computer: ";


comp=validate();

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;

where datatype: int,float,double,char,bool


long int,short int, signed int, unsigned int

signed int x; both + and -


unisgned int x; + positive values from 0 to 1233

int x;

Initialization of variables:

int x=23;

what if we want to create many integers say:

int x1,x2,x3,x4,x5;
int x[5];
char name[40];
float numbers[5];

Defination:

Array is a data structure/variable that contain elements/values of the


same data type under the same name.

Structure is a data structure that contain elements of the


different data type under the same name.

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.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last element.

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:

type arrayName [ arraySize ]; OR


datatype identifier[SIZE];

WHERE: DATATYPE CAN BE INT,FLOAT,DOUBLE,CHAR OR USER DEFINED


DATA TYPE
IDENTIFIER - A VALID VARIABLE NAME
SIZE - INT VALUE THAT SPECIFIES THE NUMBER OF VALUES

EXAMPLE:
int x1,x2,x3,x4,x5;//not using arrays
int x[5];//using arrays

This is called a single-dimension array. The arraySize must be an integer


constant greater than zero and type can be any valid C/C++ data type. For
example, to declare a 10-element array called balance of type double, use this
statement:

double balance[10];

Initializing Arrays
You can initialize C/C++ array elements either one by one or using a single
statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};


The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].

Following is an example to assign a single element of the array:


If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

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:

Accessing Array Elements

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:

TO ACCESS ARRAY ELEMENTS USE INDEXES.


THE INDEXES START FROM 0 AND ENDS AT
SIZE-1.

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};

printf("First display from the initial 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]);

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]);

printf("Enter the first value: ");


scanf("%lf",&balance[0]);
printf("Enter the second value: ");
scanf("%lf",&balance[1]);
printf("Enter the third value: ");
scanf("%lf",&balance[2]);
printf("Enter the fourth value: ");
scanf("%lf",&balance[3]);
printf("Enter the fifth value: ");
scanf("%lf",&balance[4]);

printf("Third display from the values entered through keyboard\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]);
}

printf("Third display from the values entered through keyboard\n");


printf("------------------------------------------------------\n");
for(index=0; index<5;index++)
{
printf("The value %d = %0.2Lf\n",index+1,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]);

printf("Total marks: %d\n",total);


printf("Average marks: %d\n",avg);

#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]);
}

printf("The total marks: %d\n",total);

#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]);
}

printf("The total marks: %d\n",total);


printf("The average marks: %d\n",avg);
}

#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;

printf("\nSTUDENT TRANSCRIPT FOR MAY SEMESTER\n");


printf("*************************************\n");
for(i=0;i<5;i++)
{
printf("Marks %d: %d\n", i+1,x[i]);
}

printf("The total marks: %d\n",total);


printf("The average marks: %d\n",avg);

if(avg>=70 && avg<=100)


{
grade='A';

}
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 if(avg>=0 && avg<40)


{
grade='E';

}
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)
}

for(i=0 ;i<5; i++)


{
cout<<�Enter the value for number �<<i+1<<�:�;
cin>>x[i]
}

Example 1: A program that inputs and outputs 5 marks.

#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;

Example 2: A program that inputs 5 marks obtained in an


exam compute the sum and average and then outputs.
the sum of the 5 marks

#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;

if(avg>=70 && avg<=100)


grade='A';

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='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;

if(avg>=70 && avg<=100)


grade='A';
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='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++)
{

cout<<"Enter Marks "<<i+1<<":";


cin>>x[i];
sum=sum+x[i];
}

avg=sum/5;

if(avg>=70 && avg<=100)


grade='A';

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='E';
cout<<"\nRESULTS:"<<endl;
cout<<"-----------"<<endl;
for(i=0;i<5;i++)
{

cout<<"Mark "<<i+1<<":"<< x[i]<<endl;;

}
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;

printf("Enter first number: ");


scanf("%d",&num1);

#include<stdio.h>
main()
{
int num1,num2,num3,num4,num5,sum;

printf("Enter first number: ");


scanf("%d",&num1);

printf("Enter second number: ");


scanf("%d",&num2);

printf("Enter thrid number: ");


scanf("%d",&num3);

printf("Enter fourth number: ");


scanf("%d",&num4);

printf("Enter fifth number: ");


scanf("%d",&num5);

sum=num1+num2+num3+num4+num5;

printf("The sum = %d\n",sum);


}
Array: a data structure that contains elements of the same
data type under the same name.

Syntax:

data_type identifier[SIZE];
where:

i. Data type is any valid data type i.e int,float,double,char.


ii.Identifier is any valid variable name.
iii. SIZE is the number of values and it must a whole number.

int number[5];

To access the elements of an array, use indexes. Indexes start


from 0 and the last one is SIZE-1

number[0]=10;
number[1]=20;
number[2]=30;
number[3]=40;
number[4]=50;

#include<stdio.h>
main()
{
int num[5],sum;

printf("Enter first number: ");


scanf("%d",&num[0]);

printf("Enter second number: ");


scanf("%d",&num[1]);

printf("Enter thrid number: ");


scanf("%d",&num[2]);

printf("Enter fourth number: ");


scanf("%d",&num[3]);

printf("Enter fifth number: ");


scanf("%d",&num[4]);

printf("First number: %d\n",num[0]);


printf("Second number: %d\n",num[1]);
printf("Third number: %d\n",num[2]);
printf("Fourth number: %d\n",num[3]);
printf("Fifth number: %d\n",num[4]);

sum=num[0]+num[1]+num[2]+num[3]+num[4];

printf("The sum = %d\n",sum);


}

Remember:Looping Control structures

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]);
}

printf("First number: %d\n",num[0]);


printf("Second number: %d\n",num[1]);
printf("Third number: %d\n",num[2]);
printf("Fourth number: %d\n",num[3]);
printf("Fifth number: %d\n",num[4]);

sum=num[0]+num[1]+num[2]+num[3]+num[4];

printf("The sum = %d\n",sum);


}

#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]);
}

printf("Number entered are: \n");


for(index=0;index<5;index++)
{
printf("Number %d: %d\n",index+1,num[index]);

sum=num[0]+num[1]+num[2]+num[3]+num[4];

printf("The sum = %d\n",sum);


}
#include<stdio.h>
main()
{
int num[5],index,sum=0;

for(index=0;index<5;index++)
{
printf("Enter number %d: ",index+1);
scanf("%d",&num[index]);

sum=sum+num[index];
}

printf("Number entered are: \n");


for(index=0;index<5;index++)
{
printf("Number %d: %d\n",index+1,num[index]);

printf("The sum = %d\n",sum);


}

#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];
}

printf("Number entered are: \n");


for(index=0;index<5;index++)
{
printf("Number %d: %d\n",index+1,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];
}

printf("Number entered are: \n");


for(index=0;index<5;index++)
{
printf("Number %d: %d\n",index+1,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

Structure (struct) is a data structure used to store elements of different


data types using/under the same name.

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;

printf("The area = %f\n",area);


}

Example:
#include<stdio.h>
struct Rectangle
{

float length
int width;

};

main()
{
struct Rectangle rect;
float area;

printf("Enter the length: ");


scanf("%f",&rect.l);
printf("Enter the width: ");
scanf("%f",&rect.w);

area=rect.l*rect.w;

printf("The area = %f\n",area);


}

Example 2:
#include<stdio.h>
struct Student
{

char name[40];
int age;
};

main()
{
struct Student s;
printf("Enter the name: ");
gets(s.name);

printf("Enter the age: ");


scanf("%d",&s.age);
printf("The name: %s\n",s.name);
printf("The age: %d\n",s.age);
}

Create a structure called student with the


following specification
name= Timothy Agevi
age = 19

#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);
}

Built in functions for string handling


string.h#
The following macros are built into the file string.h
strcat() Appends a string
strchr() Finds first occurrence of a given character

strcmp() Compares two strings

strcmpi() Compares two strings, non-case sensitive

strcpy() Copies one string to another

strlen() Finds length of a string

strlwr() Converts a string to lowercase


strncat() Appends n characters of string

strncmp() Compares n characters of two strings

strncpy() Copies n characters of one string to another

strnset() Sets n characters of string to a given character

strrchr() Finds last occurrence of given character in string

strrev() Reverses string

strset() Sets all characters of string to a given character

strspn() Finds first substring from given character set in string

strupr() Converts string to uppercase

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<<"Enter details of student 1:\n";


cout<<"----------------------------\n";
cout<<"Enter the age: ";
scanf"%d",&stud.age;

cout<<"Enter the name: ";


getsstud.name;

cout<<"Enter gender: ";


getsstud.gender;

cout<<"Enter the Registration number: ";


getsstud.regNumber;

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<<"Enter details of student 2:\n";


cout<<"----------------------------\n";
cout<<"Enter the age: ";
scanf"%d",&stud2.age;

cout<<"Enter the name: ";


getsstud2.name;

cout<<"Enter gender: ";


getsstud2.gender;

cout<<"Enter the Registration number: ";


getsstud2.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<<"Enter details of student 3:\n";


cout<<"----------------------------\n";
cout<<"Enter the age: ";
scanf"%d",&stud3.age;

cout<<"Enter the name: ";


getsstud3.name;

cout<<"Enter gender: ";


getsstud3.gender;

cout<<"Enter the Registration number: ";


getsstud3.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;

printf("USER DETAILS ENTRY\n");


printf("*******************\n");
printf("Enter name: ");
scanf("%s",pr.name);

printf("Enter contacts: ");


scanf("%s",pr.contacts);

printf("Enter salary: Kshs. ");


scanf("%f",&pr.salary);

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");

printf("Enter quantity: ");


scanf("%d",&quantity);

totalPrice=quantity*Sugar.UnitPrice;

printf("Uchumi SuperMarket: Reciept\n");


printf("-----------------------------\n");
printf("Product Code\t | Product Name\t | Unit Price\t| Quantity\t|Total
Price\n");

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");

printf("Enter quantity of Sugar: ");


scanf("%d",&quantity);

totalPrice=quantity*Sugar.UnitPrice;

printf("Enter quantity of Milk: ");


scanf("%d",&quantity1);

totalPrice2=quantity1*Milk.UnitPrice;

printf("Uchumi SuperMarket: Reciept\n");


printf("-----------------------------\n");

printf("Product Code\t | Product Name\t | Unit Price\t| Quantity\t|Total


Price\n");

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);
}

ENUMERATED DATA TYPES


*********************
THIS IS A STRUCTURE THAT GIVES YOU AN OPORTUNITY TO
INVENT YOUR OWN DATA TYPE AND DEFINE THE VALUES THE
VARIABLE OF THIS DATA TYPE CAN TAKE.

EXAMPLE:
WE COULD INVENT A DATA TYPE CALLED GENDER WHICH CAN HAVE
TWO2 POSSIBLE VALUES - MALE OR FEMALE

THE FORMAT IS SIMILAR TO STRUCT.

SYNTAX:

enum enum_name
{
value1,
value2,
value3
};

enum enum_name instance1,instance2;

Example:

enum gender
{
male,female

};

struct student
{
int age;
char name[20];
char regNumber[20];
enum gender g;
};
main

struct student stud;

cout<<"Enter the details of the student\n";


cout<<"---------------------------------\n ";

cout<<"Enter the age: ";


scanf"%d",&stud.age;

cout<<"Enter the name: ";


getsstud.name;
cout<<"Enter the Registration number: ";
getsstud.regNumber;

cout<<"Enter 0 for male and 1 for female\n";


scanf"%d",&stud.g;

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";

cout<<"Reg Number: %s\n",stud.regNumber;

return 0;
}

LIKE STRUCTURES, THE DECLRATION HAS GOT TWO PARTS:

aFIRST PART DECLARES THE TYPE AND POSSIBLE VALUES.


THESE VALUES ARE CALLED ENUMERATORS.
bSECOND PART DECLARES VARIABLE OF THIS TYPE.

INTERNALLY, THE COMPILER TREATS THE ENUMARATORS AS


INTEGERS.EACH VALUE ON THE LIST OF PERMISSIBLE VALUES
CORRESPONDS TO INTEGER STARTING WITH 0.
THUS IN OUR EXAMPLE MALE IS STORED AS
0, MARRIED IS STORED AS 1.

#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<<"Enter the employee name: ";


getsemp.name;

cout<<"Enter the age: ";


scanf"%d",&emp.age;

cout<<"Enter the basic salary: ";


scanf"%f",&emp.basic_salary;

cout<<"Enter the department: \n";


cout<<"0 for assembly, 1 for manufacturing,2
for accounts and 3 for stores";
scanf"%d",&emp.department;

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

typedef existing_data_type new_data_type;

int x;

typedef int age;

age height;

IN THIS DECLARATION, age IS A USER DEFINED DATA TYPE


WHICH IS EQUIVALENT TO TYPE INT.

HENCE THE DECLRATION age height,weight -


is equivalent to int height, weight;

SIMILARLY, THE DECLARATIONS,


typedef float height[100];
height men,woman; - define height as a 100- element
floating type array.

You might also like