Showing posts with label En. Jiwa. Show all posts
Showing posts with label En. Jiwa. Show all posts

Sunday, March 4, 2012

CSC138 - Mini Project: Banking System

Assalamualaikum.

Ini contoh program untuk soalan 1 mini project korang.

PERHATIAN
*program ni aku buat se-simple yang mungkin, setakat nk tunjuk concept banking system yang aku boleh bayang
*konsep2 yang aku nk tunjuk tu cmna nk delete data, nk pakai dynamic array
*aku sendiri pun tak brapa nk paham sangat soalan, jadi apa yang aku buat ni berdasarkan apa yang aku paham lah.
*basically program ni agak berterabur sikit, tak complete, dan kalau korang copy sebijik2 buat presentation, drpd 100 markah aku tak gerenti pn bleh dpt 10 markah, hahaha
*dan disebabkan aku buat sekejap jee, dlm 5-8 jam (dgn twitter dn bagai), aku expect korang yang ada lebih berjam2 ni tambah laa bunga2, kasi kemas sikit, buat clearscreen, letak error handling, senang cakap bagi dapat 100 markah lah, hohoho
*ok dah cukup membebel

program ni aku buat pakai Dev-C++ 4.9.9.2, harap maklum

#include 
#include 
using namespace std;

struct Account
{
       long accNum;
       char cusName[50];
       double deposit;
       double withdraw;
       char accType;
};

yang ni macam biasa, include apa2 yang perlu.
bawah namespace tu namanya struct Account tu, itu struct yang aku buat berdasarkan soalan. takde pape yang spesel pn kt sini

ok, memandangkan coding aku berterabur (aku letak function definition atas main program), maka aku akan terangkan daripada main lah, lepas tu kita go on satu2 ikot function yang di pakai step-by-step. (ayat pn berterabur dah)

int main(void)
{
    bool flag = true;
    int menuChoice;
    
    do
    {
         menuChoice = chooseMenu();
         
         switch(menuChoice)
         {
              case 1: createAccount();
                      break;
              case 2: modifyAccount();
                      break;
              case 3: deleteAccount();
                      break;
              case 4: flag = adminMenu();
                      break;
         }
    }while(flag);
}

ini main program nyaaa.
bool flag tu boolean variable yang aku buat untuk kawal loop do while tu.
menuChoice tu untuk simpan input user laah, user nk modify kee, nk create new account kee, nk delete account kee camtu.
masuk loop do while tu, jumpak laah function yang first sekali chooseMenu().
dalam function tu (akan diterangkan sebentar lagi) program request input dr user utk menuChoice.
menuChoice tu digunakan untuk switch tuuuu.
boleh nampak kt atas tu program ni ada 4 pilihan jee
1 - create account
2 - modify account
3 - delete account
4 - admin(ni extra)
condition kt while tu akan berubah bila user input pilihan ke 4 jee.

ok jom pergi function chooseMenu()

int chooseMenu()
{
    int menuChoice=0;
    bool error=false;
    do
    {
         if(error)
         {
                  cout << "Invalid Choice!" << endl;
                  cout << endl;
         }
         cout << "Welcome to ANC Banking! Please select an option." << endl;
         cout << "1 - Create New Account" << endl;
         cout << "2 - Modify Account" << endl;
         cout << "3 - Delete Account" << endl;
         cout << "4 - Admin Only" << endl;
         cin >> menuChoice;
         error = true;
    }while(menuChoice<1 || menuChoice>4);
    return menuChoice;
}

korang patut dah pandai baca function header kan?
baca ja function header kena tau function tu return datatype apa, receive parameter apa, berapa.
aite, menuChoice=0, instantiate variable untuk user input (tak payah 0 pn takpe).
bool error=false, untuk detect error kalau user input selain pilihan yang ada (selain 1-4), instantiate sbg false sbb mula2 start mmg takdak error la kan
do while tu condition akan loop selagi user input selain 1-4 (ni loop control paling simple yang aku bleh pk)
first if tu untuk check kalau ada error then display error message
then, display menu lah, sebelum request input pilihan user.
bwh sikit, assign error=true, tak kisah lah pilihan user dalam range atau tak. kalau dalam range, process akan keluar loop, tak kacau dah error message kt atas tu. kalau takde dlm range pilihan, loop naik atas balik display error baru request input lg skali.
kat luar loop tu return user input ke menuChoice kt function main.
rasanya kat sini je laah kot aku control user input.
kat tempat lain aku tak control, so kalau salah input korang mungkin kena close program, baru run balik
tu semua kerja korang, hahahaha

next, function createAccount()

void createAccount()
{
     Account newCus;
     cout << "Enter account number: ";
     cin >> newCus.accNum;
     cin.ignore(80, '\n');
     cout << "Enter name: ";
     cin.get(newCus.cusName,50);
     cin.ignore(80, '\n');
     cout << "Select account type (s-savings, c-current):";
     cin >> newCus.accType;
     cout << "Enter your initial deposit: ";
     cin >> newCus.deposit;
     
     newCus.withdraw = 0;
     
     insertData (newCus);
}

Account newCus, delare variable untuk struct Account
pastu, request details input dari user, account number, name, type of account (aku letak savings dgn current jee, byk lg kalau pegi check kt bank tuu, korang tambah2 laa).
pastu initial deposit tu aku saje lah letak, bukak akaun bank mesti ah letak duit skit kn? sspn pun kena masuk rm20, hoho
pastu aku assign withdraw=0, yelah, baru create account, takkan dah withdraw siap2 plak duit tu kan.
last sekali tu function insertData(), dan memandangkan ikut proses jumpak function ni dulu, aku explain laah function ni dulu sebelum function modifyAccount().


