0% found this document useful (0 votes)
17 views117 pages

08 - Algorithms & Problem Solving Level 4

Uploaded by

AMG Malath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views117 pages

08 - Algorithms & Problem Solving Level 4

Uploaded by

AMG Malath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

Problem #01

recursion ‫حل السؤال باستخدام ال‬


‫الحل‬
#include<iostream>
#include<string>
using namespace std;
string NumberToText(long long Number) {
if (Number == 0){
return"";
}
if (Number >= 1 && Number <= 19){
string arr[] = { "", "One","Two","Three","Four","Five","Six",
"Seven", "Eight","Nine","Ten","Eleven","Twelve",
"Thirteen","Fourteen", "Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen" };
return arr[Number] + " ";}

if (Number >= 20 && Number <= 99){


string arr[] = { "","","Twenty","Thirty","Forty","Fifty",
"Sixty","Seventy","Eighty","Ninety" };
return arr[Number / 10] + " " + NumberToText(Number % 10);}

if (Number >= 100 && Number <= 199){


return"One Hundred " + NumberToText(Number % 100);}

if (Number >= 200 && Number <= 999){


return NumberToText(Number / 100) + "Hundreds " + NumberToText(Number % 100);}

if (Number >= 1000 && Number <= 1999){


return"One Thousand " + NumberToText(Number % 1000);
}

if (Number >= 2000 && Number <= 999999) {


return NumberToText(Number / 1000) + "Thousands " + NumberToText(Number % 1000);
}

if (Number >= 1000000 && Number <= 1999999) {


return"One Million " + NumberToText(Number % 1000000); }
if (Number >= 2000000 && Number <= 999999999) {
return NumberToText(Number / 1000000) + "Millions "
+ NumberToText(Number % 1000000); }

if (Number >= 1000000000 && Number <= 1999999999) {


return"One Billion " + NumberToText(Number % 1000000000);
}

else { return NumberToText(Number / 1000000000) + "Billions " +


NumberToText(Number % 1000000000); } }

long long ReadNumber() {


long long Number;
cout << "\nEnter a Number? ";
cin >> Number;
return Number; }

int main() {
long long Number = ReadNumber();
cout << NumberToText(Number);

system("pause>0");

return 0; }
Problem #02
‫الحل‬
#include<iostream>
using namespace std;

bool IsLeapYear(short Year) {


// leap year if perfectly divisible by 400
if (Year % 400 == 0) { return true;
}
// not a leap year if divisible by 100// but not divisible by 400
else if (Year % 100 == 0) { return false;}
// leap year if not divisible by 100// but divisible by 4
else if (Year % 4 == 0) { return true;}
// all other years are not leap years
else { return false;} }

short ReadYear() {
short Year;
cout << "\nPlease enter a year to check? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();

if (IsLeapYear(Year))
cout << "\nYes, Year [" << Year << "] is a leap year.\n";
else
cout << "\nNo, Year [" << Year << "] is NOT a leap year.\n";

system("pause>0"); return 0; }
Problem #03
‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short ReadYear() {
short Year;
cout << "\nPlease enter a year to check? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();
if (isLeapYear(Year))
cout << "\nYes, Year [" << Year << "] is a leap year.\n";
else
cout << "\nNo, Year [" << Year << "] is NOT a leap year.\n";

system("pause>0"); return 0; }
Problem #04
‫ لوحدها‬function ‫اعمل كل سطر في‬
‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short NumberOfDaysInAYear(short Year) {


return isLeapYear(Year) ? 366 : 365; }

short NumberOfHoursInAYear(short Year) {


return NumberOfDaysInAYear(Year) * 24; }

int NumberOfMinutesInAYear(short Year) {


return NumberOfHoursInAYear(Year) * 60; }

int NumberOfSecondsInAYear(short Year) {


return NumberOfMinutesInAYear(Year) * 60; }

short ReadYear() { short Year;


cout << "\nPlease enter a year to check? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();

cout << "\nNumber of Days in Year [" << Year << "] is "
<< NumberOfDaysInAYear(Year);

cout << "\nNumber of Hours in Year [" << Year << "] is "
<< NumberOfHoursInAYear(Year);

cout << "\nNumber of Minutes in Year [" << Year << "] is "
<< NumberOfMinutesInAYear(Year);

cout << "\nNumber of Seconds in Year [" << Year << "] is "
<< NumberOfSecondsInAYear(Year);

system("pause>0"); return 0; }
Problem #05
‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
if (Month == 2){ return isLeapYear(Year) ? 29 : 28;}

short arr31Days[7] = { 1,3,5,7,8,10,12 };


for (short i = 1; i <= 7; i++){
if (arr31Days[i - 1] == Month) return 31;}
//if you reach here then its 30 days.
return 30; }

short NumberOfHoursInAMonth(short Month, short Year) {


return NumberOfDaysInAMonth(Month, Year) * 24; }

int NumberOfMinutesInAMonth(short Month, short Year) {


return NumberOfHoursInAMonth(Month, Year) * 60; }

int NumberOfSecondsInAMonth(short Month, short Year) {


return NumberOfMinutesInAMonth(Month, Year) * 60; }

short ReadMonth() {
short Month;
cout << "\nPlease enter a Month to check? ";
cin >> Month;
return Month; }

short ReadYear() {
short Year;
cout << "\nPlease enter a year to check? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();
short Month = ReadMonth();
cout << "\nNumber of Days in Month [" << Month << "] is " << NumberOfDaysInAMonth(Month, Year);
cout << "\nNumber of Hours in Month [" << Month << "] is " << NumberOfHoursInAMonth(Month, Year);
cout << "\nNumber of Minutes in Month [" << Month << "] is " << NumberOfMinutesInAMonth(Month, Year);
cout << "\nNumber of Seconds in Month [" << Month << "] is " << NumberOfSecondsInAMonth(Month, Year);

system("pause>0"); return 0; }
Problem #06

‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int NumberOfDays[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };

return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : NumberOfDays[Month - 1]; }

short ReadMonth() {
short Month;
cout << "\nPlease enter a Month to check? ";
cin >> Month;
return Month; }

short ReadYear() {
short Year;
cout << "\nPlease enter a year to check? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();
short Month = ReadMonth();
cout << "\nNumber of Days in Month [" << Month << "] is " << NumberOfDaysInAMonth(Month, Year);

system("pause>0");
return 0; }
Problem #07

‫ ده الساعه القديمه ماحدش بيستخدمها دلوقتي‬julian calender ‫ال‬


‫ دي التقويم الهجري‬hijri calender ‫ وفيه ال‬Georgian calener ‫هنستخدم ال‬
‫ سطور وتطبق عالمعادله عشان تجيب اليوم‬3 ‫المطلوب تعمل المتغيرات اللي في اول‬
‫واالسبوع بيبدا من يوم االحد‬
‫زي المثال اللي جاي‬

‫الحل‬
#include<iostream>
using namespace std;

short DayOfWeekOrder(short Day, short Month, short Year) {


short a, y, m;
a = (14 - Month) / 12;
y = Year - a;
m = Month + (12 * a) - 2;
// Gregorian://0:sun, 1:Mon, 2:Tue...etc
return (Day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7; }

string DayShortName(short DayOfWeekOrder) {


string arrDayNames[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
return arrDayNames[DayOfWeekOrder]; }

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "\nPlease enter a Month? ";
cin >> Month;
return Month; }

short ReadYear() {
short Year;
cout << "\nPlease enter a year? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();
short Month = ReadMonth();
short Day = ReadDay();
cout << "\nDate :" << Day << "/" << Month << "/" << Year;
cout << "\nDay Order : " << DayOfWeekOrder(Day, Month, Year);
cout << "\nDay Name : " << DayShortName(DayOfWeekOrder(Day, Month, Year));

system("pause>0");
return 0; }
Problem #08

‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short DayOfWeekOrder(short Day, short Month, short Year) {


short a, y, m;
a = (14 - Month) / 12;
y = Year - a;
m = Month + (12 * a) - 2;
// Gregorian://0:sun, 1:Mon, 2:Tue...etc
return (Day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7; }

string DayShortName(short DayOfWeekOrder) {


string arrDayNames[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
return arrDayNames[DayOfWeekOrder]; }

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1]; }

string MonthShortName(short MonthNumber) {


string Months[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
return (Months[MonthNumber - 1]); }

void PrintMonthCalendar(short Month, short Year) {


int NumberOfDays;
// Index of the day from 0 to 6
int current = DayOfWeekOrder(1, Month, Year);
NumberOfDays = NumberOfDaysInAMonth(Month, Year);
// Print the current month name
printf("\n _______________%s_______________\n\n",
MonthShortName(Month).c_str());
// Print the columns
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
// Print appropriate spaces
int i;
for (i = 0; i < current; i++)
printf(" ");

for (int j = 1; j <= NumberOfDays; j++){


printf("%5d", j);

if (++i == 7){
i = 0;
printf("\n");}}

printf("\n _________________________________\n");
}
short ReadMonth() {
short Month;
cout << "\nPlease enter a Month? ";
cin >> Month;
return Month; }

short ReadYear() {
short Year;
cout << "\nPlease enter a year? ";
cin >> Year;
return Year; }

int main() {
short Year = ReadYear();
short Month = ReadMonth();
PrintMonthCalendar(Month, Year);

system("pause>0"); return 0; }

‫ده الحل بتاعي اعتقد انه ابسط شويه‬


void PrintMonhCalender(short Year, short Month) {

string stMonth = Dates::GetMonthName(Month);


short NumberOfDays = Dates::NumberOfDaysInAMonth(Year,Month);
short StartingDay = DayOfWeekOrder(1,Month,Year);
short Counter = 0;
cout << " ______________"<<stMonth<<"________________\n\n";
cout << " Sun Mon Tue Wed Thu Fri Sat" << endl;
for (short i = 1; i <= NumberOfDays+StartingDay;i++) {

if (i>=StartingDay+1&&Counter<=NumberOfDays-1) {
Counter++;
cout << " " <<setw(3)<< Counter;
}
else { cout << " "; }
if (i % 7 == 0) { cout << endl; }

}
cout << "\n _________________________________\n\n";
}
Problem #09

‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year){


// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short DayOfWeekOrder(short Day, short Month, short Year) {


short a, y, m;
a = (14 - Month) / 12;
y = Year - a;
m = Month + (12 * a) - 2;

// Gregorian:
//0:sun, 1:Mon, 2:Tue...etc
return (Day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7; }

string DayShortName(short DayOfWeekOrder) {


string arrDayNames[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
return arrDayNames[DayOfWeekOrder]; }

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1]; }

string MonthShortName(short MonthNumber) {


string Months[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec" };
return (Months[MonthNumber - 1]); }

void PrintMonthCalendar(short Month, short Year) {


int NumberOfDays;
// Index of the day from 0 to 6
int current = DayOfWeekOrder(1, Month, Year);
NumberOfDays = NumberOfDaysInAMonth(Month, Year);
// Print the current month name
printf("\n _______________%s_______________\n\n",
MonthShortName(Month).c_str());
// Print the columns
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
// Print appropriate spaces
int i; for (i = 0; i < current; i++)
printf(" ");

for (int j = 1; j <= NumberOfDays; j++){


printf("%5d", j);
if (++i == 7){
i = 0;
printf("\n");
}
}
printf("\n _________________________________\n"); }

void PrintYearCalendar(int Year) {


printf("\n _________________________________\n\n");
printf(" Calendar - %d\n", Year);
printf(" _________________________________\n");

for (int i = 1; i <= 12; i++) {


PrintMonthCalendar(i, Year); }
return; }

short ReadYear() {
short Year;
cout << "\nPlease enter a year? ";
cin >> Year;
return Year; }

int main() {
PrintYearCalendar(ReadYear());
system("pause>0"); return 0; }
Problem #10

‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12)
return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1]; }

short NumberOfDaysFromTheBeginingOfTheYear(short Day, short Month, short Year) {


short TotalDays = 0;

for (int i = 1; i <= Month - 1; i++){


TotalDays += NumberOfDaysInAMonth(i, Year);
}
TotalDays += Day;
return TotalDays; }

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day; }

short ReadMonth() {
short Month;
cout << "\nPlease enter a Month? ";
cin >> Month;
return Month; }

short ReadYear() {
short Year;
cout << "\nPlease enter a Year? ";
cin >> Year;
return Year; }

int main() {
short Day = ReadDay();
short Month = ReadMonth();
short Year = ReadYear();

cout << "\nNumber of Days from the begining of the year is "
<< NumberOfDaysFromTheBeginingOfTheYear(Day, Month, Year);

system("pause>0"); return 0; }
Problem #11

‫الحل‬
#include<iostream>
using namespace std;

bool isLeapYear(short Year) {


return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); }

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12)
return 0;

int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };


return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1]; }

short NumberOfDaysFromTheBeginingOfTheYear(short Day, short Month, short Year) {


short TotalDays = 0;
for (int i = 1; i <= Month - 1; i++){
TotalDays += NumberOfDaysInAMonth(i, Year);}
TotalDays += Day;
return TotalDays; }

struct sDate{ short Year; short Month; short Day; };


sDate GetDateFromDayOrderInYear(short DateOrderInYear, short Year) {
sDate Date;
short RemainingDays = DateOrderInYear;
short MonthDays = 0;
Date.Year = Year;
Date.Month = 1;

while (true) {
MonthDays = NumberOfDaysInAMonth(Date.Month, Year);
if (RemainingDays > MonthDays) {
RemainingDays -= MonthDays;
Date.Month++; }
else {
Date.Day = RemainingDays;
break; } }
return Date; }

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day; }

