PROBLEM SOLVING APPROACH USING C++
What is problem solving?
Problem solving is the process of spelling out the steps required to accomplish a task before telling the computer what to do. A program is written to tell a computer what to do. But wait, what is the job you want the computer to perform for you? This job is what we call the problem. This activity (stating what to be done) carried out by a programmer is called problem solving or problem analysis.
Elements to solve a task
Most software applications that do important and momentous things are made up of very long lines of codes. Of course, such software as ATM (Automated Teller Machine), USSD (Unstructured Supplementary Service Data) code programmed into your SIM to perform certain actions like mobile banking, checking NIN (National Identification Number) / BVN (Bank Verification Number) number etc; Operating systems for computer system like windows, linux etc; Compiler for programming languages like C++ compiler, Pascal compiler etc; are the most logically complex things created by programmers. Hence, there is need to structure the problems appropriately, so that the code can be easy to follow, maintain (modify and add new features); even when the original programmer is not available to be consulted.
The three elements required to solve a task are:
top-down analysis, modular structure and structured coding
Top-down analysis: this is a method (or the process) of solving problems ourselves by stating every step for the computer to accomplish a task. It reduces the complexity of the process because it tells you how to start and guides you through the entire process.
Modular programming: this is a method of organizing many instructions and breaking large programs into separate smaller units called modules or subprograms or subroutines. Each module consists of a set of instructions to be performed by the computer and has a specific job to do.
Structured coding: this is a method of organizing modules within various control structures which determines that order in which the instructions will be executed. The control structures have a program flow called sequence, selection and repetition, while the pattern of execution handled sequentially, conditionally an respectively.
HINT: We will solve a task using the three elements of structured programming, this approach allows more than one person to write code for a software project, because the tasks are subdivided into modules, thus it reduces the time to accomplish a task and addresses the problem of complexity.
You can use different constructs (such as variables, selection, loop, array, method, class and object etc) and approach (simple logic, method, class and object) to solve a problem but that should be after careful consideration. Ensure you specify what you want to achieve.
Before you start writing your code, you need to analyse the code functionalities by showing how the software application will look like: sketch a high or low fidelity diagram either by hand or using prototype tool like Figma, just in mind etc
The diagram will serve as a road map when coding begins.
You need to determine whether the program will be written using Console Line Interface (CLI) or Graphical User Interface (GUI) approach.
You also need to indicate whether or not your program will require a storage unit like text file or database using Structured Query Language (SQL).
The purpose of file I/O handling is to help you store information received from the user, not to lost information and to access the information in the future for further analysis or manipulation or reading, deleting or updating or searching of data elements etc.
CASE 1
Problem: Program to calculate the accumulated amount to be paid by a customer based on the money borrowed and to be repaid for a specific number of years with interest rate.
Recall: C++ is case sensitive, for example love is not the same as Love or LOVE variable
using Dev-C++: Save the program, click execute, select compile and run option.
Other IDEs that can be used are Code-Blocks, C++-Builder, Visual Studio, RAD Studio
creating a file: file -> new -> source file -> save it (click file -> save as -> select a location -> type a file name then save)
Three ways to achieve the task or solve the problem
We will write the program in three different ways and achieve the same result. Using simple logic approach (it uses variables and primitive data types), using Method or function (it allows code reusability) and using class and object (it combines both simple logic and method approach together for code to be more efficient and easy to manage; it also allows user defined datatype to be created).
Parameters
p : Principal Amount,
t : Time,
r : Rate of interest in percentage
n : number of months per annum
Algorithm (step by step)
declare variables and initialize them: p = 20000, r = 0.08, n = 12, t = 40
Calculate f = p * ((1 + r/n) ^ (n*t));
Display the accumulated amount.
//USING SIMPLE LOGIC APPROACH
#include <iostream>
#include <cmath> //inbuilt function to handle exponent operator, pow
using namespace std;
int main()
{
//declare variables and assume that the variables are initialized
double f, p = 20000, r = 0.08, n = 12, t = 40;
//process the formula which represents the functionality
f = p * pow((1 + r/n), (n*t));
//display output
cout << "The accumulated amount to be paid is" <<endl;
cout<<f;
return 0;
}
//USING FUNCTION APPROACH
#include <iostream>
#include <cmath>
using namespace std;
//create function
float futureAmt( int p, float r, int n, int t) {
float f;
f = p * pow((1 + r/n), (n*t));
return f;
}
int main() {
int p = 20000;
float r = 0.08;
int n = 12;
int t = 40;
float answer;
//call function
answer = futureAmt(p, r, n, t);
cout << answer << endl;
cout << "The accumulated amount to be paid is" << answer <<endl;
// cout << "The total amount is: " << p + answer;
return 0;
}
USING CLASS AND OBJECT APPROACH
#include <iostream>
#include <cmath>
using namespace std;
//create class
class futureAmt
{
private:
double p, r, n, t;
double f;
//method getter will handle the user action (accept input data elements)
public:
void getter ( )
{
cout <<" Enter Principal Amount, rate, number of months per annum, time:: "<<endl;
//to accept multiple data elements
cin>>p >>r >>n >>t;
f = p * pow((1 + r/n), (n*t));
}
//method getter will handle the output of the data elements
void setter( )
{
cout<<"\n Entered Details are :: \n";
cout<<"\n Principal Amount: "<<p;
cout <<"\n\n Rate of Interest: "<<r;
cout <<"\n\n Number of months per annum: "<<t;
cout <<"\n\n Number of years: "<<t;
cout <<"\n\n The accumulated amount is :: "<<f;
}
};
int main ()
{
//create object from the class
futureAmt f1 ;
f1.getter ( );
f1.setter ( );
return 0;
}
In the above code,
Instead of using the primitive datatype fto declare f1(the object), we use our user defined datatype (the class name) as the datatype for the object that was created from the class we defined.
Also, we use the dot syntax to bind the object to the method responsible for handling user action and display of data elements.
CASE 2:
2-in-1 Mathematical Calculator Program
This program will help students to learn formulas like simple interest, volume cuboid
//complete code
//create header files
#include<iostream>
using namespace std;
//create methods / functions
// we make the method global so that it can be accessed anywhere within the program
void menuoption();
void sinterest();
void vcuboid();
int main(){
int choice;
//call meuoption() method
menuoption();
//accept input
cout<<"\n\t --Enter your choice-- | ";
cin>>choice;
//menu to select
switch(choice){
case 1:
sinterest(); //call sinterest() method
break;
case 2:
vcuboid(); //call vcuboid() method
break;
case 3:
cout<<"\t --Thank You \n We hope you find the program interesting-- "<<endl;
break;
default:
system("cls"); //to clear the screen
cout<<"\t --Please check the selected option \n Try again-- "<<endl;
main(); //take control to the main body
}
return 0;
}
/*to make empty method
void vcuboid(){
}
*/
void menuoption(){
//display menu option
cout<<"\t_________\n\n";
cout<<"\tWeclcome to MATHEMATICAL EXERCISE page\n\n"<<endl;
cout<<"\t This program will assist you to practice with formulas\n\n"<<endl;
cout<<"\t_________ MENU __________\n\n";
cout<<"\t | --Press 1 for SIMPLE INTEREST-- | "<<endl;
cout<<"\t | --Press 2 for VOLUME OF CUBOID-- | "<<endl;
cout<<"\t | --Press 3 to EXIT APPLICATION-- | "<<endl;
}
void sinterest(){
float p,r,t;
float si;
system("cls");
cout<<"\t_________\n\n";
cout<<"\t Simple Interest Formula:: si = (p*r*t)/100 \n\n";
cout<<"\t_________\n\n";
cout<<"\t --Enter the principal amount"<<endl;
cin>>p;
cout<<"\t --Enter the rate (whole number)"<<endl;
cin>>r;
cout<<"\t --Enter the time (in years)"<<endl;
cin>>t;
//calculate
si = (p*r*t)/100;
//display output
cout<<"\n\t The Simple Interest is:: "<<si<<endl;
main();
}
void vcuboid(){
float l,w,h;
float volume;
system("cls");
cout<<"\t_________\n\n";
cout<<"\t Volume of cuboid Formula:: volume = l * w * h \n\n";
cout<<"\t_________\n\n";
cout<<"\t --Enter the length"<<endl;
cin>>l;
cout<<"\t --Enter the width"<<endl;
cin>>w;
cout<<"\t --Enter the height"<<endl;
cin>>h;
//calculate
volume = l * w * h;
//display output
cout<<"\n\t The volume of the cuboid is:: "<<volume<<endl;
main();
}
OUTPUT
In the code above, we need understand the way the three methods or functions work. By using function, we were able to manage our code separately, which allows for easy editing and code resusability.
Void as a Method Return Type
When void is used as a return type for a function or method, it means that the method does not have parameters and it returns no value
The void method processes its task and then returns control to the caller. The void method is a stand-alone statement. Hence, you can declare a method once and call it as many times as you want, this proves that method allows maximum reusability of codes.
Here, after the method sinterest() accomplishes its task, it returns control to the main() body within the switch case for execution to be completed.
CASE 3: FILE I/O HANDLING
Output File Stream (ofstream)
Phase 1a: Typing the file name directly in the program (source file)
algorithm
step1: create header files
step2: declare file stream variable (just the way you declare a variable with primitive datatypes)
step3: open a file to write to
step4: write information to the file
step5: close the file stream - just the way you open and close ms-word
//code implementation
//create header files
#include<iostream>
#include<fstream>
using namespace std;
int main(){
//declare file stream variable
ofstream outfile;
//open a file to write to
outfile.open("myclient.txt");
//write information to the file
//the variable outfile acts like cout function of c++
outfile << "The Lord is good to me and He is my shepherd" <<endl;
//close the file stream - just the way you open and close ms-word
//we want to close the file after execution is completed
//so as not to hinder other programs from running
outfile.close();
return 0;
}
NB: The file will be created inside document directory by default, open to view it. Although you can also change the default directory. Meanwhile, if you write another information in the file, it will replace the content of the file using Phase 1 approach.
To overcome phase 1a limitation, you need to use the append (app) parameter.
Phase 1b: Using the "app" mode in file handling
//create header files
#include<iostream>
#include<fstream>
using namespace std;
int main(){
//declare file stream variable
ofstream outfile;
//open a file to write to
outfile.open("myclient.txt", ios::app);
//write information to the file
outfile << "The Lord is good to me and He is my shepherd" <<endl;
outfile << "I shall not want" <<endl;
//close the file stream
outfile.close();
return 0;
}
HINT: when you run the above code, it will not replace the initial content of myclient.txt, it will add the new content to the tail end. you can also type new content again, execute the code to view the new content in myclient.txt.
Phase 1c: Using the "app" mode in file handling with selection statement
//create header files
#include<iostream>
#include<fstream>
using namespace std;
int main(){
//declare file stream variable
ofstream outfile;
//open a file to write to
outfile.open("myclient.txt", ios::app);
if(outfile.is_open()){
//write information to the file
outfile << "God is wonderful to us" <<endl;
}
else{
cout<<"Something went wrong"<<endl;
}
//close the file stream
outfile.close();
return 0;
}
Phase 2: Asking the user for a file name after executing the program (source file)
//code implementation
//create header files
#include<iostream>
#include<fstream>
#include<string> //to save the file as a string variable
using namespace std;
int main(){
//declare file stream variable
string userfilename;
ofstream outfile;
//get the name of the file to be created
cout << "Enter the filename: ";
cin >> userfilename;
//open a file to write to
outfile.open(userfilename);
//write information to the file
outfile << "I am learning file handling in C++" <<endl;
//close the file stream
return 0;
}
HINT: After running the program, the user can type any file name of their choice (e.g studentrecord.txt), then check the document directory to view.
Phase 3: Asking the user for a file name and content to be typed after executing the program (source file)
//code implementation
//create header files
#include<iostream>
#include<fstream>
#include<string> //to save the file as a string variable
#include<climits> //to handle INT_MAX
using namespace std;
int main(){
//declare file stream variable
string userfilename;
string msg;
ofstream outfile;
//get the name of the file to be created
cout << "Enter the filename: ";
cin >> userfilename;
//INT_MAX is a predefined constant, representing the largest number integer can hold
//ignore when it gets to a new line (\n)
//to help get a new line of text for user to type his content
cin.ignore(INT_MAX, '\n');
//get the content to be stored
cout << "Enter the content: ";
//if you use only cin >> msg;, it will truncate your content, hence we need use getline
getline(cin, msg);
//open a file to write to
outfile.open(userfilename);
//write information to the file
outfile << msg <<endl;
//close the file stream
return 0;
}
CASE 4:
Login and Registration Page
Constructs to be used to handle the code functionalities are:
variables, escape sequence (use to decorate the page for spacing, alignment etc), selection statement (if-else, switch case), loop (while), operator (arithmetic ==, logical &&), methods, fstream (ifstream, ofstream) etc.
After running the code, a text file will be created in your document directory called mydata.txt, this will help store all the information entered by your users.
Basically, the code will allow users to perform operations like registration, login, forgot password and exit the application
//create header files
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
//create methods / functions
void login();
void tregister();
void forgot();
int main(){
int choice;
//display menu option
cout<<"\t_________\n\n";
cout<<"\tWeclcome to the LOGIN PAGE\n\n"<<endl;
cout<<"\t_________ MENU __________\n\n";
cout<<"\t | --Press 1 to LOGIN-- | "<<endl;
cout<<"\t | --Press 2 to REGISTER-- | "<<endl;
cout<<"\t | --Press 3 for FORGOT PASSWORD -- | "<<endl;
cout<<"\t | --Press 4 to EXIT APPLICATION-- | "<<endl;
cout<<"\n\t --Enter your choice-- | ";
//accept input
cin>>choice;
//menu to select
switch(choice){
case 1:
login();
break;
case 2:
tregister();
break;
case 3:
forgot();
break;
case 4:
cout<<"\t --Thank You-- "<<endl;
break;
default:
system("cls"); //to clear the screen
cout<<"\t --Please check the selected option \n Try again-- "<<endl;
main(); //take control to the main body
}
return 0;
}
void login(){
int count;
string userid, password, id, pass;
system("cls");
cout<<"\t --Please enter the username and password"<<endl;
cout<<"\t USERNAME:: ";
cin>>userid;
cout<<"\t PASSWORD:: ";
cin>>password;
//file handling operation
ifstream inp("mydata.txt"); //read to file AND validate if u, p exist
//check if u, p match with the data in the file
while (inp>>id>>pass){
if(id==userid && pass==password){
count = 1;
system("cls");
}
}
inp.close();
if(count==1){
cout<<userid<<"\n -- You have successfully login \n You are welcome!";
main();
}
//if u,p is not found
else{
cout<<"\n -- Something went wrong \n check username and password";
main();
}
}
void tregister(){
string ruserid, rpassword, rid, rpass;
system("cls");
cout<<"\t --Please enter the username"<<endl;
cin>>ruserid;
cout<<"\t --Pleaase enter the password"<<endl;
cin>>rpassword;
//file handling operation
ofstream outp("mydata.txt", ios::app); //write to file
outp<<ruserid<<' '<<rpassword<<endl;
system("cls");
cout<<"\n -- You have successfully registered \n Welcome";
main();
}
void forgot(){
int opt;
system("cls");
//1. ask user to search for their userid and 2. go back the main menu
cout<<"\t --Forgot password"<<endl;
cout<<"Press 1 to search your USERNAME ID"<<endl;
cout<<"Press 2 to go back to the MAIN MENU"<<endl;
cout<<"\t Enter your choice: ";
cin>>opt;
switch(opt){
case 1: {
int count = 0;
string suserid, sid, spass;
cout<<"\t --Enter the USERNAME you remember"<<endl;
cin>>suserid;
ifstream outp2("mydata.txt");
while(outp2>>sid>>spass){
if(sid==suserid){
count=1;
}
}
outp2.close();
if(count==1){
cout<<"\n Your account exist!"<<endl;
cout<<"\n Your password is:: "<<spass;
main();
}
else{
cout<<"\n Sorry, Your account does not exist"<<endl;
main();
}
break;
}
case 2:{
main();
break;
}
default:
cout<<"\n\t -- Something went wrong \n Please try again";
forgot(); //call this method to allow the user try again
}
}
Comments
Post a Comment