void insertData (Account acc)
{
     ofstream outfile ("account.dat", ios::out | ios::app);
     outfile << acc.accNum << endl;
     outfile << acc.cusName << endl;
     outfile << acc.deposit << endl;
     outfile << acc.withdraw << endl;
     outfile << acc.accType << endl;
     outfile.close();
}

function insertData ni kt dlm full coding ada 3 jenis semua.
aku pakai konsep function overload (korang belajar ke belum eh?).
function overload ni, nama function sama, tapi yang membezakan tu mungkin parameter atau return value.
kalau belum belajar lg mungkin part 3 korang belajar dlm java.
so, dlm function ni, receive satu variable struct account dari function call
account ni kita nk insert dalam output file sbg 'database' customer yang buat transaction.
simple jee function ni, aku open file pakai ofstream ios::out dgn ios::app
ios out tu, open file cam biasa lah, kalau file belum ada, create baru, kalau dah ada, overwrite.
tapi aku letak ios app, tu untuk sambung output file dekat end of file.
instead of overwrite semua data yang ada, aku just tambah baru kt hujung.
imagine kalau korang pakai ios::out jee, dalam output file asal ada 10 rekod customer lama, tiba2 tambah customer baru sorang, dah overwrite semua data tadi, hilang camtu jee 10 rekod customer lama.
sbb tu aku pakai ios::app.
yang bawah2 tu macam biasa lah outfile dari console ke output file.

next, modifyAccount()

void modifyAccount()
{
     long accNum;
     bool found = false;
     int modifyChoice;
     do
     {
          cout << "Enter account number: ";
          cin >> accNum;
          
          found = searchData(accNum);
          if(found == false)
              cout << "Account not found" << endl;
          else
          {
              modifyChoice = chooseModify();
              switch(modifyChoice)
              {                    
              case 1: changeName(accNum);
                      break;
              case 2: depositCash(accNum);
                      break;
              case 3: withdrawCash(accNum);
                      break;
              case 4: changeType(accNum);
                      break;
              }
          }        
     }while (found == false);
}

urm, kat sini sakit sikit laah. kalau tak dapat tangkap apa yang aku nk cerita ni mungkin pening sikit. sbb dalam ni ada lagi 5 function. aku akan cuba explain sebaik mungkin. macam tadi gak aku akan explain function ikot flow proses.
so, function ni void, and takdak parameter, maksudnya function ni aku buat sbb nak segmentize kan coding. taknak serabut sangat letak semua kat function main()
long accNum variable untuk request akaun number yang user nk modify( macam pergi atm masukkan kad, atm sebenarnya baca nombor akaun kt kad tu, dari cip la kot skrg, dulu dari strip magnetik yang hitam tuu)
bool found=false variable untuk control loop dan untuk validate akaun number tu ada dalam database atau tak.
int modifyChoice untuk request pilihan user (1-4) nak tukar nama, buat deposit atau withdraw, atau tukar account type.
masuk loop do while, first sekali request number account dr user
pastu call function searchData() dgn akaun number yg user input, untuk cari rekod dalam database.
kalau tak jumpak rekod, display message, loop balik request number dr user lg.
kalau rekod ada, request input dari user, apa dorg nk modify, pakai function chooseModify()
pastu baru masuk switch, mengikut pilihan user, ada 4 function
1 - changeName()
2 - depositCash()
3 - withdrawCash()
4 - changeType
(kat sini aku dh malas nk control input, so kalau user pilih selain dari 1-4 mungkn program akan keluar terus, try ler tgk ape jadi)

jom tgk searchData()

bool searchData(long accNum)
{
     ifstream infile ("account.dat");
     bool flag = false;
     while (!infile.eof())
     {
           Account acc;
           infile >> acc.accNum;
           infile >> acc.cusName;
           infile >> acc.deposit;
           infile >> acc.withdraw;
           infile >> acc.accType;
           
           if(accNum == acc.accNum)
           {
                flag = true;
                cout << "account found" << endl;
                break;
           }
           
     }
     infile.close();
     return flag;
}

function searchData() receive long datatype, return bool datatype.
function ni receive accNum yang user input kt funtion call sebelum ni, untuk search rekod melalui nombor akaun(yang sepatutnya unique untuk setiap customer)
first thing, open input file, nak baca rekod dalam database,
set flag = false, flag ni sebagai tanda jumpak atau tak nombor akaun yg user input tu dalam database.
masuk loop while, condition selagi tak sampai hujung file. condition ni ada masalah skit sebenarnya, sbb aku test td dia akan read line yang kosong last sekali tu sbg infile jugak. tp jgn risau, function2 lain yang lebih kurang, aku dh setel masalah tu, nnt kita tgk.
dalam loop benda biasa, baca dari input file.
condition if tu untuk bila jumpak rekod akaun number yang sama dgn user input.
set flag = true, display message dh jumpak rekod, lepastu break untuk serta merta keluar dari loop walaupun belum sampai hujung file. sbb dah jumpak rekod, tak payah nk tengok yang lain2.
close file, return flag.


chooseModify()

int chooseModify()
{
    cin.ignore(80,'\n');
    int choice;
    cout << "Select an option: " << endl;
    cout << "1 - Change name" << endl;
    cout << "2 - Deposit Cash" << endl;
    cout << "3 - Withdraw Cash" << endl;
    cout << "4 - Change Account Type" << endl;
    cin >> choice;
    return choice;
}