short ReadMonth() {
short Month;
cout << "\nPlease enter a Month? ";
cin >> Month;
return Month; }

short ReadYear() {
short Year;
cout << "\nPlease enter a Year? ";
cin >> Year;
return Year; }

int main() {
short Day = ReadDay();
short Month = ReadMonth();
short Year = ReadYear();
short DaysOrderInYear = NumberOfDaysFromTheBeginingOfTheYear(Day, Month, Year);

cout << "\nNumber of Days from the begining of the year is " << DaysOrderInYear << "\n\n";
sDate Date;
Date = GetDateFromDayOrderInYear(DaysOrderInYear, Year);

cout << "Date for [" << DaysOrderInYear << "] is: ";
cout << Date.Day << "/" << Date.Month << "/" << Date.Year;

system("pause>0"); return 0; }
Problem #12
‫الحل‬
#include<iostream>
using namespace std;

struct sDate { short Year; short Month; short Day; };

bool isLeapYear(short Year) {


return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

short NumberOfDaysFromTheBeginingOfTheYear(short Day, short Month, short Year) {


short TotalDays = 0;
for (int i = 1; i <= Month - 1; i++) {
TotalDays += NumberOfDaysInAMonth(i, Year);
}
TotalDays += Day;
return TotalDays;
}

sDate DateAddDays(short Days, sDate Date) {


short RemainingDays = Days + NumberOfDaysFromTheBeginingOfTheYear(Date.Day, Date.Month, Date.Year);
short MonthDays = 0;
Date.Month = 1;
while (true) {
MonthDays = NumberOfDaysInAMonth(Date.Month, Date.Year);
if (RemainingDays > MonthDays) {
RemainingDays -= MonthDays;
Date.Month++;
if (Date.Month > 12) {
Date.Month = 1; Date.Year++;
}
}
else {
Date.Day = RemainingDays;
break;
}
}
return Date;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "\nPlease enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "\nPlease enter a Year? ";
cin >> Year;
return Year;
}

sDate ReadFullDate() {
sDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

short ReadDaysToAdd() {
short Days;
cout << "\nHow many days to add? ";
cin >> Days;
return Days;
}

int main() {
sDate Date = ReadFullDate();
short Days = ReadDaysToAdd();
Date = DateAddDays(Days, Date);
cout << "\nDate after adding [" << Days << "] days is: ";
cout << Date.Day << "/" << Date.Month << "/" << Date.Year;
system("pause>0");
return 0;
}
Problem #13

‫الحل‬
#include<iostream>
using namespace std;

struct stDate { short Year; short Month; short Day; };

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true
: ((Date1.Year == Date2.Year) ?
(Date1.Month < Date2.Month ? true
: (Date1.Month == Date2.Month ?
Date1.Day < Date2.Day : false))
: false);
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;

return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

int main() {
stDate Date1 = ReadFullDate();
stDate Date2 = ReadFullDate();

if (IsDate1BeforeDate2(Date1, Date2))
cout << "\nYes, Date1 is Less than Date2.";
else
cout << "\nNo, Date1 is NOT Less than Date2.";

system("pause>0"); return 0;
}

Problem #14

‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
bool IsDate1EqualDate2(stDate Date1, stDate Date2) {
return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
} short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
} short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
} short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;

} int main() {
stDate Date1 = ReadFullDate();
stDate Date2 = ReadFullDate();
if (IsDate1EqualDate2(Date1, Date2))
cout << "\nYes, Date1 is Equal To Date2.";
else
cout << "\nNo, Date1 is NOT Equal To Date2.";

system("pause>0");
return 0;
}
Problem #15

‫الحل‬
#include<iostream>
using namespace std;
struct stDate {
short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
} short NumberOfDaysInAMonth(short Month, short Year) {
if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
} bool IsLastDayInMonth(stDate Date) {
return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
} bool IsLastMonthInYear(short Month) {
return (Month == 12);
} short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

int main() {
stDate Date1 = ReadFullDate();
if (IsLastDayInMonth(Date1))
cout << "\nYes, Day is Last Day in Month.";
else
cout << "\nNo, Day is Not Last Day in Month.";

if (IsLastMonthInYear(Date1.Month))
cout << "\nYes, Month is Last Month in Year.";
else
cout << "\nNo, Month is Not Last Month in Year.";

system("pause>0");
return 0;
}
Problem #16

‫ماتستخدمش الطريقه اللي قبل كده‬


‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
} bool IsLastDayInMonth(stDate Date) {
return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
} bool IsLastMonthInYear(short Month) {
return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date) {


if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
} return Date;

} short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
} short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
} short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

int main() {
stDate Date1 = ReadFullDate();
Date1 = IncreaseDateByOneDay(Date1);
cout << "\nDate after adding one day is:" << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
system("pause>0");
return 0;
}
Problem #17

‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};

bool isLeapYear(short Year) {


return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

bool IsLastDayInMonth(stDate Date) {


return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}

bool IsLastMonthInYear(short Month) {


return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date) {


if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
} return Date;
}
int GetDifferenceInDays(stDate Date1, stDate Date2, bool IncludeEndDay = false) {
int Days = 0;
while (IsDate1BeforeDate2(Date1, Date2)) {
Days++;
Date1 = IncreaseDateByOneDay(Date1);
} return IncludeEndDay ? ++Days : Days;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

int main() {
stDate Date1 = ReadFullDate();
stDate Date2 = ReadFullDate();
cout << "\nDiffrence is: " << GetDifferenceInDays(Date1, Date2) << " Day(s).";
cout << "\nDiffrence (Including End Day) is: " << GetDifferenceInDays(Date1, Date2, true) << " Day(s).";
system("pause>0");
return 0;
}
‫حلي باختصار انه الفرق هيكون مجموع عدد االيام بكل سنه بداية من سنه التاريخ االول الي سنة التاريخ الثاني وبعدين نطرح منهم عدد االيام من‬
‫بدايه السنه بتاعت التاريخ الثاني وعدد االيام بداية من التاريخ االول لحد ااخر سنة التاريخ االول انا فكرت في نفس حله بس قولت افرض اليوزر‬
‫ مره‬365000 ‫ سنه كده هيفضل يلف اكتر من‬1000 ‫عاوز يجيب الفرق من‬

int DifferenceBetween2Dates(stDate Date1, stDate Date2) {


int DifferenceInDays = 0;
short NumberOfDaysRemaningOfTheYearOfDate2 = NumberOfDaysInAYear(Date2.Year) -
NumberOfDaysFromBeginningOfTheYear(Date2.Day, Date2.Month, Date2.Year);

if (IsDate1BeforeDate2(Date1, Date2)) {

for (short i = Date1.Year ; i <= Date2.Year; i++) {


DifferenceInDays += NumberOfDaysInAYear(i);
}
DifferenceInDays -= NumberOfDaysRemaningOfTheYearOfDate2 +
NumberOfDaysFromBeginningOfTheYear(Date1.Day, Date1.Month, Date1.Year);
}

return DifferenceInDays;
}
Problem #18
‫الحل‬
#pragma warning(disable : 4996)
#include<iostream>
using namespace std;

struct stDate{
short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

bool IsLastDayInMonth(stDate Date) {


return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}

bool IsLastMonthInYear(short Month) {


return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date) {


if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
} return Date;
}

int GetDifferenceInDays(stDate Date1, stDate Date2, bool IncludeEndDay = false) {


int Days = 0;
while (IsDate1BeforeDate2(Date1, Date2)) {
Days++;
Date1 = IncreaseDateByOneDay(Date1);
} return IncludeEndDay ? ++Days : Days;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

stDate GetSystemDate() {
stDate Date;
time_t t = time(0);
tm* now = localtime(&t);
Date.Year = now->tm_year + 1900;
Date.Month = now->tm_mon + 1;
Date.Day = now->tm_mday;
return Date;
}

int main() {
cout << "\nPlease Enter Your Date of Birth:\n";
stDate Date1 = ReadFullDate();
stDate Date2 = GetSystemDate();
cout << "\nYour Age is : " << GetDifferenceInDays(Date1, Date2, true) << " Day(s).";
system("pause>0");
return 0;
}
Problem #19
‫بيقولك عاوز لما اليوزر يدخل التاريخ التاني اقل من التاريخ األول يطلع الفرق بالسالب‬

‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

bool IsLastDayInMonth(stDate Date) {


return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
} bool IsLastMonthInYear(short Month) {
return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date) {


if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
} return Date;
}

void SwapDates(stDate& Date1, stDate& Date2) {


stDate TempDate;
TempDate.Year = Date1.Year;
TempDate.Month = Date1.Month;
TempDate.Day = Date1.Day;
Date1.Year = Date2.Year;
Date1.Month = Date2.Month;
Date1.Day = Date2.Day;
Date2.Year = TempDate.Year;
Date2.Month = TempDate.Month;
Date2.Day = TempDate.Day;
}

int GetDifferenceInDays(stDate Date1, stDate Date2, bool IncludeEndDay = false) {


int Days = 0;
short SawpFlagValue = 1;
if (!IsDate1BeforeDate2(Date1, Date2)) { //Swap Dates SwapDates(Date1, Date2);
SawpFlagValue = -1;
} while (IsDate1BeforeDate2(Date1, Date2)) {
Days++;
Date1 = IncreaseDateByOneDay(Date1);
} return IncludeEndDay ? ++Days * SawpFlagValue : Days * SawpFlagValue;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
} int main() {
stDate Date1 = ReadFullDate();
stDate Date2 = ReadFullDate();
cout << "\nDiffrence is: " << GetDifferenceInDays(Date1, Date2) << " Day(s).";
cout << "\nDiffrence (Including End Day) is: " << GetDifferenceInDays(Date1, Date2, true) << " Day(s).";
system("pause>0");
return 0;
}
recursion ‫الحل بتاعي عن طريق ال‬
int DifferenceBetween2Dates(stDate Date1, stDate Date2, bool IncludeEndDay = false) {
int DifferenceInDays = 0;
short NumberOfDaysRemaningOfTheYearOfDate2 = NumberOfDaysInAYear(Date2.Year) -
NumberOfDaysFromBeginningOfTheYear(Date2.Day, Date2.Month, Date2.Year);
if (IsDate1BeforeDate2(Date1, Date2)) {

for (short i = Date1.Year ; i <= Date2.Year; i++) {


DifferenceInDays += NumberOfDaysInAYear(i);
}
DifferenceInDays -= NumberOfDaysRemaningOfTheYearOfDate2 +
NumberOfDaysFromBeginningOfTheYear(Date1.Day, Date1.Month, Date1.Year);
}
else if(IsDate1BeforeDate2(Date2, Date1)){
DifferenceInDays =-1* DifferenceBetween2Dates(Date2,Date1, IncludeEndDay);

return(IncludeEndDay) ? DifferenceInDays : DifferenceInDays ;


}

return (IncludeEndDay)?++DifferenceInDays:DifferenceInDays;
}
Problem #20:32
‫بتعمل داله بتضيف يوم او أسبوع واحد وبعدين بتستخدمها عشان تضيف ال ‪ x‬اللي جاي من اليوزر‬
‫يعني تعمل داله تضيف يوم واحد وداله تانيه تشغلها بال ‪ for loop‬يعني رقم اتنين في الحل بيستخدم رقم واحد‬
for loop ‫ هوا مش عايز‬faster‫لما توصل لل‬
‫الحل‬
#include<iostream>
using namespace std;
struct stDate{ short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12)
return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

bool IsLastDayInMonth(stDate Date) {


return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}

bool IsLastMonthInYear(short Month) {


return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date) {


if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
} return Date;
}
stDate IncreaseDateByOneWeek(stDate Date) {
for (int i = 1;
i <= 7;
i++) {
Date = IncreaseDateByOneDay(Date);
} return Date;
}

stDate IncreaseDateByXWeeks(short Weeks, stDate Date) {


for (short i = 1;
i <= Weeks;
i++) {
Date = IncreaseDateByOneWeek(Date);
} return Date;
}

stDate IncreaseDateByOneMonth(stDate Date) {


if (Date.Month == 12) {
Date.Month = 1;
Date.Year++;
}
else {
Date.Month++;
} //last check day in date should not exceed max days in the current month
// example if date is 31/1/2022 increasing one month should not be 31/2/2022, it should
// be 28/2/2022

short NumberOfDaysInCurrentMonth = NumberOfDaysInAMonth(Date.Month, Date.Year);


if (Date.Day > NumberOfDaysInCurrentMonth) {
Date.Day = NumberOfDaysInCurrentMonth;
} return Date;
} stDate IncreaseDateByXDays(short Days, stDate Date) {
for (short i = 1;
i <= Days;
i++) {
Date = IncreaseDateByOneDay(Date);
}
return Date;
}

stDate IncreaseDateByXMonths(short Months, stDate Date) {


for (short i = 1;
i <= Months;
i++) {
Date = IncreaseDateByOneMonth(Date);
} return Date;
}

stDate IncreaseDateByOneYear(stDate Date) {


Date.Year++;
return Date;
}

stDate IncreaseDateByXYears(short Years, stDate Date) {


for (short i = 1;
i <= Years;
i++) {
Date = IncreaseDateByOneYear(Date);
} return Date;
}

stDate IncreaseDateByXYearsFaster(short Years, stDate Date) {


Date.Year += Years;
return Date;
}