return int datatype, no paramater.
function simple untuk display menun request input pilihan user.
input return kat function call.


changeName()

void changeName(long accNum)
{
     int recordSize = countRecord();
     char newName[50];
     cout << "Enter new name: ";
     cin.ignore(80,'\n');
     cin.get(newName,50);
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
             {
                 int i;
                 for(i=0;i<50;i++)
                 {
                     acc.cusName[i] = '\0';
                 }
                 i=0;
                 do
                 {
                     acc.cusName[i] = newName[i];
                     i++;
                 }while(newName[i]!='\0');
             }
             
             pAcc[x] = acc;
     }
     infile.close();
     insertData (pAcc,recordSize);
     cout << "Update Successful" << endl;     
}

void function, parameter long accNum dari function call.
kat sini start pakai pointer dgn dynamic array.
aku tak nampak cara lain dah untuk buat benda ni. kalau korang ada cara lain , sharing2 lah ek.
nombor akaun yg user input digunakan untuk compare dan modify rekod yg berkaitan.
function ni untuk ubah nama pemilik akaun.
int recordSize = countRecord() ni untuk kira bilangan akaun yang ada dalam database(atau input file kita).
 char newName untuk simpan nama baru yang user nk ubah.
pastu request nama dari user
Account * pAcc declare pointer untuk struct jenis Account (sbb nak buat dynamic array)
line yg bawah tu, cara declare dynamic array, <pointer> = new (no throw) <datatype>[<dynamic size>].
(no throw) tu aku pun baru belajar, kalau tak letak tu nanti dynamic array akan throw error kalau memory tak cukup, kalau ada throw, kena ada catch, sbb tu aku buat no throw, malas nk catch. so that, bila ada error nanti, program continue macam biasa(xsure)
aku pakai dynamic array ni sbb jumlah bilangan akaun dalam database berubah2 ikot berapa user create new account dan berapa user delete account. bilangan akaun dalam database tak tetap, a.k.a dynamic.
sbb tu wujud function countRecord tadi tu, untuk kira berapa akaun dalam input file, then baru pakai value tu sbg size array.
open file, masuk for loop, condition selagi x kurang dari size bilangan akaun.
baca input dari file,
sampai if tu, condition nombor akaun rekod sama dengan nombor akaun user input, baru masuk proses tukar nama.
ok, part ni aku sendiri tak brapa nk faham.
loop for tu untuk 'clear' array char yang simpan nama user yang lama(dari input file).
lepas dah clear tu baru lah salin nama yang user input, abjad demi abjad, sbb array takleh buat assignment.
dah habes tukar nama, simpan data dalam dynamic array Account.
tutup input file, then call function insertData(), tgk betul2 function insertData() ni lain sikit dari function insertData() yang kt createAccount() tu, yang ni ada dua parameter(function overload) walaupun nama sama. function call ni hantar pointer untuk dynamic array dgn size rekod atau jumlah bilangan akaun dalam input file.

countRecord()

int countRecord()
{

     int countData = 0;
     Account acc;
     ifstream infile ("account.dat");
     while (infile >> acc.accNum)
     {
           infile >> acc.cusName;
           infile >> acc.deposit;
           infile >> acc.withdraw;
           infile >> acc.accType;
           countData++;   
     }
     infile.close();
     return countData;
}

function countRecord() return integer value sbg saiz atau jumlah bilangan akaun dalam input file.
countData untuk kira bilangan akaun. basically function ni cuma baca dari input file macam biasa, sambil tu setiap kali cukup satu set data(accNum, name, deposit, withdraw, accType) kita increment countData sbg tanda cukup satu rekod.
last sekali return countData ke function call.
function ni rasanya semua function untuk modify account ada pakai benda ni.

insertData() - yang kedua

void insertData (Account * pAcc, int size)
{
     ofstream outfile ("account.dat", ios::trunc);
     for(int x=0;x<size;x++)
     {     
             insertData (pAcc[x]);   
     }
     outfile.close();
}

insertData() ni ada dua parameter, satu pointer, lagi satu saiz rekod atau blangan akaun.
untuk yang ni, aku pakai ofstream ios::trunc, yang ni untuk overwrite semua data yang ada dalam database, tulis yang baru. data2 yang lama aku overwrite dgn data2 yang aku simpan dalam dynamic array tadi dalam function changeName()
dalam loop for tu aku call function insertData() yang first tadi.


depositCash()


void depositCash(long accNum)
{
     int recordSize = countRecord();
     double deposit;
     cout << "Enter deposit amount: ";
     cin >> deposit;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             if(acc.accNum == accNum)
                 acc.deposit = acc.deposit + deposit;
             pAcc[x] = acc;
     }
     infile.close();
     insertData (pAcc,recordSize);
     cout << "Deposit successful" << endl;
}

function void, receive satu parameter long, accNum (user input)
countRecord ni benda sama macam changeName() tadi
next 3 lines untuk request input user punya deposit amount (dah makin malas nak menaip)
pointer, dynamic array, open file, macam changeName() jugak
loop dan baca dari input file pun sama.
beza kt sini cuma if tu, dalam if tu kita cuma nk tambah jumlah deposit yang sedia ada(dulu), dgn deposit yang user baru input tadi. total up, simpan dalam acc.deposit
then simpan struct tu dalam dynamic array.
keluar loop, tutup file, insertData() jenis yang kedua macam dalam changeName()
display message, *chiiiiiing* (blurr dah)


withdrawCash()