stDate IncreaseDateByOneDecade(stDate Date) {


//Period of 10 years
Date.Year += 10;
return Date;
} stDate IncreaseDateByXDecades(short Decade, stDate Date) {
for (short i = 1;
i <= Decade * 10;
i++) {
Date = IncreaseDateByOneYear(Date);
} return Date;
}
stDate IncreaseDateByXDecadesFaster(short Decade, stDate Date) {
Date.Year += Decade * 10;
return Date;
}

stDate IncreaseDateByOneCentury(stDate Date) {


//Period of 100 years
Date.Year += 100;
return Date;
}

stDate IncreaseDateByOneMillennium(stDate Date) {


//Period of 1000 years
Date.Year += 1000;
return Date;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}

int main() {
stDate Date1 = ReadFullDate();
cout << "\nDate After: \n";
Date1 = IncreaseDateByOneDay(Date1);
cout << "\n01-Adding one day is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXDays(10, Date1);
cout << "\n02-Adding 10 days is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByOneWeek(Date1);
cout << "\n03-Adding one week is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXWeeks(10, Date1);
cout << "\n04-Adding 10 weeks is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByOneMonth(Date1);
cout << "\n05-Adding one month is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXMonths(5, Date1);
cout << "\n06-Adding 5 months is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByOneYear(Date1);
cout << "\n07-Adding one year is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXYears(10, Date1);
cout << "\n08-Adding 10 Years is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXYearsFaster(10, Date1);
cout << "\n09-Adding 10 Years (faster) is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByOneDecade(Date1);
cout << "\n10-Adding one Decade is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXDecades(10, Date1);
cout << "\n11-Adding 10 Decades is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByXDecadesFaster(10, Date1);
cout << "\n12-Adding 10 Decade (faster) is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByOneCentury(Date1);
cout << "\n13-Adding One Century is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = IncreaseDateByOneMillennium(Date1);
cout << "\n14-Adding One Millennium is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
system("pause>0");
return 0;
}
Problem #33:46
‫الحل‬
#include<iostream>
using namespace std;

struct stDate{
short Year;
short Month;
short Day;
};

bool isLeapYear(short Year) {


return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}
short NumberOfDaysInAMonth(short Month, short Year) {
if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }
;
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

stDate DecreaseDateByOneDay(stDate Date) {


if (Date.Day == 1) {
if (Date.Month == 1) {
Date.Month = 12;
Date.Day = 31;
Date.Year--;
}
else {
Date.Month--;
Date.Day = NumberOfDaysInAMonth(Date.Month, Date.Year);
}
}
else {
Date.Day--;
}
return Date;
}
stDate DecreaseDateByOneWeek(stDate Date) {
for (int i = 1;
i <= 7;
i++) {
Date = DecreaseDateByOneDay(Date);
}
return Date;
}
stDate DecreaseDateByXWeeks(short Weeks, stDate Date) {
for (short i = 1;
i <= Weeks;
i++) {
Date = DecreaseDateByOneWeek(Date);
}
return Date;
}

stDate DecreaseDateByOneMonth(stDate Date) {


if (Date.Month == 1) {
Date.Month = 12;
Date.Year--;
}
else
Date.Month--;
//last check day in date should not exceed max days in the current month
// example if date is 31/3/2022 decreasing one month should not be 31/2/2022, it should
// be 28/2/2022
short NumberOfDaysInCurrentMonth = NumberOfDaysInAMonth(Date.Month, Date.Year);
if (Date.Day > NumberOfDaysInCurrentMonth) {
Date.Day = NumberOfDaysInCurrentMonth;
}
return Date;
}
stDate DecreaseDateByXDays(short Days, stDate Date) {
for (short i = 1;
i <= Days;
i++) {
Date = DecreaseDateByOneDay(Date);
}
return Date;
}
stDate DecreaseDateByXMonths(short Months, stDate Date) {
for (short i = 1;
i <= Months;
i++) {
Date = DecreaseDateByOneMonth(Date);
}
return Date;
}

stDate DecreaseDateByOneYear(stDate Date) {


Date.Year--;
return Date;
}
stDate DecreaseDateByXYears(short Years, stDate Date) {
for (short i = 1;
i <= Years;
i++) {
Date = DecreaseDateByOneYear(Date);
}
return Date;
}
stDate DecreaseDateByXYearsFaster(short Years, stDate Date) {
Date.Year -= Years;
return Date;
}
stDate DecreaseDateByOneDecade(stDate Date) { //Period of 10 yearsDate.Year -= 10;
return Date;
}
stDate DecreaseDateByXDecades(short Decade, stDate Date) {
for (short i = 1;
i <= Decade * 10;
i++) {
Date = DecreaseDateByOneYear(Date);
}
return Date;
}
stDate DecreaseDateByXDecadesFaster(short Decade, stDate Date) {
Date.Year -= Decade * 10;
return Date;
}

stDate DecreaseDateByOneCentury(stDate Date) {


//Period of 100 years
Date.Year -= 100;
return Date;
}
stDate DecreaseDateByOneMillennium(stDate Date) {
//Period of 1000 years
Date.Year -= 1000;
return Date;
}
short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
int main() {
stDate Date1 = ReadFullDate();
cout << "\nDate After: \n";
Date1 = DecreaseDateByOneDay(Date1);
cout << "\n01-Subtracting one day is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXDays(10, Date1);
cout << "\n02-Subtracting 10 days is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByOneWeek(Date1);
cout << "\n03-Subtracting one week is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXWeeks(10, Date1);
cout << "\n04-Subtracting 10 weeks is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByOneMonth(Date1);
cout << "\n05-Subtracting one month is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXMonths(5, Date1);
cout << "\n06-Subtracting 5 months is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByOneYear(Date1);
cout << "\n07-Subtracting one year is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXYears(10, Date1);
cout << "\n08-Subtracting 10 Years is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXYearsFaster(10, Date1);
cout << "\n09-Subtracting 10 Years (faster) is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByOneDecade(Date1);
cout << "\n10-Subtracting one Decade is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXDecades(10, Date1);
cout << "\n11-Subtracting 10 Decades is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByXDecadesFaster(10, Date1);
cout << "\n12-Subtracting 10 Decade (faster) is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByOneCentury(Date1);
cout << "\n13-Subtracting One Century is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
Date1 = DecreaseDateByOneMillennium(Date1);
cout << "\n14-Subtracting One Millennium is: " << Date1.Day << "/" << Date1.Month << "/" << Date1.Year;
system("pause>0");
return 0;
}