void withdrawCash(long accNum)
{
     int recordSize = countRecord();
     double withdraw;
     cout << "Enter withdraw amount: ";
     cin >> withdraw;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
             {
                 if((acc.deposit-acc.withdraw) < withdraw)
                     cout << "Insufficient account balance to withdraw" << endl;
                 else
                 {
                     acc.withdraw +=withdraw;
                     cout << "Withdrawal successful" << endl;
                 }
                     
             }
             
             pAcc[x] = acc;
     }
     infile.close();
     insertData (pAcc,recordSize);
}


konsep sama macam depositCash(), (sepatutnya boleh segmentize lg benda2 yang sama ni bg jadi satu function, tp aku dh pening)
beza kalini untuk withdraw duit
kt dlm if tu, aku buat condition untuk check (yang ni aku pk logik sendiri) 'balance' account, asamada cukup atau tak user nk withdraw.
kalau tengok kt coding aku takdak laa tulis balance account kt mana2, tapi tgk formula "acc.deposit - acc.withdraw" yang tu sebenarnya 'balance account' sbb user hanya boleh withdraw duit yang dia dh deposit,
so, kalau user mintak nk withdraw lebih dari yang dia deposit, kena halang transaction.
so, condition if tu sebenarnya kalau balance tu kurang dari permintaan withdraw user, then display error, stop transaction.
else, continue transaction, pastu rekodkan jumlah withdraw yang baru.
yang seterusnya pun sama macam function depositCash()

changeType()

void changeType(long accNum)
{
     int recordSize = countRecord();
     char accType;
     cout << "Select account type (s-savings, c-current):";
     cin >> accType;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
                 acc.accType = accType;
             
             pAcc[x] = acc;          
     }
     infile.close();
     insertData (pAcc,recordSize);
     cout << "Update successful" << endl;
}

again, same thing over here, just change the input request and the process inside the if, the rests are all copy-pasted from the former functions.

deleteAccount()
yayyyy!!! back to the 3rd menu of the first selection~~ (lol)


void deleteAccount()
{
     long accNum;
     char confirm;
     bool found = false;
     do
     {
          cout << "Enter account number: ";
          cin >> accNum;
          
          found = searchData(accNum);
          if(found == false)
              cout << "Account not found" << endl;
          else
          {
              cout << "Are you sure you want to delete account?(Y/N): ";
              cin >> confirm;
              if(confirm == 'Y' || confirm == 'y')
              {
                  deleteData(accNum);
                  break;
              }
              else
                  break;
          }        
     }while (found == false);
}

kay, function ni untuk delete account user, berdasarkan nombor akaun (macam yang lain2 jugak).
flow proses lebih kurang camni: request nombor akaun dari user, check account tu ada tak dalam input file, kalau takdak abort, kalau ada, buat confirmation untuk delete. tu jaaa
long accNum untuk simpan nombor akaun user input,
char confirm untuk confirmation user betul2 nk delete atau tak,
bool found = false, untuk validate ada rekod nombor akaun atau tak dalam database,
dlm loop, request input user, searchData() dh explain kt atas.
kalau jumpa rekod, baru buat confirmation.
then bila user dah confirm, baru proses masuk function deleteData().
selain dari tu, break je keluar loop.


deleteData()


void deleteData(long accNum)
{
     int recordSize = countRecord();
     int deleteIndex;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
             {
                 deleteIndex=x;
             }  
             pAcc[x] = acc;       
     }
     infile.close();
     insertData (pAcc,recordSize,deleteIndex);
     cout << "Account deleted" << endl;
}

function void, receive one parameter, long, accNum, input from user.
countRecord() dah explain.
deleteIndex ni just satu variable untuk simpan index untuk data dlm array yang kita nk delete (of course ada cara lain lagi selain pakai deleteIndex ni, malas nk pk)
skip2 benda yg dah tahu, masuk if, deleteIndex = x; nampak kt sini kita just nk amek value 'x' tu bila nombor akaun user input sama dengan nombor akaun dalam database. kita cuma nak index array tu.
skip2, insertData() kalini ada 3 parameter( function overload lagi).

insertData() - yang ketiga


void insertData (Account * pAcc, int size, int deleteIndex)
{
     ofstream outfile ("account.dat", ios::trunc);
     for(int x=0;x<size;x++)
     {     
           if(x!=deleteIndex)
               insertData (pAcc[x]);   
     }
     outfile.close();
}

function void, terima 3 parameter, pointer struct account, integer size rekod database, integer index array utk 'delete' data.
secara keseluruhan, hampir sama dengan insertData() kedua tadi, cuma ada condition untuk insertData() dalam loop for tu.
condition tu untuk kita insert semua data dalam array, kecuali data yg index kita retrieve dari function call tadi.
dari segi logiknya, kita bukanlah 'delete' data tu, kita cuma tak tulis balik dalam database :D




adminMenu()
yayyyy!! last!!


bool adminMenu()
{
     return false;
} 

takde pape pun kt sini
aku buat function ni utk exit jee sbnarnye, tp atm kan takde exit.
so, kt sini laa korang nk tambah extra features, nk letak option untuk print report kee tgk brapa byk dh user deposit, nak kira jumlah customer ke ape, ikot kreativiti masing2.


okay, selamat mencobaa.


ini full coding




//BANKING SYSTEM

#include <iostream>
#include <fstream>
using namespace std;

struct Account
{
       long accNum;
       char cusName[50];
       double deposit;
       double withdraw;
       char accType;
};

int chooseMenu()
{
    int menuChoice=0;
    bool error=false;
    do
    {
         if(error)
         {
                  cout << "Invalid Choice!" << endl;
                  cout << endl;
         }
         cout << "Welcome to ANC Banking! Please select an option." << endl;
         cout << "1 - Create New Account" << endl;
         cout << "2 - Modify Account" << endl;
         cout << "3 - Delete Account" << endl;
         cout << "4 - Admin Only" << endl;
         cin >> menuChoice;
         error = true;
    }while(menuChoice<1 || menuChoice>4);
    return menuChoice;
}

void insertData (Account acc)
{
     ofstream outfile ("account.dat", ios::out | ios::app);
     outfile << acc.accNum << endl;
     outfile << acc.cusName << endl;
     outfile << acc.deposit << endl;
     outfile << acc.withdraw << endl;
     outfile << acc.accType << endl;
     outfile.close();
}

void insertData (Account * pAcc, int size)
{
     ofstream outfile ("account.dat", ios::trunc);
     for(int x=0;x<size;x++)
     {     
             insertData (pAcc[x]);   
     }
     outfile.close();
}

void insertData (Account * pAcc, int size, int deleteIndex)
{
     ofstream outfile ("account.dat", ios::trunc);
     for(int x=0;x<size;x++)
     {     
           if(x!=deleteIndex)
               insertData (pAcc[x]);   
     }
     outfile.close();
}

void createAccount()
{
     Account newCus;
     cout << "Enter account number: ";
     cin >> newCus.accNum;
     cin.ignore(80, '\n');
     cout << "Enter name: ";
     cin.get(newCus.cusName,50);
     cin.ignore(80, '\n');
     cout << "Select account type (s-savings, c-current):";
     cin >> newCus.accType;
     cout << "Enter your initial deposit: ";
     cin >> newCus.deposit;
     
     newCus.withdraw = 0;
     
     insertData (newCus);
}

bool searchData(long accNum)
{
     ifstream infile ("account.dat");
     bool flag = false;
     while (!infile.eof())
     {
           Account acc;
           infile >> acc.accNum;
           infile >> acc.cusName;
           infile >> acc.deposit;
           infile >> acc.withdraw;
           infile >> acc.accType;
           
           if(accNum == acc.accNum)
           {
                flag = true;
                cout << "account found" << endl;
                break;
           }
           
     }
     infile.close();
     return flag;
}

int chooseModify()
{
    cin.ignore(80,'\n');
    int choice;
    cout << "Select an option: " << endl;
    cout << "1 - Change name" << endl;
    cout << "2 - Deposit Cash" << endl;
    cout << "3 - Withdraw Cash" << endl;
    cout << "4 - Change Account Type" << endl;
    cin >> choice;
    return choice;
}

int countRecord()
{

     int countData = 0;
     Account acc;
     ifstream infile ("account.dat");
     while (infile >> acc.accNum)
     {
           infile >> acc.cusName;
           infile >> acc.deposit;
           infile >> acc.withdraw;
           infile >> acc.accType;
           countData++;   
     }
     infile.close();
     return countData;
}

void changeName(long accNum)
{
     int recordSize = countRecord();
     char newName[50];
     cout << "Enter new name: ";
     cin.ignore(80,'\n');
     cin.get(newName,50);
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
             {
                 int i;
                 for(i=0;i<50;i++)
                 {
                     acc.cusName[i] = '\0';
                 }
                 i=0;
                 do
                 {
                     acc.cusName[i] = newName[i];
                     i++;
                 }while(newName[i]!='\0');
             }
             
             pAcc[x] = acc;
     }
     infile.close();
     insertData (pAcc,recordSize);
     cout << "Update Successful" << endl;     
}

void depositCash(long accNum)
{
     int recordSize = countRecord();
     double deposit;
     cout << "Enter deposit amount: ";
     cin >> deposit;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             if(acc.accNum == accNum)
                 acc.deposit = acc.deposit + deposit;
             pAcc[x] = acc;
     }
     infile.close();
     insertData (pAcc,recordSize);
     cout << "Deposit successful" << endl;
}

void withdrawCash(long accNum)
{
     int recordSize = countRecord();
     double withdraw;
     cout << "Enter withdraw amount: ";
     cin >> withdraw;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
             {
                 if((acc.deposit-acc.withdraw) < withdraw)
                     cout << "Insufficient account balance to withdraw" << endl;
                 else
                 {
                     acc.withdraw +=withdraw;
                     cout << "Withdrawal successful" << endl;
                 }
                     
             }
             
             pAcc[x] = acc;
     }
     infile.close();
     insertData (pAcc,recordSize);
}

void changeType(long accNum)
{
     int recordSize = countRecord();
     char accType;
     cout << "Select account type (s-savings, c-current):";
     cin >> accType;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
                 acc.accType = accType;
             
             pAcc[x] = acc;          
     }
     infile.close();
     insertData (pAcc,recordSize);
     cout << "Update successful" << endl;
}

void modifyAccount()
{
     long accNum;
     bool found = false;
     int modifyChoice;
     do
     {
          cout << "Enter account number: ";
          cin >> accNum;
          
          found = searchData(accNum);
          if(found == false)
              cout << "Account not found" << endl;
          else
          {
              modifyChoice = chooseModify();
              switch(modifyChoice)
              {                    
              case 1: changeName(accNum);
                      break;
              case 2: depositCash(accNum);
                      break;
              case 3: withdrawCash(accNum);
                      break;
              case 4: changeType(accNum);
                      break;
              }
          }        
     }while (found == false);
}