Problem #74:53
‫ اللي احنا‬structure ‫ اعمل نفس الداله بس المرادي بتاخد ال‬: ‫احنا كنا عاملين داله بتاخد يوم وشهر وسنه عشان تجيبلنا ترتيب اليوم في األسبوع‬
‫عاملينه‬
‫الحل‬
#pragma warning(disable : 4996)
#include<iostream>
using namespace std; struct stDate{ short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}
bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {
return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
short NumberOfDaysInAMonth(short Month, short Year) {
if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

bool IsLastDayInMonth(stDate Date) {


return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}
bool IsLastMonthInYear(short Month) {
return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date) {


if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
}
return Date;
}
int GetDifferenceInDays(stDate Date1, stDate Date2, bool IncludeEndDay = false) {
int Days = 0;
while (IsDate1BeforeDate2(Date1, Date2)) {
Days++;
Date1 = IncreaseDateByOneDay(Date1);
}
return IncludeEndDay ? ++Days : Days;
}

short DayOfWeekOrder(short Day, short Month, short Year) {


short a, y, m;
a = (14 - Month) / 12;
y = Year - a;
m = Month + (12 * a) - 2;
// Gregorian:
//0:sun, 1:Mon, 2:Tue...etc
return (Day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7;
}
short DayOfWeekOrder(stDate Date) {
return DayOfWeekOrder(Date.Day, Date.Month, Date.Year);
}
string DayShortName(short DayOfWeekOrder) {
string arrDayNames[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" }
;
return arrDayNames[DayOfWeekOrder];
}
short IsEndOfWeek(stDate Date) {
return DayOfWeekOrder(Date) == 6;
}
bool IsWeekEnd(stDate Date) {
//Weekends are Fri and Sat
short DayIndex = DayOfWeekOrder(Date);
return (DayIndex == 5 || DayIndex == 6);
}

bool IsBusinessDay(stDate Date) {


//Weekends are Sun,Mon,Tue,Wed and Thur
/*
short DayIndex = DayOfWeekOrder(Date);
return (DayIndex >= 5 && DayIndex <= 4);
*///shorter method is to invert the IsWeekEnd: this will save updating code.
return !IsWeekEnd(Date);
}

short DaysUntilTheEndOfWeek(stDate Date) {


return 6 - DayOfWeekOrder(Date);
}
short DaysUntilTheEndOfMonth(stDate Date1) {
stDate EndOfMontDate;
EndOfMontDate.Day = NumberOfDaysInAMonth(Date1.Month, Date1.Year);
EndOfMontDate.Month = Date1.Month;
EndOfMontDate.Year = Date1.Year;
return GetDifferenceInDays(Date1, EndOfMontDate, true);
}
short DaysUntilTheEndOfYear(stDate Date1) {
stDate EndOfYearDate;
EndOfYearDate.Day = 31;
EndOfYearDate.Month = 12;
EndOfYearDate.Year = Date1.Year;
return GetDifferenceInDays(Date1, EndOfYearDate, true);
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
stDate GetSystemDate() {
stDate Date;
time_t t = time(0);
tm* now = localtime(&t);
Date.Year = now->tm_year + 1900;
Date.Month = now->tm_mon + 1;
Date.Day = now->tm_mday;
return Date;
}

int main() {
stDate Date1 = GetSystemDate();
cout << "\nToday is " << DayShortName(DayOfWeekOrder(Date1)) << " , " << Date1.Day << "/" << Date1.Month <<
"/" << Date1.Year << endl;
//--------------------- cout << "\nIs it End of Week?\n";
if (IsEndOfWeek(Date1)) cout << "Yes it is Saturday, it's of Week.";
else cout << "No it's Not end of week.";
//--------------------- cout << "\n\nIs it Weekend?\n";
if (IsWeekEnd(Date1)) cout << "Yes it is a week end.";
else cout << "No today is " << DayShortName(DayOfWeekOrder(Date1)) << ", Not a weekend.";
//--------------------- cout << "\n\nIs it Business Day?\n";
if (IsBusinessDay(Date1)) cout << "Yes it is a business day.";
else cout << "No it is NOT a business day.";
//--------------------- cout << "\n\nDays until end of week : " << DaysUntilTheEndOfWeek(Date1) << " Day(s).";
//--------------------- cout << "\nDays until end of month : "<< DaysUntilTheEndOfMonth(Date1) << " Day(s).";
//--------------------- cout << "\nDays until end of year : " << DaysUntilTheEndOfYear(Date1) << " Day(s).";
system("pause>0");
return 0;
}
Problem #54

‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};

bool isLeapYear(short Year) {


return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}
bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {
return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
short NumberOfDaysInAMonth(short Month, short Year) {
if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }
;
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}
bool IsLastDayInMonth(stDate Date) {
return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}
bool IsLastMonthInYear(short Month) {
return (Month == 12);
}
stDate IncreaseDateByOneDay(stDate Date) {
if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
}
return Date;
}
short DayOfWeekOrder(short Day, short Month, short Year) {
short a, y, m;
a = (14 - Month) / 12;
y = Year - a;
m = Month + (12 * a) - 2;
// Gregorian:
//0:sun, 1:Mon, 2:Tue...etc
return (Day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7;
}
short DayOfWeekOrder(stDate Date) {
return DayOfWeekOrder(Date.Day, Date.Month, Date.Year);
}

string DayShortName(short DayOfWeekOrder) {


string arrDayNames[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" }
;
return arrDayNames[DayOfWeekOrder];
}
bool IsWeekEnd(stDate Date) {
//Weekends are Fri and Sat
short DayIndex = DayOfWeekOrder(Date.Day, Date.Month, Date.Year);
return (DayIndex == 5 || DayIndex == 6);
}
bool IsBusinessDay(stDate Date) {
//Weekends are Sun,Mon,Tue,Wed and Thur
/* short DayIndex = DayOfWeekOrder(Date.Day, Date.Month, Date.Year);
return (DayIndex >= 5 && DayIndex <= 4);
*///shorter method is to invert the IsWeekEnd: this will save updating code.
return !IsWeekEnd(Date);
}
short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
short CalculateVacationDays(stDate DateFrom, stDate DateTo) {
short DaysCount = 0;
while (IsDate1BeforeDate2(DateFrom, DateTo)) {
if (IsBusinessDay(DateFrom)) DaysCount++;
DateFrom = IncreaseDateByOneDay(DateFrom);
}
return DaysCount;
}

int main() {
cout << "\nVacation Starts: ";
stDate DateFrom = ReadFullDate();
cout << "\nVacation Ends: ";
stDate DateTo = ReadFullDate();
cout << "\nVaction From: " << DayShortName(DayOfWeekOrder(DateFrom)) << " , " << DateFrom.Day << "/" <<
DateFrom.Month << "/" << DateFrom.Year << endl;
cout << "Vaction To: " << DayShortName(DayOfWeekOrder(DateTo)) << " , " << DateTo.Day << "/" << DateTo.Month
<< "/" << DateTo.Year << endl;
cout << "\n\nActucal Vacation Days is: " << CalculateVacationDays(DateFrom, DateTo);
system("pause>0");
return 0;
}

Problem #55
‫الحل‬
#include <iostream>
using namespace std;

struct stDate
{
short Year;
short Month;
short Day;

};

bool isLeapYear(short Year)


{
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

bool IsDate1BeforeDate2(stDate Date1, stDate Date2)


{
return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}

short NumberOfDaysInAMonth(short Month, short Year)


{

if (Month < 1 || Month>12)


return 0;

int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };


return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];

bool IsLastDayInMonth(stDate Date)


{

return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));

bool IsLastMonthInYear(short Month)


{
return (Month == 12);
}

stDate IncreaseDateByOneDay(stDate Date)


{
if (IsLastDayInMonth(Date))
{
if (IsLastMonthInYear(Date.Month))
{
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else
{
Date.Day = 1;
Date.Month++;
}
}
else
{
Date.Day++;
}

return Date;
}

short DayOfWeekOrder(short Day, short Month, short Year)


{
short a, y, m;
a = (14 - Month) / 12;
y = Year - a;
m = Month + (12 * a) - 2;
// Gregorian:
//0:sun, 1:Mon, 2:Tue...etc
return (Day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7;
}

short DayOfWeekOrder(stDate Date)


{
return DayOfWeekOrder(Date.Day, Date.Month, Date.Year);

string DayShortName(short DayOfWeekOrder)


{
string arrDayNames[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };

return arrDayNames[DayOfWeekOrder];

bool IsWeekEnd(stDate Date)


{
//Weekends are Fri and Sat
short DayIndex = DayOfWeekOrder(Date.Day, Date.Month, Date.Year);
return (DayIndex == 5 || DayIndex == 6);
}

bool IsBusinessDay(stDate Date)


{
//Weekends are Sun,Mon,Tue,Wed and Thur

/*
short DayIndex = DayOfWeekOrder(Date.Day, Date.Month, Date.Year);
return (DayIndex >= 5 && DayIndex <= 4);
*/

//shorter method is to invert the IsWeekEnd: this will save updating code.
return !IsWeekEnd(Date);

short ReadDay()
{
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}

short ReadMonth()
{
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear()
{
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}

stDate ReadFullDate()
{
stDate Date;

Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();

return Date;
}

stDate CalculateVacationReturnDate(stDate DateFrom, short VacationDays)


{

short WeekEndCounter = 0;

//in case the data is weekend keep adding one day util you reach business day
//we get rid of all weekends before the first business day
while (IsWeekEnd(DateFrom))
{
DateFrom = IncreaseDateByOneDay(DateFrom);
}

//here we increase the vacation dates to add all weekends to it.

for (short i = 1; i <= VacationDays + WeekEndCounter; i++)


{
if (IsWeekEnd(DateFrom))
WeekEndCounter++;

DateFrom = IncreaseDateByOneDay(DateFrom);
}

//in case the return date is week end keep adding one day util you reach business day
while (IsWeekEnd(DateFrom))
{
DateFrom = IncreaseDateByOneDay(DateFrom);
}

return DateFrom;
}

short ReadVacationDays()
{
short Days;
cout << "\nPlease enter vacation days? ";
cin >> Days;
return Days;
}

int main()
{
cout << "\nVacation Starts: ";
stDate DateFrom = ReadFullDate();

short VacationDays = ReadVacationDays();

stDate ReturnDate = CalculateVacationReturnDate(DateFrom, VacationDays);

cout << "\n\nReturn Date: " << DayShortName(DayOfWeekOrder(ReturnDate)) << " , "
<< ReturnDate.Day << "/" << ReturnDate.Month << "/" << ReturnDate.Year << endl;

system("pause>0");
return 0;
}
Problem #56
‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
}
;
bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {
return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
bool IsDate1EqualDate2(stDate Date1, stDate Date2) {
return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
}
bool IsDate1AfterDate2(stDate Date1, stDate Date2) {
return (!IsDate1BeforeDate2(Date1, Date2) && !IsDate1EqualDate2(Date1, Date2));
}
short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
int main() {
cout << "\nEnter Date1:";
stDate Date1 = ReadFullDate();
cout << "\nEnter Date2:";
stDate Date2 = ReadFullDate();
if (IsDate1AfterDate2(Date1, Date2)) cout << "\nYes, Date1 is After Date2.";
else cout << "\nNo, Date1 is NOT After Date2.";
system("pause>0");
return 0;
}

Problem #57

‫الحل‬
#include<iostream>
using namespace std;
struct stDate{ short Year;
short Month;
short Day;
}
;
bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {
return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
bool IsDate1EqualDate2(stDate Date1, stDate Date2) {
return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
}
bool IsDate1AfterDate2(stDate Date1, stDate Date2) {
return (!IsDate1BeforeDate2(Date1, Date2) && !IsDate1EqualDate2(Date1, Date2));
}
enum enDateCompare{ Before = -1, Equal = 0, After = 1 }
;
enDateCompare CompareDates(stDate Date1, stDate Date2) {
if (IsDate1BeforeDate2(Date1, Date2)) return enDateCompare::Before;
if (IsDate1EqualDate2(Date1, Date2)) return enDateCompare::Equal;
/* if (IsDate1AfterDate2(Date1,Date2)) return enDateCompare::After;
*///this is faster
return enDateCompare::After;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
int main() {
cout << "\nEnter Date1:";
stDate Date1 = ReadFullDate();
cout << "\nEnter Date2:";
stDate Date2 = ReadFullDate();
cout << "\nCompare Result = " << CompareDates(Date1, Date2);
system("pause>0");
return 0;
‫}‬

‫‪Problem #58‬‬

‫هل الفترتين متداخلتين وال ال؟‬


‫ده الحل‬
‫ده حل مختصر‬

‫دول الحالتين اللي بيحصل فيه عدم تقاطع للفترتين ان تاريخ نهاية الفتره الثانيه يكون قبل تاريخ بداية الفتره االولي‬
‫او تاريخ بداية الثانيه يكون بعد تاريخ نهاية االولي‬
‫الحل‬
#include<iostream>
using namespace std;

struct stDate{
short Year;
short Month;
short Day;};

struct stPeriod{
stDate StartDate;
stDate EndDate;};

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
bool IsDate1EqualDate2(stDate Date1, stDate Date2) {
return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
}
bool IsDate1AfterDate2(stDate Date1, stDate Date2) {
return (!IsDate1BeforeDate2(Date1, Date2) && !IsDate1EqualDate2(Date1, Date2));
}
enum enDateCompare{ Before = -1, Equal = 0, After = 1 };

enDateCompare CompareDates(stDate Date1, stDate Date2) {


if (IsDate1BeforeDate2(Date1, Date2)) return enDateCompare::Before;
if (IsDate1EqualDate2(Date1, Date2)) return enDateCompare::Equal;
/* if (IsDate1AfterDate2(Date1,Date2)) return enDateCompare::After;
*///this is fasterreturn enDateCompare::After;
}
bool IsOverlapPeriods(stPeriod Period1, stPeriod Period2) {
if (CompareDates(Period2.EndDate, Period1.StartDate) == enDateCompare::Before || CompareDates(Period2.StartDate,
Period1.EndDate) == enDateCompare::After) return false;
else return true;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
stPeriod ReadPeriod() {
stPeriod Period;
cout << "\nEnter Start Date:\n";
Period.StartDate = ReadFullDate();
cout << "\nEnter End Date:\n";
Period.EndDate = ReadFullDate();
return Period;
}
int main() {
cout << "\nEnter Period 1:";
stPeriod Period1 = ReadPeriod();
cout << "\nEnter Period 2:";
stPeriod Period2 = ReadPeriod();
if (IsOverlapPeriods(Period1, Period2)) cout << "\nYes, Periods Overlap\n";
else cout << "\nNo, Periods do not Overlap\n";
system("pause>0");
return 0;
}
Problem #59
period ‫اعمل زي مابيقولك واستخدم اللي بتحسب الفرق بين تاريخين بس خليها تاخد‬
‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
struct stPeriod{
stDate StartDate;
stDate EndDate;
};

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}

bool IsDate1EqualDate2(stDate Date1, stDate Date2) {


return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
}
bool IsDate1AfterDate2(stDate Date1, stDate Date2) {
return (!IsDate1BeforeDate2(Date1, Date2) && !IsDate1EqualDate2(Date1, Date2));
}
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}
short NumberOfDaysInAMonth(short Month, short Year) {
if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }
;
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}
bool IsLastDayInMonth(stDate Date) {
return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}
bool IsLastMonthInYear(short Month) {
return (Month == 12);
}
stDate IncreaseDateByOneDay(stDate Date) {
if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
}
return Date;
}

int GetDifferenceInDays(stDate Date1, stDate Date2, bool IncludeEndDay = false) {


int Days = 0;
while (IsDate1BeforeDate2(Date1, Date2)) {
Days++;
Date1 = IncreaseDateByOneDay(Date1);
}
return IncludeEndDay ? ++Days : Days;
}
int PeriodLengthInDays(stPeriod Period, bool IncludeEndDate = false) {
return GetDifferenceInDays(Period.StartDate, Period.EndDate, IncludeEndDate);
}
short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
stPeriod ReadPeriod() {
stPeriod Period;
cout << "\nEnter Start Date:\n";
Period.StartDate = ReadFullDate();
cout << "\nEnter End Date:\n";
Period.EndDate = ReadFullDate();
return Period;
}
int main() {
cout << "\nEnter Period 1:";
stPeriod Period1 = ReadPeriod();
cout << "\nPeriod Length is: " << PeriodLengthInDays(Period1);
cout << "\nPeriod Length (Including End Date) is: " << PeriodLengthInDays(Period1, true);
system("pause>0");
return 0;
}

Problem #60
‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};

struct stPeriod{
stDate StartDate;
stDate EndDate;
};

bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {


return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
bool IsDate1EqualDate2(stDate Date1, stDate Date2) {
return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
}
bool IsDate1AfterDate2(stDate Date1, stDate Date2) {
return (!IsDate1BeforeDate2(Date1, Date2) && !IsDate1EqualDate2(Date1, Date2));
}
enum enDateCompare { Before = -1, Equal = 0, After = 1 };

enDateCompare CompareDates(stDate Date1, stDate Date2) {


if (IsDate1BeforeDate2(Date1, Date2)) return enDateCompare::Before;
if (IsDate1EqualDate2(Date1, Date2)) return enDateCompare::Equal;
/* if (IsDate1AfterDate2(Date1,Date2))
return enDateCompare::After;
*///this is fasterreturn enDateCompare::After;
}
bool isDateInPeriod(stDate Date, stPeriod Period) {
return !(CompareDates(Date, Period.StartDate) == enDateCompare::Before || CompareDates(Date, Period.EndDate) ==
enDateCompare::After);
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
stPeriod ReadPeriod() {
stPeriod Period;
cout << "\nEnter Start Date:\n";
Period.StartDate = ReadFullDate();
cout << "\nEnter End Date:\n";
Period.EndDate = ReadFullDate();
return Period;
}
int main() {
cout << "\nEnter Period :";
stPeriod Period = ReadPeriod();
cout << "\nEnter Date to check:\n";
stDate Date = ReadFullDate();
if (isDateInPeriod(Date, Period)) cout << "\nYes, Date is within period\n";
else cout << "\nNo, Date is NOT within period\n";
system("pause>0");
return 0;
}

Problem #61
‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};

struct stPeriod{
stDate StartDate;
stDate EndDate;
};
bool IsDate1BeforeDate2(stDate Date1, stDate Date2) {
return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true :
(Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false);
}
bool IsDate1EqualDate2(stDate Date1, stDate Date2) {
return (Date1.Year == Date2.Year) ? ((Date1.Month == Date2.Month) ? ((Date1.Day == Date2.Day) ? true : false) : false)
: false;
}
bool IsDate1AfterDate2(stDate Date1, stDate Date2) {
return (!IsDate1BeforeDate2(Date1, Date2) && !IsDate1EqualDate2(Date1, Date2));
}
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}

short NumberOfDaysInAMonth(short Month, short Year) {


if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }
;
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}
bool IsLastDayInMonth(stDate Date) {
return (Date.Day == NumberOfDaysInAMonth(Date.Month, Date.Year));
}
bool IsLastMonthInYear(short Month) {
return (Month == 12);
}
stDate IncreaseDateByOneDay(stDate Date) {
if (IsLastDayInMonth(Date)) {
if (IsLastMonthInYear(Date.Month)) {
Date.Month = 1;
Date.Day = 1;
Date.Year++;
}
else {
Date.Day = 1;
Date.Month++;
}
}
else {
Date.Day++;
}
return Date;
}

int GetDifferenceInDays(stDate Date1, stDate Date2, bool IncludeEndDay = false) {


int Days = 0;
while (IsDate1BeforeDate2(Date1, Date2)) {
Days++;
Date1 = IncreaseDateByOneDay(Date1);
}
return IncludeEndDay ? ++Days : Days;
}
enum enDateCompare{ Before = -1, Equal = 0, After = 1 }
;
enDateCompare CompareDates(stDate Date1, stDate Date2) {
if (IsDate1BeforeDate2(Date1, Date2)) return enDateCompare::Before;
if (IsDate1EqualDate2(Date1, Date2)) return enDateCompare::Equal;
/* if (IsDate1AfterDate2(Date1,Date2)) return enDateCompare::After;
*///this is fasterreturn enDateCompare::After;
}
int PeriodLengthInDays(stPeriod Period, bool IncludeEndDate = false) {
return GetDifferenceInDays(Period.StartDate, Period.EndDate, IncludeEndDate);
}

bool IsOverlapPeriods(stPeriod Period1, stPeriod Period2) {


if (CompareDates(Period2.EndDate, Period1.StartDate) == enDateCompare::Before || CompareDates(Period2.StartDate,
Period1.EndDate) == enDateCompare::After) return false;
else return true;
}
bool isDateInPeriod(stDate Date, stPeriod Period) {
return !(CompareDates(Date, Period.StartDate) == enDateCompare::Before || CompareDates(Date, Period.EndDate) ==
enDateCompare::After);
}

int CountOverlapDays(stPeriod Period1, stPeriod Period2) {


int Period1Length = PeriodLengthInDays(Period1, true);
int Period2Length = PeriodLengthInDays(Period2, true);
int OverlapDays = 0;
if (!IsOverlapPeriods(Period1, Period2)) return 0;
if (Period1Length < Period2Length) {
while (IsDate1BeforeDate2(Period1.StartDate, Period1.EndDate)) {
if (isDateInPeriod(Period1.StartDate, Period2)) OverlapDays++;
Period1.StartDate = IncreaseDateByOneDay(Period1.StartDate);
}
}
else {
while (IsDate1BeforeDate2(Period2.StartDate, Period2.EndDate)) {
if (isDateInPeriod(Period2.StartDate, Period1)) OverlapDays++;
Period2.StartDate = IncreaseDateByOneDay(Period2.StartDate);
}
}
return OverlapDays;
}

short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}
short ReadYear() {
short Year;
cout << "Please enter a Year? ";
cin >> Year;
return Year;
}
stDate ReadFullDate() {
stDate Date;
Date.Day = ReadDay();
Date.Month = ReadMonth();
Date.Year = ReadYear();
return Date;
}
stPeriod ReadPeriod() {
stPeriod Period;
cout << "\nEnter Start Date:\n";
Period.StartDate = ReadFullDate();
cout << "\nEnter End Date:\n";
Period.EndDate = ReadFullDate();
return Period;
}

int main() {
cout << "\nEnter Period 1 :";
stPeriod Period1 = ReadPeriod();
cout << "\nEnter Period 2 :";
stPeriod Period2 = ReadPeriod();
cout << "\nOverlap Days Count Is: " << CountOverlapDays(Period1, Period2);
system("pause>0");
return 0;
}

Problem #62
‫الحل‬
#include<iostream>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
bool isLeapYear(short Year) {
return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0);
}
short NumberOfDaysInAMonth(short Month, short Year) {
if (Month < 1 || Month>12) return 0;
int days[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }
;
return (Month == 2) ? (isLeapYear(Year) ? 29 : 28) : days[Month - 1];
}

bool IsValidDate(stDate Date) {


if (Date.Day < 1 || Date.Day>31) return false;
if (Date.Month < 1 || Date.Month>12) return false;
if (Date.Month == 2) {
if (isLeapYear(Date.Year)) {
if (Date.Day > 29) return false;
}
else {
if (Date.Day > 28) return false;
}
}
short DaysInMonth = NumberOfDaysInAMonth(Date.Month, Date.Year);
if (Date.Day > DaysInMonth) return false;
return true;
}
short ReadDay() {
short Day;
cout << "\nPlease enter a Day? ";
cin >> Day;
return Day;
}
short ReadMonth() {
short Month;
cout << "Please enter a Month? ";
cin >> Month;
return Month;
}

Problem #63:64

‫الحل‬
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
vector<string> SplitString(string S1, string Delim) {
vector<string> vString;
short pos = 0;
string sWord;
// define a string variable
//use find() function to get the position of the delimiters
while ((pos = S1.find(Delim)) != std::string::npos){
sWord =S1.substr(0, pos);
// store the word
if (sWord !=""){
vString.push_back(sWord);}

S1.erase(0, pos + Delim.length());}

if (S1 != "") {
vString.push_back(S1);
// it adds last word of the string.
}
return vString;
}

string DateToString(stDate Date) {


return to_string(Date.Day) + "/" + to_string(Date.Month) + "/" + to_string(Date.Year);}

stDate StringToDate(string DateString) {


stDate Date;
vector <string> vDate;
vDate = SplitString(DateString, "/");
Date.Day = stoi(vDate[0]);
Date.Month = stoi(vDate[1]);
Date.Year = stoi(vDate[2]);
return Date;
}
string ReadStringDate(string Message) {
string DateString;
cout << Message;
getline(cin >> ws, DateString);
return DateString;
}
int main() {
string DateString = ReadStringDate("\nPlease Enter Date dd/mm/yyyy? ");
stDate Date = StringToDate(DateString);
cout << "\nDay:" << Date.Day << endl;
cout << "Month:" << Date.Month << endl;
cout << "Year:" << Date.Year << endl;
cout << "\nYou Entered: " << DateToString(Date) << "\n";
system("pause>0");
return 0;
}

Problem #65
‫الحل‬
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct stDate{
short Year;
short Month;
short Day;
};
vector<string> SplitString(string S1, string Delim) {
vector<string> vString;
short pos = 0;
string sWord;
// define a string variable
// // use find() function to get the position of the delimiters
while ((pos = S1.find(Delim)) != std::string::npos){
sWord =S1.substr(0, pos);
// store the word
if (sWord !=""){
vString.push_back(sWord);}
S1.erase(0, pos + Delim.length());
/* erase() until positon and move to next word. */ }
if (S1 != "") {
vString.push_back(S1);
// it adds last word of the string.
}
return vString;
}

string ReplaceWordInString(string S1, string StringToReplace, string sRepalceTo){


short pos = S1.find(StringToReplace);
while (pos != std::string::npos) {
S1 = S1.replace(pos, StringToReplace.length(), sRepalceTo);
pos = S1.find(StringToReplace);
//find next
}
return S1;
}
string DateToString(stDate Date) {
return to_string(Date.Day) + "/" + to_string(Date.Month) + "/" + to_string(Date.Year);
}
stDate StringToDate(string DateString) {
stDate Date;
vector <string> vDate;
vDate = SplitString(DateString, "/");
Date.Day = stoi(vDate[0]);
Date.Month = stoi(vDate[1]);
Date.Year = stoi(vDate[2]);
return Date;
}

string FormateDate(stDate Date, string DateFormat = "dd/mm/yyyy") {


string FormattedDateString = "";
FormattedDateString = ReplaceWordInString(DateFormat, "dd", to_string(Date.Day));
FormattedDateString = ReplaceWordInString(FormattedDateString, "mm", to_string(Date.Month));
FormattedDateString = ReplaceWordInString(FormattedDateString, "yyyy", to_string(Date.Year));
return FormattedDateString;
}
string ReadStringDate(string Message) {
string DateString;
cout << Message;
getline(cin >> ws, DateString);
return DateString;
}
int main() {
string DateString = ReadStringDate("\nPlease Enter Date dd/mm/yyyy? ");
stDate Date = StringToDate(DateString);
cout << "\n" << FormateDate(Date) << "\n";
cout << "\n" << FormateDate(Date, "yyyy/dd/mm") << "\n";
cout << "\n" << FormateDate(Date, "mm/dd/yyyy") << "\n";
cout << "\n" << FormateDate(Date, "mm-dd-yyyy") << "\n";
cout << "\n" << FormateDate(Date, "dd-mm-yyyy") << "\n";
cout << "\n" << FormateDate(Date, "Day:dd, Month:mm, Year:yyyy") << "\n";
system("pause>0");
return 0;
}
Project 1 Bank Extension 2 (Requirements)
‫هتجيب المشروع بتاع الكورس اللي فات وهتكمل عليه‬
‫هتعمل ملف خاص بالمستخدمين‬
‫هتسجل فيه بيانات المستخدمين وصالحياتهم‬
‫يعني يكون فيه اسم المستخدم والباسورد والصالحيات‬
‫ معناها انه ليه كل الصالحيات‬1- ‫الصالحيه‬
‫رقم ‪ 8‬بترجعك علي شاشة تسجيل الدخول‬
‫شاشة المستخدمين خاصه باالدمن‬
‫لو داس علي أي زرار بيرجع علي شاشة ال ‪manage users‬‬
‫بيمثل صالحيات المستخدمين برقم واحد الرقم ده عباره عن ‪ binary‬باستخدام ال ‪bitwise operator‬‬
‫فلما ادي لليوزر األخير صالحيات علي رقم ‪ 1‬و ‪ 5‬رقم واحد بيمثل القيمه واحد ورقم ‪ 5‬بيمثل ال‪ bit‬الخامس قيمته ‪16‬‬
‫فلما جمعهم اداله ‪17‬‬
‫ماتقدرش تحذف االدمن‬
‫الحل‬
/*
CopyRight ProgrammingAdvices.com
Mohammed Abu-Hadhoud
*/

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

struct stUser
{
string UserName;
string Password;
int Permissions;
bool MarkForDelete = false;
};

enum enTransactionsMenueOptions { eDeposit = 1, eWithdraw = 2, eShowTotalBalance = 3, eShowMainMenue = 4 };

enum enManageUsersMenueOptions {
eListUsers = 1, eAddNewUser = 2, eDeleteUser = 3,
eUpdateUser = 4, eFindUser = 5, eMainMenue = 6
};

enum enMainMenueOptions {
eListClients = 1, eAddNewClient = 2, eDeleteClient = 3,
eUpdateClient = 4, eFindClient = 5, eShowTransactionsMenue = 6,
eManageUsers = 7, eExit = 8
};

enum enMainMenuePermissions {
eAll = -1, pListClients = 1, pAddNewClient = 2, pDeleteClient = 4,
pUpdateClients = 8, pFindClient = 16, pTranactions = 32, pManageUsers = 64
};

const string ClientsFileName = "Clients.txt";


const string UsersFileName = "Users.txt";

stUser CurrentUser;

void ShowMainMenue();
void ShowTransactionsMenue();
void ShowManageUsersMenue();
bool CheckAccessPermission(enMainMenuePermissions Permission);
void Login();

struct sClient
{
string AccountNumber;
string PinCode;
string Name;
string Phone;
double AccountBalance;
bool MarkForDelete = false;
};

vector<string> SplitString(string S1, string Delim)


{

vector<string> vString;

short pos = 0;
string sWord; // define a string variable

// use find() function to get the position of the delimiters


while ((pos = S1.find(Delim)) != std::string::npos)
{
sWord = S1.substr(0, pos); // store the word
if (sWord != "")
{
vString.push_back(sWord);
}

S1.erase(0, pos + Delim.length()); /* erase() until positon and move to next word. */
}

if (S1 != "")
{
vString.push_back(S1); // it adds last word of the string.
}

return vString;

stUser ConvertUserLinetoRecord(string Line, string Seperator = "#//#")


{

stUser User;
vector<string> vUserData;

vUserData = SplitString(Line, Seperator);

User.UserName = vUserData[0];
User.Password = vUserData[1];
User.Permissions = stoi(vUserData[2]);

return User;

sClient ConvertLinetoRecord(string Line, string Seperator = "#//#")


{

sClient Client;
vector<string> vClientData;

vClientData = SplitString(Line, Seperator);

Client.AccountNumber = vClientData[0];
Client.PinCode = vClientData[1];
Client.Name = vClientData[2];
Client.Phone = vClientData[3];
Client.AccountBalance = stod(vClientData[4]);//cast string to double

return Client;

stUser ConvertUserLinetoRecord2(string Line, string Seperator = "#//#")


{
stUser User;
vector<string> vUserData;

vUserData = SplitString(Line, Seperator);

User.UserName = vUserData[0];
User.Password = vUserData[1];
User.Permissions = stoi(vUserData[2]);

return User;

string ConvertRecordToLine(sClient Client, string Seperator = "#//#")


{

string stClientRecord = "";

stClientRecord += Client.AccountNumber + Seperator;


stClientRecord += Client.PinCode + Seperator;
stClientRecord += Client.Name + Seperator;
stClientRecord += Client.Phone + Seperator;
stClientRecord += to_string(Client.AccountBalance);

return stClientRecord;

string ConvertUserRecordToLine(stUser User, string Seperator = "#//#")


{

string stClientRecord = "";

stClientRecord += User.UserName + Seperator;


stClientRecord += User.Password + Seperator;
stClientRecord += to_string(User.Permissions);

return stClientRecord;

bool ClientExistsByAccountNumber(string AccountNumber, string FileName)


{

vector <sClient> vClients;

fstream MyFile;
MyFile.open(FileName, ios::in);//read Mode

if (MyFile.is_open())
{

string Line;
sClient Client;

while (getline(MyFile, Line))


{

Client = ConvertLinetoRecord(Line);
if (Client.AccountNumber == AccountNumber)
{
MyFile.close();
return true;
}
vClients.push_back(Client);
}

MyFile.close();

return false;

bool UserExistsByUsername(string Username, string FileName)


{

fstream MyFile;
MyFile.open(FileName, ios::in);//read Mode

if (MyFile.is_open())
{

string Line;
stUser User;

while (getline(MyFile, Line))


{

User = ConvertUserLinetoRecord(Line);
if (User.UserName == Username)
{
MyFile.close();
return true;
}

MyFile.close();

return false;

sClient ReadNewClient()
{
sClient Client;

cout << "Enter Account Number? ";

// Usage of std::ws will extract allthe whitespace character


getline(cin >> ws, Client.AccountNumber);

while (ClientExistsByAccountNumber(Client.AccountNumber, ClientsFileName))


{
cout << "\nClient with [" << Client.AccountNumber << "] already exists, Enter another Account Number? ";
getline(cin >> ws, Client.AccountNumber);
}
cout << "Enter PinCode? ";
getline(cin, Client.PinCode);

cout << "Enter Name? ";


getline(cin, Client.Name);

cout << "Enter Phone? ";


getline(cin, Client.Phone);

cout << "Enter AccountBalance? ";


cin >> Client.AccountBalance;

return Client;

int ReadPermissionsToSet()
{

int Permissions = 0;
char Answer = 'n';

cout << "\nDo you want to give full access? y/n? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
return -1;
}

cout << "\nDo you want to give access to : \n ";

cout << "\nShow Client List? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{

Permissions += enMainMenuePermissions::pListClients;
}

cout << "\nAdd New Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pAddNewClient;
}

cout << "\nDelete Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pDeleteClient;
}

cout << "\nUpdate Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pUpdateClients;
}

cout << "\nFind Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pFindClient;
}

cout << "\nTransactions? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pTranactions;
}

cout << "\nManage Users? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pManageUsers;
}

return Permissions;

stUser ReadNewUser()
{
stUser User;

cout << "Enter Username? ";

// Usage of std::ws will extract allthe whitespace character


getline(cin >> ws, User.UserName);

while (UserExistsByUsername(User.UserName, UsersFileName))


{
cout << "\nUser with [" << User.UserName << "] already exists, Enter another Username? ";
getline(cin >> ws, User.UserName);
}

cout << "Enter Password? ";


getline(cin, User.Password);

User.Permissions = ReadPermissionsToSet();

return User;

vector <stUser> LoadUsersDataFromFile(string FileName)


{

vector <stUser> vUsers;


fstream MyFile;
MyFile.open(FileName, ios::in);//read Mode

if (MyFile.is_open())
{

string Line;
stUser User;

while (getline(MyFile, Line))


{

User = ConvertUserLinetoRecord(Line);

vUsers.push_back(User);
}

MyFile.close();

return vUsers;

vector <sClient> LoadCleintsDataFromFile(string FileName)


{

vector <sClient> vClients;

fstream MyFile;
MyFile.open(FileName, ios::in);//read Mode

if (MyFile.is_open())
{

string Line;
sClient Client;

while (getline(MyFile, Line))


{

Client = ConvertLinetoRecord(Line);

vClients.push_back(Client);
}

MyFile.close();

return vClients;

void PrintClientRecordLine(sClient Client)


{

cout << "| " << setw(15) << left << Client.AccountNumber;
cout << "| " << setw(10) << left << Client.PinCode;
cout << "| " << setw(40) << left << Client.Name;
cout << "| " << setw(12) << left << Client.Phone;
cout << "| " << setw(12) << left << Client.AccountBalance;

void PrintUserRecordLine(stUser User)


{

cout << "| " << setw(15) << left << User.UserName;
cout << "| " << setw(10) << left << User.Password;
cout << "| " << setw(40) << left << User.Permissions;
}

void PrintClientRecordBalanceLine(sClient Client)


{

cout << "| " << setw(15) << left << Client.AccountNumber;
cout << "| " << setw(40) << left << Client.Name;
cout << "| " << setw(12) << left << Client.AccountBalance;

void ShowAccessDeniedMessage()
{
cout << "\n------------------------------------\n";
cout << "Access Denied, \nYou dont Have Permission To Do this,\nPlease Conact Your Admin.";
cout << "\n------------------------------------\n";
}
oid ShowAllClientsScreen()
{

if (!CheckAccessPermission(enMainMenuePermissions::pListClients))
{
ShowAccessDeniedMessage();
return;
}

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);

cout << "\n\t\t\t\t\tClient List (" << vClients.size() << ") Client(s).";
cout << "\n_______________________________________________________";
cout << "_________________________________________\n" << endl;

cout << "| " << left << setw(15) << "Accout Number";
cout << "| " << left << setw(10) << "Pin Code";
cout << "| " << left << setw(40) << "Client Name";
cout << "| " << left << setw(12) << "Phone";
cout << "| " << left << setw(12) << "Balance";
cout << "\n_______________________________________________________";
cout << "_________________________________________\n" << endl;

if (vClients.size() == 0)
cout << "\t\t\t\tNo Clients Available In the System!";
else

for (sClient Client : vClients)


{
PrintClientRecordLine(Client);
cout << endl;
}

cout << "\n_______________________________________________________";


cout << "_________________________________________\n" << endl;

void ShowAllUsersScreen()
{

vector <stUser> vUsers = LoadUsersDataFromFile(UsersFileName);

cout << "\n\t\t\t\t\tUsers List (" << vUsers.size() << ") User(s).";
cout << "\n_______________________________________________________";
cout << "_________________________________________\n" << endl;

cout << "| " << left << setw(15) << "User Name";
cout << "| " << left << setw(10) << "Password";
cout << "| " << left << setw(40) << "Permissions";
cout << "\n_______________________________________________________";
cout << "_________________________________________\n" << endl;

if (vUsers.size() == 0)
cout << "\t\t\t\tNo Users Available In the System!";
else

for (stUser User : vUsers)


{

PrintUserRecordLine(User);
cout << endl;
}

cout << "\n_______________________________________________________";


cout << "_________________________________________\n" << endl;

void ShowTotalBalances()
{

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);

cout << "\n\t\t\t\t\tBalances List (" << vClients.size() << ") Client(s).";
cout << "\n_______________________________________________________";
cout << "_________________________________________\n" << endl;

cout << "| " << left << setw(15) << "Accout Number";
cout << "| " << left << setw(40) << "Client Name";
cout << "| " << left << setw(12) << "Balance";
cout << "\n_______________________________________________________";
cout << "_________________________________________\n" << endl;

double TotalBalances = 0;

if (vClients.size() == 0)
cout << "\t\t\t\tNo Clients Available In the System!";
else

for (sClient Client : vClients)


{

PrintClientRecordBalanceLine(Client);
TotalBalances += Client.AccountBalance;

cout << endl;


}

cout << "\n_______________________________________________________";


cout << "_________________________________________\n" << endl;
cout << "\t\t\t\t\t Total Balances = " << TotalBalances;

void PrintClientCard(sClient Client)


{
cout << "\nThe following are the client details:\n";
cout << "-----------------------------------";
cout << "\nAccout Number: " << Client.AccountNumber;
cout << "\nPin Code : " << Client.PinCode;
cout << "\nName : " << Client.Name;
cout << "\nPhone : " << Client.Phone;
cout << "\nAccount Balance: " << Client.AccountBalance;
cout << "\n-----------------------------------\n";

void PrintUserCard(stUser User)


{
cout << "\nThe following are the user details:\n";
cout << "-----------------------------------";
cout << "\nUsername : " << User.UserName;
cout << "\nPassword : " << User.Password;
cout << "\nPermissions : " << User.Permissions;
cout << "\n-----------------------------------\n";

bool FindClientByAccountNumber(string AccountNumber, vector <sClient> vClients, sClient& Client)


{

for (sClient C : vClients)


{

if (C.AccountNumber == AccountNumber)
{
Client = C;
return true;
}

}
return false;

bool FindUserByUsername(string Username, vector <stUser> vUsers, stUser& User)


{
for (stUser U : vUsers)
{

if (U.UserName == Username)
{
User = U;
return true;
}

}
return false;

bool FindUserByUsernameAndPassword(string Username, string Password, stUser& User)


{

vector <stUser> vUsers = LoadUsersDataFromFile(UsersFileName);

for (stUser U : vUsers)


{

if (U.UserName == Username && U.Password == Password)


{
User = U;
return true;
}

}
return false;

sClient ChangeClientRecord(string AccountNumber)


{
sClient Client;

Client.AccountNumber = AccountNumber;

cout << "\n\nEnter PinCode? ";


getline(cin >> ws, Client.PinCode);

cout << "Enter Name? ";


getline(cin, Client.Name);

cout << "Enter Phone? ";


getline(cin, Client.Phone);

cout << "Enter AccountBalance? ";


cin >> Client.AccountBalance;

return Client;

stUser ChangeUserRecord(string Username)


{
stUser User;
User.UserName = Username;

cout << "\n\nEnter Password? ";


getline(cin >> ws, User.Password);

User.Permissions = ReadPermissionsToSet();

return User;

bool MarkClientForDeleteByAccountNumber(string AccountNumber, vector <sClient>& vClients)


{
for (sClient& C : vClients)
{
if (C.AccountNumber == AccountNumber)
{
C.MarkForDelete = true;
return true;
}
}
return false;
}
bool MarkUserForDeleteByUsername(string Username, vector <stUser>& vUsers)
{
for (stUser& U : vUsers)
{
if (U.UserName == Username)
{
U.MarkForDelete = true;
return true;
}
}
return false;
}

vector <sClient> SaveCleintsDataToFile(string FileName, vector <sClient> vClients)


{

fstream MyFile;
MyFile.open(FileName, ios::out);//overwrite

string DataLine;

if (MyFile.is_open())
{

for (sClient C : vClients)


{

if (C.MarkForDelete == false)
{
//we only write records that are not marked for delete.
DataLine = ConvertRecordToLine(C);
MyFile << DataLine << endl;

}
MyFile.close();

return vClients;

vector <stUser> SaveUsersDataToFile(string FileName, vector <stUser> vUsers)


{

fstream MyFile;
MyFile.open(FileName, ios::out);//overwrite

string DataLine;

if (MyFile.is_open())
{

for (stUser U : vUsers)


{

if (U.MarkForDelete == false)
{
//we only write records that are not marked for delete.
DataLine = ConvertUserRecordToLine(U);
MyFile << DataLine << endl;

MyFile.close();

return vUsers;

void AddDataLineToFile(string FileName, string stDataLine)


{
fstream MyFile;
MyFile.open(FileName, ios::out | ios::app);

if (MyFile.is_open())
{

MyFile << stDataLine << endl;

MyFile.close();
}

void AddNewClient()
{
sClient Client;
Client = ReadNewClient();
AddDataLineToFile(ClientsFileName, ConvertRecordToLine(Client));
}

void AddNewUser()
{
stUser User;
User = ReadNewUser();
AddDataLineToFile(UsersFileName, ConvertUserRecordToLine(User));

void AddNewClients()
{
char AddMore = 'Y';
do
{
//system("cls");
cout << "Adding New Client:\n\n";

AddNewClient();
cout << "\nClient Added Successfully, do you want to add more clients? Y/N? ";

cin >> AddMore;

} while (toupper(AddMore) == 'Y');

void AddNewUsers()
{
char AddMore = 'Y';
do
{
//system("cls");
cout << "Adding New User:\n\n";

AddNewUser();
cout << "\nUser Added Successfully, do you want to add more Users? Y/N? ";

cin >> AddMore;

} while (toupper(AddMore) == 'Y');

bool DeleteClientByAccountNumber(string AccountNumber, vector <sClient>& vClients)


{

sClient Client;
char Answer = 'n';

if (FindClientByAccountNumber(AccountNumber, vClients, Client))


{

PrintClientCard(Client);
cout << "\n\nAre you sure you want delete this client? y/n ? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
MarkClientForDeleteByAccountNumber(AccountNumber, vClients);
SaveCleintsDataToFile(ClientsFileName, vClients);

//Refresh Clients
vClients = LoadCleintsDataFromFile(ClientsFileName);

cout << "\n\nClient Deleted Successfully.";


return true;
}

}
else
{
cout << "\nClient with Account Number (" << AccountNumber << ") is Not Found!";
return false;
}

bool DeleteUserByUsername(string Username, vector <stUser>& vUsers)


{

if (Username == "Admin")
{
cout << "\n\nYou cannot Delete This User.";
return false;

stUser User;
char Answer = 'n';

if (FindUserByUsername(Username, vUsers, User))


{

PrintUserCard(User);

cout << "\n\nAre you sure you want delete this User? y/n ? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{

MarkUserForDeleteByUsername(Username, vUsers);
SaveUsersDataToFile(UsersFileName, vUsers);

//Refresh Clients
vUsers = LoadUsersDataFromFile(UsersFileName);

cout << "\n\nUser Deleted Successfully.";


return true;
}

}
else
{
cout << "\nUser with Username (" << Username << ") is Not Found!";
return false;
}

bool UpdateClientByAccountNumber(string AccountNumber, vector <sClient>& vClients)


{

sClient Client;
char Answer = 'n';

if (FindClientByAccountNumber(AccountNumber, vClients, Client))


{

PrintClientCard(Client);
cout << "\n\nAre you sure you want update this client? y/n ? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{

for (sClient& C : vClients)


{
if (C.AccountNumber == AccountNumber)
{
C = ChangeClientRecord(AccountNumber);
break;
}

SaveCleintsDataToFile(ClientsFileName, vClients);

cout << "\n\nClient Updated Successfully.";


return true;
}

}
else
{
cout << "\nClient with Account Number (" << AccountNumber << ") is Not Found!";
return false;
}

bool UpdateUserByUsername(string Username, vector <stUser>& vUsers)


{

stUser User;
char Answer = 'n';

if (FindUserByUsername(Username, vUsers, User))


{

PrintUserCard(User);
cout << "\n\nAre you sure you want update this User? y/n ? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
for (stUser& U : vUsers)
{
if (U.UserName == Username)
{
U = ChangeUserRecord(Username);
break;
}

SaveUsersDataToFile(UsersFileName, vUsers);

cout << "\n\nUser Updated Successfully.";


return true;
}

}
else
{
cout << "\nUser with Account Number (" << Username << ") is Not Found!";
return false;
}

bool DepositBalanceToClientByAccountNumber(string AccountNumber, double Amount, vector <sClient>& vClients)


{
char Answer = 'n';
cout << "\n\nAre you sure you want perfrom this transaction? y/n ? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{

for (sClient& C : vClients)


{
if (C.AccountNumber == AccountNumber)
{
C.AccountBalance += Amount;
SaveCleintsDataToFile(ClientsFileName, vClients);
cout << "\n\nDone Successfully. New balance is: " << C.AccountBalance;

return true;
}

return false;
}

string ReadClientAccountNumber()
{
string AccountNumber = "";

cout << "\nPlease enter AccountNumber? ";


cin >> AccountNumber;
return AccountNumber;
}

string ReadUserName()
{
string Username = "";

cout << "\nPlease enter Username? ";


cin >> Username;
return Username;

void ShowListUsersScreen()
{

ShowAllUsersScreen();

void ShowAddNewUserScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tAdd New User Screen";
cout << "\n-----------------------------------\n";

AddNewUsers();

void ShowDeleteUserScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tDelete Users Screen";
cout << "\n-----------------------------------\n";

vector <stUser> vUsers = LoadUsersDataFromFile(UsersFileName);

string Username = ReadUserName();


DeleteUserByUsername(Username, vUsers);

}
void ShowUpdateUserScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tUpdate Users Screen";
cout << "\n-----------------------------------\n";

vector <stUser> vUsers = LoadUsersDataFromFile(UsersFileName);


string Username = ReadUserName();

UpdateUserByUsername(Username, vUsers);
}

void ShowDeleteClientScreen()
{

if (!CheckAccessPermission(enMainMenuePermissions::pDeleteClient))
{
ShowAccessDeniedMessage();
return;
}

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


cout << "\tDelete Client Screen";
cout << "\n-----------------------------------\n";
vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);
string AccountNumber = ReadClientAccountNumber();
DeleteClientByAccountNumber(AccountNumber, vClients);

void ShowUpdateClientScreen()
{
if (!CheckAccessPermission(enMainMenuePermissions::pUpdateClients))
{
ShowAccessDeniedMessage();
return;
}

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


cout << "\tUpdate Client Info Screen";
cout << "\n-----------------------------------\n";

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


string AccountNumber = ReadClientAccountNumber();
UpdateClientByAccountNumber(AccountNumber, vClients);

void ShowAddNewClientsScreen()
{

if (!CheckAccessPermission(enMainMenuePermissions::pUpdateClients))
{
ShowAccessDeniedMessage();
return;
}

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


cout << "\tAdd New Clients Screen";
cout << "\n-----------------------------------\n";

AddNewClients();

void ShowFindClientScreen()
{

if (!CheckAccessPermission(enMainMenuePermissions::pFindClient))
{
ShowAccessDeniedMessage();
return;
}

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


cout << "\tFind Client Screen";
cout << "\n-----------------------------------\n";

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


sClient Client;
string AccountNumber = ReadClientAccountNumber();
if (FindClientByAccountNumber(AccountNumber, vClients, Client))
PrintClientCard(Client);
else
cout << "\nClient with Account Number[" << AccountNumber << "] is not found!";

void ShowFindUserScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tFind User Screen";
cout << "\n-----------------------------------\n";

vector <stUser> vUsers = LoadUsersDataFromFile(UsersFileName);


stUser User;
string Username = ReadUserName();
if (FindUserByUsername(Username, vUsers, User))
PrintUserCard(User);
else
cout << "\nUser with Username [" << Username << "] is not found!";

void ShowEndScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tProgram Ends :-)";
cout << "\n-----------------------------------\n";

void ShowDepositScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tDeposit Screen";
cout << "\n-----------------------------------\n";

sClient Client;

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


string AccountNumber = ReadClientAccountNumber();

while (!FindClientByAccountNumber(AccountNumber, vClients, Client))


{
cout << "\nClient with [" << AccountNumber << "] does not exist.\n";
AccountNumber = ReadClientAccountNumber();
}

PrintClientCard(Client);

double Amount = 0;
cout << "\nPlease enter deposit amount? ";
cin >> Amount;

DepositBalanceToClientByAccountNumber(AccountNumber, Amount, vClients);

void ShowWithDrawScreen()
{
cout << "\n-----------------------------------\n";
cout << "\tWithdraw Screen";
cout << "\n-----------------------------------\n";

sClient Client;

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


string AccountNumber = ReadClientAccountNumber();

while (!FindClientByAccountNumber(AccountNumber, vClients, Client))


{
cout << "\nClient with [" << AccountNumber << "] does not exist.\n";
AccountNumber = ReadClientAccountNumber();
}

PrintClientCard(Client);

double Amount = 0;
cout << "\nPlease enter withdraw amount? ";
cin >> Amount;

//Validate that the amount does not exceeds the balance


while (Amount > Client.AccountBalance)
{
cout << "\nAmount Exceeds the balance, you can withdraw up to : " << Client.AccountBalance << endl;
cout << "Please enter another amount? ";
cin >> Amount;
}

DepositBalanceToClientByAccountNumber(AccountNumber, Amount * -1, vClients);

void ShowTotalBalancesScreen()
{

ShowTotalBalances();

}
bool CheckAccessPermission(enMainMenuePermissions Permission)
{
if (CurrentUser.Permissions == enMainMenuePermissions::eAll)
return true;

if ((Permission & CurrentUser.Permissions) == Permission)


return true;
else
return false;

}
void GoBackToMainMenue()
{
cout << "\n\nPress any key to go back to Main Menue...";
system("pause>0");
ShowMainMenue();
}

void GoBackToTransactionsMenue()
{
cout << "\n\nPress any key to go back to Transactions Menue...";
system("pause>0");
ShowTransactionsMenue();

void GoBackToManageUsersMenue()
{
cout << "\n\nPress any key to go back to Transactions Menue...";
system("pause>0");
ShowManageUsersMenue();

short ReadTransactionsMenueOption()
{
cout << "Choose what do you want to do? [1 to 4]? ";
short Choice = 0;
cin >> Choice;

return Choice;
}

void PerfromTranactionsMenueOption(enTransactionsMenueOptions TransactionMenueOption)


{
switch (TransactionMenueOption)
{
case enTransactionsMenueOptions::eDeposit:
{
system("cls");
ShowDepositScreen();
GoBackToTransactionsMenue();
break;
}

case enTransactionsMenueOptions::eWithdraw:
{
system("cls");
ShowWithDrawScreen();
GoBackToTransactionsMenue();
break;
}

case enTransactionsMenueOptions::eShowTotalBalance:
{
system("cls");
ShowTotalBalancesScreen();
GoBackToTransactionsMenue();
break;
}
case enTransactionsMenueOptions::eShowMainMenue:
{

ShowMainMenue();

}
}

void ShowTransactionsMenue()
{

if (!CheckAccessPermission(enMainMenuePermissions::pTranactions))
{
ShowAccessDeniedMessage();
GoBackToMainMenue();
return;
}

system("cls");
cout << "===========================================\n";
cout << "\t\tTransactions Menue Screen\n";
cout << "===========================================\n";
cout << "\t[1] Deposit.\n";
cout << "\t[2] Withdraw.\n";
cout << "\t[3] Total Balances.\n";
cout << "\t[4] Main Menue.\n";
cout << "===========================================\n";
PerfromTranactionsMenueOption((enTransactionsMenueOptions)ReadTransactionsMenueOption());
}

short ReadMainMenueOption()
{
cout << "Choose what do you want to do? [1 to 8]? ";
short Choice = 0;
cin >> Choice;

return Choice;
}

void PerfromManageUsersMenueOption(enManageUsersMenueOptions ManageUsersMenueOption)


{
switch (ManageUsersMenueOption)
{
case enManageUsersMenueOptions::eListUsers:
{
system("cls");
ShowListUsersScreen();
GoBackToManageUsersMenue();
break;
}

case enManageUsersMenueOptions::eAddNewUser:
{
system("cls");
ShowAddNewUserScreen();
GoBackToManageUsersMenue();
break;
}

case enManageUsersMenueOptions::eDeleteUser:
{
system("cls");
ShowDeleteUserScreen();
GoBackToManageUsersMenue();
break;
}

case enManageUsersMenueOptions::eUpdateUser:
{
system("cls");
ShowUpdateUserScreen();
GoBackToManageUsersMenue();
break;
}

case enManageUsersMenueOptions::eFindUser:
{
system("cls");

ShowFindUserScreen();
GoBackToManageUsersMenue();
break;
}

case enManageUsersMenueOptions::eMainMenue:
{
ShowMainMenue();
}
}

short ReadManageUsersMenueOption()
{
cout << "Choose what do you want to do? [1 to 6]? ";
short Choice = 0;
cin >> Choice;

return Choice;
}

void ShowManageUsersMenue()
{

if (!CheckAccessPermission(enMainMenuePermissions::pManageUsers))
{
ShowAccessDeniedMessage();
GoBackToMainMenue();
return;
}

system("cls");
cout << "===========================================\n";
cout << "\t\tManage Users Menue Screen\n";
cout << "===========================================\n";
cout << "\t[1] List Users.\n";
cout << "\t[2] Add New User.\n";
cout << "\t[3] Delete User.\n";
cout << "\t[4] Update User.\n";
cout << "\t[5] Find User.\n";
cout << "\t[6] Main Menue.\n";
cout << "===========================================\n";

PerfromManageUsersMenueOption((enManageUsersMenueOptions)ReadManageUsersMenueOption());
}

void PerfromMainMenueOption(enMainMenueOptions MainMenueOption)


{
switch (MainMenueOption)
{
case enMainMenueOptions::eListClients:
{
system("cls");
ShowAllClientsScreen();
GoBackToMainMenue();
break;
}
case enMainMenueOptions::eAddNewClient:
system("cls");
ShowAddNewClientsScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eDeleteClient:
system("cls");
ShowDeleteClientScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eUpdateClient:
system("cls");
ShowUpdateClientScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eFindClient:
system("cls");
ShowFindClientScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eShowTransactionsMenue:
system("cls");
ShowTransactionsMenue();
break;

case enMainMenueOptions::eManageUsers:
system("cls");
ShowManageUsersMenue();
break;

case enMainMenueOptions::eExit:
system("cls");
// ShowEndScreen();
Login();
break;
}

void ShowMainMenue()
{
system("cls");
cout << "===========================================\n";
cout << "\t\tMain Menue Screen\n";
cout << "===========================================\n";
cout << "\t[1] Show Client List.\n";
cout << "\t[2] Add New Client.\n";
cout << "\t[3] Delete Client.\n";
cout << "\t[4] Update Client Info.\n";
cout << "\t[5] Find Client.\n";
cout << "\t[6] Transactions.\n";
cout << "\t[7] Manage Users.\n";
cout << "\t[8] Logout.\n";
cout << "===========================================\n";

PerfromMainMenueOption((enMainMenueOptions)ReadMainMenueOption());
}

bool LoadUserInfo(string Username, string Password)


{

if (FindUserByUsernameAndPassword(Username, Password, CurrentUser))


return true;
else
return false;

void Login()
{
bool LoginFaild = false;

string Username, Password;


do
{
system("cls");

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


cout << "\tLogin Screen";
cout << "\n---------------------------------\n";

if (LoginFaild)
{
cout << "Invlaid Username/Password!\n";
}

cout << "Enter Username? ";


cin >> Username;

cout << "Enter Password? ";


cin >> Password;
LoginFaild = !LoadUserInfo(Username, Password);

} while (LoginFaild);

ShowMainMenue();

int main()

{
Login();

system("pause>0");
return 0;
}

binary ‫فكرة انك تعمل الصالحيات في شكل‬


bit ‫الفكره هنا انك بتعوض عن كل صالحيه برقم بيعبر عن قيمة ال‬
)128‫و‬64‫و‬32‫و‬16‫و‬8‫و‬4‫و‬2‫و‬1( ‫ دي ارقامها بالترتيب‬bits ‫ فااحنا عارفين ان ال‬bits 8 ‫ فيه‬byte‫يعني لو ال‬
)A,B,C,D,E( ‫ منتجات عاوز اعبرعنهم في رقم وحد وليكن اساميهم‬5 ‫ صالحيات او‬5 ‫انا دلوقتي عندي‬
‫ زي كده‬bit ‫ واحط اسامي العناصر دي وادي كل واحد فيهم رقم من ارقام ال‬ENUM ‫هقوم جاي عامل‬

1 2 4 8 16
A B C D E

enum enMainMenuePermissions {
eAll = -1, pListClients = 1, pAddNewClient = 2, pDeleteClient = 4,
pUpdateClients = 8, pFindClient = 16, pTranactions = 32, pManageUsers = 64
};

‫ من اليوزر ولو اليوزر وافق انه يديها صالحيه‬n‫ و‬y ‫ او بتقرا‬false‫ و‬true ‫ مثال وهقوم عامل داله بتقرا‬int ‫بعدين هقوم معرف‬
‫وكل ماليوزر يديك موافقه علي حاجه هتقوم جايب قيمه المتغير وجامع عليه قيمة الصالحيه دي زي كده‬

int ReadPermissionsToSet()
{

int Permissions = 0;
char Answer = 'n';

cout << "\nDo you want to give full access? y/n? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
return -1;
}

cout << "\nDo you want to give access to : \n ";

cout << "\nShow Client List? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{

Permissions += enMainMenuePermissions::pListClients;
}
cout << "\nAdd New Client? y/n? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pAddNewClient;
}

cout << "\nDelete Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pDeleteClient;
}

cout << "\nUpdate Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pUpdateClients;
}

cout << "\nFind Client? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pFindClient;
}

cout << "\nTransactions? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pTranactions;
}

cout << "\nManage Users? y/n? ";


cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{
Permissions += enMainMenuePermissions::pManageUsers;
}

return Permissions;

1 2 4 8 16
A B C D E
21
1 0 1 0 1

21 ‫ مجموعهم بيساوي‬16‫و‬4‫و‬1 ‫ عناصر قيمتهم‬3 ‫هنا اليوزر اختار‬


user‫ في ال‬21 ‫هقوم مخزن ال‬

‫طيب انا دلوقتي عاوزر اعرف الصالحيه معينه متاحه مع اليوزر ده وال ال هعمل ايه؟‬
‫ببساطه هقوله هل الرقم اللي بيعبر عن الصالحيات ده (بالنسبالنا هنا ‪ )21‬هل من ضمنه الرقم ‪ 4‬مثال ؟‬

‫)‪bool CheckAccessPermission(enMainMenuePermissions Permission‬‬


‫{‬
‫)‪if (CurrentUser.Permissions == enMainMenuePermissions::eAll‬‬
‫;‪return true‬‬

‫)‪if ((Permission & CurrentUser.Permissions) == Permission‬‬


‫;‪return true‬‬
‫‪else‬‬
‫;‪return false‬‬

‫}‬

‫فاللي هيتم انه هيمسك الرقم ‪ 21‬ويمسك او ‪ bit‬فيه هيالقيه بيساوي ‪ 1‬فيحط صفر ويمسك الرقم التاني يالقيه بيساوي ‪ 2‬فيحط قدامه صفر ويمسك‬
‫الرقم اللي بعد يالقيه بيساوي ‪ 4‬ويحط قدامه ‪ 1‬الن ده اللي بيدور عليه وهكذا لحد مانالقي النتيجه بقت كده‬
‫‪1‬‬ ‫‪2‬‬ ‫‪4‬‬ ‫‪8‬‬ ‫‪16‬‬
‫‪A‬‬ ‫‪B‬‬ ‫‪C‬‬ ‫‪D‬‬ ‫‪E‬‬
‫‪21‬‬
‫‪1‬‬ ‫‪0‬‬ ‫‪1‬‬ ‫‪0‬‬ ‫‪1‬‬
‫‪0‬‬ ‫‪0‬‬ ‫‪1‬‬ ‫‪0‬‬ ‫‪0‬‬ ‫‪4‬‬
‫‪0‬‬ ‫‪0‬‬ ‫‪1‬‬ ‫‪0‬‬ ‫‪0‬‬ ‫‪4‬‬

‫وأصبحت القيمه النهائية يااما نفس الرقم اللي انت بتدور عليه او صفر‬

‫)‪Project 2 - ATM System (Requirements‬‬


‫هنا بيقولك انك هتعمل سيستم منفصل لل ‪ atm‬الن البنوك بيبقي عندها سيستم خاص بالبنك وسيستم تاني منفصل خاص بال ‪ ATM‬لكن بيكونوا‬
‫مشتركين في الداتا بيز اللي فيها بيانات العمالء‬
‫فاحنا هناخد البيانات من الملف بتاع المشروع اللي فات بتاع العمالء‬
‫الزم الرقم يكون ‪ 5‬او مضاعفاتها‬
‫الحل‬
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

struct sClient
{
string AccountNumber;
string PinCode;
string Name;
string Phone;
double AccountBalance;
bool MarkForDelete = false;
};

enum enMainMenueOptions {
eQucikWithdraw = 1, eNormalWithDraw = 2, eDeposit = 3,
eCheckBalance = 4, eExit = 5
};

const string ClientsFileName = "Clients.txt";


sClient CurrentClient;
void ShowMainMenue();
void Login();
void ShowQuickWithdrawScreen();
void ShowNormalWithDrawScreen();
void ShowDepositScreen();

vector<string> SplitString(string S1, string Delim)


{

vector<string> vString;

short pos = 0;
string sWord; // define a string variable

// use find() function to get the position of the delimiters


while ((pos = S1.find(Delim)) != std::string::npos)
{
sWord = S1.substr(0, pos); // store the word
if (sWord != "")
{
vString.push_back(sWord);
}

S1.erase(0, pos + Delim.length()); /* erase() until positon and move to next word. */
}

if (S1 != "")
{
vString.push_back(S1); // it adds last word of the string.
}

return vString;

sClient ConvertLinetoRecord(string Line, string Seperator = "#//#")


{

sClient Client;
vector<string> vClientData;

vClientData = SplitString(Line, Seperator);

Client.AccountNumber = vClientData[0];
Client.PinCode = vClientData[1];
Client.Name = vClientData[2];
Client.Phone = vClientData[3];
Client.AccountBalance = stod(vClientData[4]);//cast string to double

return Client;

string ConvertRecordToLine(sClient Client, string Seperator = "#//#")


{

string stClientRecord = "";


stClientRecord += Client.AccountNumber + Seperator;
stClientRecord += Client.PinCode + Seperator;
stClientRecord += Client.Name + Seperator;
stClientRecord += Client.Phone + Seperator;
stClientRecord += to_string(Client.AccountBalance);

return stClientRecord;

vector <sClient> LoadCleintsDataFromFile(string FileName)


{

vector <sClient> vClients;

fstream MyFile;
MyFile.open(FileName, ios::in);//read Mode

if (MyFile.is_open())
{

string Line;
sClient Client;

while (getline(MyFile, Line))


{

Client = ConvertLinetoRecord(Line);

vClients.push_back(Client);
}

MyFile.close();

return vClients;

bool FindClientByAccountNumberAndPinCode(string AccountNumber, string PinCode, sClient& Client)


{

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);

for (sClient C : vClients)


{

if (C.AccountNumber == AccountNumber && C.PinCode == PinCode)


{
Client = C;
return true;
}

}
return false;

vector <sClient> SaveCleintsDataToFile(string FileName, vector <sClient> vClients)


{

fstream MyFile;
MyFile.open(FileName, ios::out);//overwrite

string DataLine;

if (MyFile.is_open())
{

for (sClient C : vClients)


{

if (C.MarkForDelete == false)
{
//we only write records that are not marked for delete.
DataLine = ConvertRecordToLine(C);
MyFile << DataLine << endl;

MyFile.close();

return vClients;

}
bool DepositBalanceToClientByAccountNumber(string AccountNumber, double Amount, vector <sClient>& vClients)
{
char Answer = 'n';

cout << "\n\nAre you sure you want perfrom this transaction? y/n ? ";
cin >> Answer;
if (Answer == 'y' || Answer == 'Y')
{

for (sClient& C : vClients)


{
if (C.AccountNumber == AccountNumber)
{
C.AccountBalance += Amount;
SaveCleintsDataToFile(ClientsFileName, vClients);
cout << "\n\nDone Successfully. New balance is: " << C.AccountBalance;

return true;
}

return false;
}

short ReadQuickWithdrawOption()
{
short Choice = 0;
while (Choice < 1 || Choice>9)
{
cout << "\nChoose what to do from [1] to [9] ? ";
cin >> Choice;
}

return Choice;
}

short getQuickWithDrawAmount(short QuickWithDrawOption)


{
switch (QuickWithDrawOption)
{
case 1:
return 20;
case 2:
return 50;
case 3:
return 100;
case 4:
return 200;
case 5:
return 400;
case 6:
return 600;
case 7:
return 800;
case 8:
return 1000;
default:
return 0;

void PerfromQuickWithdrawOption(short QuickWithDrawOption)


{
if (QuickWithDrawOption == 9)//exit
return;

short WithDrawBalance = getQuickWithDrawAmount(QuickWithDrawOption);

if (WithDrawBalance > CurrentClient.AccountBalance)


{
cout << "\nThe amount exceeds your balance, make another choice.\n";
cout << "Press Anykey to continue...";
system("pause>0");
ShowQuickWithdrawScreen();
return;
}

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


DepositBalanceToClientByAccountNumber(CurrentClient.AccountNumber, WithDrawBalance * -1, vClients);
CurrentClient.AccountBalance -= WithDrawBalance;

}
double ReadDepositAmount()
{
double Amount;
cout << "\nEnter a positive Deposit Amount? ";

cin >> Amount;


while (Amount <= 0)
{
cout << "\nEnter a positive Deposit Amount? ";
cin >> Amount;
}
return Amount;
}

void PerfromDepositOption()
{

double DepositAmount = ReadDepositAmount();

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


DepositBalanceToClientByAccountNumber(CurrentClient.AccountNumber, DepositAmount, vClients);
CurrentClient.AccountBalance += DepositAmount;
}
void ShowDepositScreen()
{
system("cls");
cout << "===========================================\n";
cout << "\t\tDeposit Screen\n";
cout << "===========================================\n";
PerfromDepositOption();

void ShowCheckBalanceScreen()
{
system("cls");
cout << "===========================================\n";
cout << "\t\tCheck Balance Screen\n";
cout << "===========================================\n";
cout << "Your Balance is " << CurrentClient.AccountBalance << "\n";

int ReadWithDrawAmont()
{
int Amount;
cout << "\nEnter an amount multiple of 5's ? ";

cin >> Amount;

while (Amount % 5 != 0)
{
cout << "\nEnter an amount multiple of 5's ? ";
cin >> Amount;
}
return Amount;
}

void PerfromNormalWithdrawOption()
{
int WithDrawBalance = ReadWithDrawAmont();

if (WithDrawBalance > CurrentClient.AccountBalance)


{
cout << "\nThe amount exceeds your balance, make another choice.\n";
cout << "Press Anykey to continue...";
system("pause>0");
ShowNormalWithDrawScreen();
return;
}

vector <sClient> vClients = LoadCleintsDataFromFile(ClientsFileName);


DepositBalanceToClientByAccountNumber(CurrentClient.AccountNumber, WithDrawBalance * -1, vClients);
CurrentClient.AccountBalance -= WithDrawBalance;

void ShowNormalWithDrawScreen()
{
system("cls");
cout << "===========================================\n";
cout << "\t\tNormal Withdraw Screen\n";
cout << "===========================================\n";
PerfromNormalWithdrawOption();
}

void ShowQuickWithdrawScreen()
{
system("cls");
cout << "===========================================\n";
cout << "\t\tQucik Withdraw\n";
cout << "===========================================\n";
cout << "\t[1] 20\t\t[2] 50\n";
cout << "\t[3] 100\t\t[4] 200\n";
cout << "\t[5] 400\t\t[6] 600\n";
cout << "\t[7] 800\t\t[8] 1000\n";
cout << "\t[9] Exit\n";
cout << "===========================================\n";
cout << "Your Balance is " << CurrentClient.AccountBalance;

PerfromQuickWithdrawOption(ReadQuickWithdrawOption());
}

void GoBackToMainMenue()
{
cout << "\n\nPress any key to go back to Main Menue...";
system("pause>0");
ShowMainMenue();
}

short ReadMainMenueOption()
{
cout << "Choose what do you want to do? [1 to 5]? ";
short Choice = 0;
cin >> Choice;

return Choice;
}
void PerfromMainMenueOption(enMainMenueOptions MainMenueOption)
{
switch (MainMenueOption)
{
case enMainMenueOptions::eQucikWithdraw:
{
system("cls");
ShowQuickWithdrawScreen();
GoBackToMainMenue();
break;
}
case enMainMenueOptions::eNormalWithDraw:
system("cls");
ShowNormalWithDrawScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eDeposit:
system("cls");
ShowDepositScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eCheckBalance:
system("cls");
ShowCheckBalanceScreen();
GoBackToMainMenue();
break;

case enMainMenueOptions::eExit:
system("cls");
Login();

break;
}

}
void ShowMainMenue()
{
system("cls");
cout << "===========================================\n";
cout << "\t\tATM Main Menue Screen\n";
cout << "===========================================\n";
cout << "\t[1] Quick Withdraw.\n";
cout << "\t[2] Normal Withdraw.\n";
cout << "\t[3] Deposit\n";
cout << "\t[4] Check Balance.\n";
cout << "\t[5] Logout.\n";
cout << "===========================================\n";

PerfromMainMenueOption((enMainMenueOptions)ReadMainMenueOption());
}

bool LoadClientInfo(string AccountNumber, string PinCode)


{

if (FindClientByAccountNumberAndPinCode(AccountNumber, PinCode, CurrentClient))


return true;
else
return false;
}

void Login()
{
bool LoginFaild = false;
string AccountNumber, PinCode;
do
{
system("cls");
cout << "\n---------------------------------\n";
cout << "\tLogin Screen";
cout << "\n---------------------------------\n";

if (LoginFaild)
{
cout << "Invlaid Account Number/PinCode!\n";
}

cout << "Enter Account Number? ";


cin >> AccountNumber;

cout << "Enter Pin? ";


cin >> PinCode;
LoginFaild = !LoadClientInfo(AccountNumber, PinCode);

} while (LoginFaild);

ShowMainMenue();

int main()

{
Login();

system("pause>0");
return 0;
}

end

You might also like