void deleteData(long accNum)
{
     int recordSize = countRecord();
     int deleteIndex;
     Account * pAcc;
     pAcc = new (nothrow) Account[recordSize];
     ifstream infile ("account.dat");
     for(int x=0;x<recordSize;x++)
     {
             
             Account acc;
             infile >> acc.accNum;
             infile >> acc.cusName;
             infile >> acc.deposit;
             infile >> acc.withdraw;
             infile >> acc.accType;
             
             if(acc.accNum == accNum)
             {
                 deleteIndex=x;
             }  
             pAcc[x] = acc;       
     }
     infile.close();
     insertData (pAcc,(recordSize),deleteIndex);
     cout << "Account deleted" << endl;
}

void deleteAccount()
{
     long accNum;
     char confirm;
     bool found = false;
     do
     {
          cout << "Enter account number: ";
          cin >> accNum;
          
          found = searchData(accNum);
          if(found == false)
              cout << "Account not found" << endl;
          else
          {
              cout << "Are you sure you want to delete account?(Y/N): ";
              cin >> confirm;
              if(confirm == 'Y' || confirm == 'y')
              {
                  deleteData(accNum);
                  break;
              }
              else
                  break;
          }        
     }while (found == false);
}

bool adminMenu()
{
     return false;
} 

int main(void)
{
    bool flag = true;
    int menuChoice;
    
    do
    {
         menuChoice = chooseMenu();
         
         switch(menuChoice)
         {
              case 1: createAccount();
                      break;
              case 2: modifyAccount();
                      break;
              case 3: deleteAccount();
                      break;
              case 4: flag = adminMenu();
                      break;
         }
    }while(flag);
}

edit: file coding aku baru upload yg updated. yg lama tu ada benda2 kecik aku tak delete

sekian, terima kasih kerana membaca.
Assalamualaikum.

Saturday, December 31, 2011

Tutorial Assignment 1

Assalamualaikum.
Macam yg dh dijanjikan, ni tutorial pertama aku leh bg.
Program ni berdasarkan assignment 1 CSC138 kelas En. Jiwa sesi November 2011
Aku dah modify sikit soalan sbb xnk bg korang copy paste jwpn bg kt sir.
Ini full coding dgn soalan modified.
(aku guna site mediafire sbb tu yg aku tau, kalau ade site lg sng pakai btau ah)
Jom, tgk coding fragment by fragment.
Oh, aku tulis, compile n run program ni pakai Turbo C++

#include <iostream.h>
#include <iomanip.h>

const int CITYNUM = 2;
const int WEEKNUM = 4;

So, #include <iostream.h> ni benda biasa lah kot, tak payah nk explain kn?

#include <iomanip.h> ni untuk kita pakai function2 untuk manipulate(kawal) input atau output. Input Output MANIPulator. Dalam program ni kita cuma pakai setw dgn setprecision. I'll explain more as we get to them.
Kalau korang pakai compiler selain dari Turbo, korang kena buang '.h' tu jadi #include <iostream>, kalau tak error. Pastu kena tambah satu statement lg lepas dh habes #include, 'using namespace std;'

const int CITYNUM = 2;
const int WEEKNUM = 4;
Ini pun korg tahu kot, declare constant. Dua2 constant ni aku pakai sbg saiz 2D array. Aku sj pakai constant supaya senang nnt kalau aku nk ubah saiz 2D array aku just ubah kt sini, tak payah nk tukar satu2 kt dlm coding.

void main()
{
 char cityName[CITYNUM][15];
 int victim[CITYNUM][WEEKNUM];
 float expenditure[CITYNUM][WEEKNUM];

 cout.setf (ios::fixed);
 cout << setprecision(2);

 cout << "Flood Victim Application" << endl;
void main() ini pun benda wajib tahu, sape taktau lg pegi part 1 blaja balik :P . Computer mmg akan cari function 'main()' ni sbg entry point untuk apa2 program yg kita tulis. boleh jugak pakai 'int main()', tapi nanti kena tambah return statement sebelum end. Lg satu, kena tambah 2 parameter apa entah (dh lupa) untuk compiler2 baru.

char cityName[CITYNUM][15];
Aku declare 2D array of char, untuk store nama2 bandar. Sebenarnya ini array of string. Tapi dah string tu sendiri ialah array of char (char name[20]), so bila nk simpan byk2 nama, jadi lah 2D array of char. Kalau rajin explore, boleh je cari kt website cplusplus cara nk pakai datatype string,  tak payah pakai char.

int victim[CITYNUM][WEEKNUM];
Ini 2D array utk store number of victim.
float expenditure[CITYNUM][WEEKNUM];
Ini 2D array utk store expenditure.
Nampak tak aku pakai constants kt sini? Contoh la nanti kalau aku nk ubah program ni, nak kira untuk 10 weeks pulak instead of 4 weeks, aku just pegi ubah kt declaration constant td, tak payah ubah semua kt sini.

cout.setf (ios::fixed);
cout << setprecision(2);
Ok, yang ni rasanya korang dh penah buat, tp aku explain je lah. Ni untuk format-kan nombor perpuluhan yang korang nk display. yang cout.setf tu copy lah bulat2 satu line tu, aku pun xpaham sgt nk explain camne, tapi kira line ni untuk set kan jenis format nombor floating yg kita nk display lah. selain dari ios::fixed tu ade lg parameter lain boleh pakai, korg explore sendiri nanti share2 dgn aku lak. Tapi yang kita pakai fixed tu format dia supaya nombor pepuluhan yg keluar ikut bilangan dalam setprecision tu dan nombor2 yang lebih takkan dibundarkan. Contoh la kalau kita buat :
cout << 12.3456 << endl;
cout << 12.1 << endl;
output :
12.34
12.10
Nombor tak bundar jadi 12.35 .
Then, kalau korang nak ubah titik perpuluhan, korang ubah la nombor kt dalam setprecision tu. Aku guna 2 sebab nak display nilai duit kan.

 //loop for row
 for(int x=0;x<CITYNUM;x++)
 {
  cout << "*** City " << (x+1) << " ***" << endl;
  //input city name
  cout << "City Name : ";
  cin.get(cityName[x],15);

So, ini loop pertama, disebabkan kena pakai 2D array, mau takmau kena lah buat nested loops. Loop ni untuk array berubah dari satu row ke row seterusnya.
Line 2: sekali lagi aku pakai constant sbg condition for loop.
Line 4: cout biasa, nk display input untuk city yang ke berapa.
Line 6: cara nk request input pakai cin.get (<variable name char> , <size variable>). Size variable tu ikut lah size datatype char yg kita declare kt atas td.

  //loop for column
  for(int y=0;y<WEEKNUM;y++)
  {
   //input number of victims weekly
   cout << "Week " << (y+1) << " : ";
   cin >> victim[x][y];

Ini loop kedua, loop yg belah dalam. Loop ni untuk ubah dari column ke column lah.
Line 5: cout biasa untuk display input week ke berapa.
Line 6: request input untuk number of victims.

   //calculate expenditure
   if(victim[x][y] < 50)
    expenditure[x][y] = (float)(victim[x][y]*70);

   else if((victim[x][y]>50) && (victim[x][y]<=100))
    expenditure[x][y] = (float)(victim[x][y]*68);

   else if((victim[x][y]>100) && (victim[x][y]<=200))
    expenditure[x][y] = (float)(victim[x][y]*66);

   else if((victim[x][y]>200) && (victim[x][y]<=100))
    expenditure[x][y] = (float)(victim[x][y]*64);

   else
    expenditure[x][y] = (float)(victim[x][y]*60);
  }

Ini semua if statements lah, untuk calculate expenditure, ikut soalan.
Tgk line 3,6,9,12,15 tu ada (float) ini casting untuk tukar integer dari variable victim tu jadi float datatype.
Lepas tu end loop untuk column.

  //flush input stream
  cin.ignore(80,'\n');
  cout << endl;
 }

Line 2: cin.ignore ni sebenarnya untuk flush input stream. Kita kena flush input stream di antara satu input statement (cin) dan sebelum pakai cin.get . Macam dalam coding ni, kita baru buat input number of victim, tp selepas pusingan loop yang pertama, kita nk buat input city name, pakai cin.get sbb tu kena flush.

A bit hard to explain but here we go:
Setiap kali kita buat input, let say, cin>>num1; , masa run, kita kena type input, contoh : 2, so kita tekanlah nombor '2' kt keyboard and then tekan 'Enter', baru input tu masuk dalam console. Nombor '2' tu akan masuk dalam variable 'num1', tapi, value 'Enter' (compiler baca 'Enter' sbg '\n') tu stay kt dalam console. Kalau kita just pakai cin>> takdak masalah, boleh run mcm biasa. Tapi, bila pakai cin.get atau cin.getline, compiler akan baca value 'Enter' tu sbg satu input. So, kalau kita tak flush value 'Enter' tu, variable yg kita pakai dlm cin.get tu akan store value 'Enter' atau '\n' tu. Sbb tu kalau korang tak flush, masa run tiba2 program skip satu input. (kalau explanation ni tak faham, btau aku, nanti aku buat graphical punya).

 //display victim report
 cout << endl;
 cout << "Weekly Victim Report" << endl;
 cout << setw(15) << "City";

 for(x=0;x<WEEKNUM;x++)
 {
  cout << setw(9) << "Week " << setw(1) << (x+1);
 }
 cout << endl;

Part ni yang lain2 tu biasa je lah kot. kecuali Line 4 dgn Line 8 tu, setw. Benda ni kalau korang taknak pakai pun takpe, setakat nk bagi chantek output je. Rasanya korang pakai '\t' jee senang untuk buat display macam table tu kan. Tapi aku pakai setw sbb aku rasa cam cool je, haha.

setw ni rasanya untuk set width utk satu output stream yg seterusnya. Satu je. Contoh :
cout << setw(10) << "Hello" << "World";
Statement ni akan 'reserve' 10 character space untuk "Hello", tapi tak buat apa2 untuk "World".
Output dia camni :
_ _ _ _ _ HelloWorld
Underline tu blank space, satu underline untuk satu character space (macam tekan space bar sekali).
Yang ni pulak :  cout << setw(10) << "Hello" << setw(8) << "World";
Output : _ _ _ _ _Hello_ _ _World
Korang try lah macam2 pakai setw ni, sampai paham macam mana nk manipulate. Jgn risau, tak masuk exam kot. Kot~~~
Line 4: aku set width utk field 'City' 15 character space, sbb saiz city name aku 15 (tgk declaration)
Line 8: aku set width untuk "Week " (ade satu space situ) 9 space, untuk nombor week tu 1 space. Total spacing untuk setiap 'Week' = 10 spacing.

 //loop for row
 for(x=0;x<CITYNUM;x++)
 {
  cout << setw(15) << cityName[x];

  //loop for columns
  for(int y=0;y<WEEKNUM;y++)
  {
   cout << setw(10) << victim[x][y];
  }
  cout << endl;
 }

So, ini untuk display 'table' korang, of course kena display row by row, kena access balik 2D array yg dh input sebelum ni, so, kena lahh pakai nested loop lagi.
Line 3: aku set width untuk display cityName 15 spacing, sama saiz dgn 'City' (part sebelum ni).
Line 8: set width 10 spacing untuk display number of victim, sama saiz dgn total spacing untuk 'Week' (part sebelum ni).
Kiranya pakai setw ni aku dah susun supaya output jadi camni (contoh input city name = Kajang, week 1 victim = 100):
_ _ _ _ _ _ _ _ _ _ _ City _ _ _ _ _ Week 1 (sampai Week 4)
_ _ _ _ _ _ _ _ _ Kajang  _ _ _ _ _ _ _ 100 (sampai week 4)

huruf 'y' kt 'City' akan selari dgn huruf 'g' kt 'Kajang' tu. Nombor '1' kt 'Week 1' akan selari dgn nombor '0' kt '100' tu.

 //display expenditure report
 cout << endl;
 cout << "Weekly Expenditure Report" << endl;
 cout << setw(15) << "City";
 for(x=0;x<WEEKNUM;x++)
 {
  cout << setw(9) << "Week " << setw(1) << (x+1);
 }
 cout << endl;

 //loop for row
 for(x=0;x<CITYNUM;x++)
 {
  cout << setw(15) << cityName[x];

  //loop for columns
  for(int y=0;y<WEEKNUM;y++)
  {
   cout << setw(10) << expenditure[x][y];
  }
  cout << endl;
 }
}

Part ni sama je dgn part2 atas yang display victim report tu. Cuma tukar variable dgn tajuk report je kot. Boleh je nk adjust2 setw kt sini, sbb expenditure tu akan keluar byk digit, so 10 spacing tu mungkin tak cukup.

Takat ni je lah aku buat utk korang eh. Yang extra 5 marks untuk function tu pandai2 sendiri lah yee, hahaha. Function korang kena paham betul2, kalau boleh genggam betul2 sbb function ni kira core untuk programming lah. Korang akan pakai banyak function sampai part 5. Mungkin part 3 atau part 4 nanti baru korang betul2 boleh faham function ni camne. Anyway, kalau ada apa2 tak paham dlm post ni, comment je. Insyaallah aku reply secepat mungkin, n kalau perlu aku edit lah entri ni. Kalau nk request coding untuk  extra 5 marks tu pun boleh, kalau ade request, then aku buat entri baru. So, jgn lah malu2 nak tanya walau sebodoh mana pun korang rasa soalan korang tu, insyaallah kalau aku mampu aku jawab. Kalau aku tak mampu, kita sama2 google cari.

Full Coding:
#include <iostream.h>
#include <iomanip.h>

const int CITYNUM = 2;
const int WEEKNUM = 4;

void main()
{
 char cityName[CITYNUM][15];
 int victim[CITYNUM][WEEKNUM];
 float expenditure[CITYNUM][WEEKNUM];

 cout.setf (ios::fixed);
 cout << setprecision(2);

 cout << "Flood Victim Application" << endl;

 //loop for row
 for(int x=0;x<CITYNUM;x++)
 {
  cout << "*** City " << (x+1) << " ***" << endl;
  //input city name
  cout << "City Name : ";
  cin.get(cityName[x],15);

  //loop for column
  for(int y=0;y<WEEKNUM;y++)
  {
   //input number of victims weekly
   cout << "Week " << (y+1) << " : ";
   cin >> victim[x][y];

   //calculate expenditure
   if(victim[x][y] < 50)
    expenditure[x][y] = (float)(victim[x][y]*70);

   else if((victim[x][y]>50) && (victim[x][y]<=100))
    expenditure[x][y] = (float)(victim[x][y]*68);

   else if((victim[x][y]>100) && (victim[x][y]<=200))
    expenditure[x][y] = (float)(victim[x][y]*66);

   else if((victim[x][y]>200) && (victim[x][y]<=100))
    expenditure[x][y] = (float)(victim[x][y]*64);

   else
    expenditure[x][y] = (float)(victim[x][y]*60);
  }

  //flush input stream
  cin.ignore(80,'\n');
  cout << endl;
 }

 //display victim report
 cout << endl;
 cout << "Weekly Victim Report" << endl;
 cout << setw(15) << "City";

 for(x=0;x<WEEKNUM;x++)
 {
  cout << setw(9) << "Week " << setw(1) << (x+1);
 }
 cout << endl;


 //loop for row
 for(x=0;x<CITYNUM;x++)
 {
  cout << setw(15) << cityName[x];

  //loop for columns
  for(int y=0;y<WEEKNUM;y++)
  {
   cout << setw(10) << victim[x][y];
  }
  cout << endl;
 }

 //display expenditure report
 cout << endl;
 cout << "Weekly Expenditure Report" << endl;
 cout << setw(15) << "City";
 for(x=0;x<WEEKNUM;x++)
 {
  cout << setw(9) << "Week " << setw(1) << (x+1);
 }
 cout << endl;

 //loop for row
 for(x=0;x<CITYNUM;x++)
 {
  cout << setw(15) << cityName[x];

  //loop for columns
  for(int y=0;y<WEEKNUM;y++)
  {
   cout << setw(10) << expenditure[x][y];
  }
  cout << endl;
 }
}

Program Screenshot:


Terima kasih kerana membaca.
Assalamualaikum.