BongoBob Posted March 7, 2006 Share Posted March 7, 2006 I've been recently learning C++ programming from http://www.cprogramming.com, and I know that I'm not the only person on here with some programming experience. I figure we should have a thread about programming, were we can post source code, ask for some help, and give tips I'll start off. I've only gone through the first 8 or 9 lessons on cprogramming.com, but I got bored today and decided to make a program that would find either the circumference or the area of a circle. Well after 3 hours of thinking, writing source code, and compiling, I finally got a finished product I am pretty happy with. Keep in mind I am in no means an expert at programming, and that this source isn't organized none too well, and I havn't implemented a loop in it yet, but it works. #include <iostream> using namespace std; int mainmenu(); // Main menu of the program int cmenu(); // Menu for the circumference choice int amenu(); // Menu for the area choice int cmchoice1(); // Finds the circumference given the diameter int cmchoice2(); // Finds the circumference given the radius int amchoice1(); // Finds the area given the radius int amchoice2(); // Finds the area given the diameter int mmenuinpt; // Directs the user to the selected part of the program int cmenuinpt; // Directs the user to the selected part of the program int amenuinpt; // Directs the user to the selected part of the program int exitmsg(); // Message displayed upon exit float pi = 3.14; // Tells the program that Pi equals 3.14 float r; // Variable for radius float d; // Variable for diameter int cform(); // Formula to find the circumference of a circle int aform(); // Formula to find the area of a circle int rfromd(); // Derives a radius from the diameter int dfromr(); // Derives a diameter from the radius float c; // Variable for circumference float a; // Variable for the true area int errormsg(); // Message displayed upon a user error int main() { mainmenu(); if ( mmenuinpt == 1 ) { cmenu(); if ( cmenuinpt == 1 ) { cmchoice1(); } else if ( cmenuinpt == 2 ) { cmchoice2(); } else { errormsg(); } } else if ( mmenuinpt == 2 ) { amenu(); if ( amenuinpt == 1 ) { amchoice1(); } else if ( amenuinpt == 2 ) { amchoice2(); } else { errormsg(); } } else if ( mmenuinpt == 3 ) { exitmsg(); } else { errormsg(); } } int mainmenu() // Main menu of the program { cout<<"1. Find the circumference of a circle\n"; cout<<"2. Find the area of a circle\n"; cout<<"3. Exit\n"; cout<<"Please enter your choice: "; cin>> mmenuinpt; cin.ignore(); } int cmenu() // Menu for the circumference choice { cout<<"\nWhich do you know about the circle, (1) the diameter, or (2) the radius: "; cin>> cmenuinpt; cin.ignore(); } int cmchoice1() // Finds the circumference given the radius { cout<<"\nPlease enter the diameter of the circle: "; cin>> d; cin.ignore(); cform(); cout<<"\nThe circumference of the circle is "<< c <<"\n"; exitmsg(); } int cmchoice2() // Finds the circumference given the diameter { cout<<"\nPlease enter the radius of the circle: "; cin>> r; cin.ignore(); dfromr(); cform(); cout<<"\nThe circumference of the circle is "<< c <<"\n"; exitmsg(); } int amenu() // Menu for the area choice { cout<<"\nWhich do you know about the circle, (1) the radius, or (2) the diameter: "; cin>> amenuinpt; cin.ignore(); } int amchoice1() // Finds the area given the diameter { cout<<"\nPlease enter the radius of the circle: "; cin>> r; cin.ignore(); aform(); cout<<"\nThe area of the circle is "<< a <<"\n"; exitmsg(); } int amchoice2() // Finds the area given the radius { cout<<"\nPlease enter the diameter of the circle: "; cin>> d; cin.ignore(); rfromd(); aform(); cout<<"\nThe area of the circle is "<< a <<"\n"; exitmsg(); } int exitmsg() // Message displayed upon exit { cout<<"\nThank you for using this program.\n"; cout<<"Press enter to exit.\n"; cin.get(); } int rfromd() // Derives a radius from the diameter { r = d / 2; } int dfromr() // Derives a diameter from the radius { d = r * 2; } int cform() // Formula to find the circumference of a circle { c = d * pi; } int aform() // Formula to find the area of a circle { a = r * pi; a = a * a; } int errormsg() { cout<<"\nError, please press enter to exit the program.\n"; cin.get(); } Comments, oppinions? Pants stealing squirrels? Link to comment Share on other sites More sharing options...
TiE23 Posted March 7, 2006 Share Posted March 7, 2006 Programming illiterate alert!!! How do I use this? Cause I'd love to try it out. Link to comment Share on other sites More sharing options...
narfblat Posted March 7, 2006 Share Posted March 7, 2006 I think your formula for the area of a circle is incorrect. It should be a = pi * r * r. area of circle is pi * r^2, not (pi * r)^2. ( "^2" means "squared") optherwise, well done. Edit: plus, some pants stealing squirrels. Link to comment Share on other sites More sharing options...
Sabretooth Posted March 7, 2006 Share Posted March 7, 2006 ...but I got bored today and decided to make a program that would find either the circumference or the area of a circle. Shame, Bongo. I can do that in GWBASIC in less than 10 minutes, with hardly any code, as compared to that massive code you had there. 10 Input r 20 let a=3.14*r*r 30 print a 40 end Of course, you have done all that diameter/area etc. stuff, with choice and all. I can do all that, but I'm feeling too lazy write now. Link to comment Share on other sites More sharing options...
Det. Bart Lasiter Posted March 7, 2006 Share Posted March 7, 2006 @BongoBob- Here's a simplified version of yours: #include "stdafx.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int nChoice; float fResult, fRadius; float PI = 3.14159; cout << "1. Calculate circumferance.\n"; cout << "2. Calculate area.\n"; cout << "3. Exit.\n"; cout << "Choice: "; cin >> nChoice; switch(nChoice) { case 1: cout << "Radius: "; cin >> fRadius; fResult = PI*(fRadius * fRadius); cout << fResult << endl; return 0; case 2: cout << "Radius: "; cin >> fRadius; fResult = PI*fRadius; fResult *= fResult; cout << fResult << endl; return 0; case 3: break; } return 0; } Link to comment Share on other sites More sharing options...
BongoBob Posted March 7, 2006 Author Share Posted March 7, 2006 Programming illiterate alert!!! How do I use this? Cause I'd love to try it out. You have to use a compiler to compile the source code into an executable file. Later I'll compile it on Windows, and I'll upload it and post it here. I think your formula for the area of a circle is incorrect. It should be a = pi * r * r. area of circle is pi * r^2, not (pi * r)^2. ( "^2" means "squared") optherwise, well done. Edit: plus, some pants stealing squirrels. *Geometry teacher tosses something heavy at me* Thank you for catching that narfblat BRING BACK MY PANTS! Shame, Bongo. I can do that in GWBASIC in less than 10 minutes, with hardly any code, as compared to that massive code you had there. Of course, you have done all that diameter/area etc. stuff, with choice and all. I can do all that, but I'm feeling too lazy write now. But your finds only finds one thing, mine finds circumference or area, and it also divides/multiplies the diameter/radius to get you a radius/diameter. @BongoBob- Here's a simplified version of yours: #include "stdafx.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int nChoice; float fResult, fRadius; float PI = 3.14159; cout << "1. Calculate circumferance.\n"; cout << "2. Calculate area.\n"; cout << "3. Exit.\n"; cout << "Choice: "; cin >> nChoice; switch(nChoice) { case 1: cout << "Radius: "; cin >> fRadius; fResult = PI*(fRadius * fRadius); cout << fResult << endl; return 0; case 2: cout << "Radius: "; cin >> fRadius; fResult = PI*fRadius; fResult *= fResult; cout << fResult << endl; return 0; case 3: break; } return 0; } Wow, that's some slightly more advanced code than I know of. I might go back and use switch case in my program just becuase I havn't used that yet. Also, your code doesn't half the diameter for area, or multiply the radius for circumference. Do that, and it would be my program in a much smaller package. Also, I really wrote this as a test of custom functions, something that I really hadn't done yet, which is a contributing factor to the unorganizedness and whatnot. Whew, I think I'm done with that long ass post Link to comment Share on other sites More sharing options...
ET Warrior Posted March 7, 2006 Share Posted March 7, 2006 Just as a little aside...at the end of that revised code I would have a case 3: default: break; } That way if they input anything that isn't a 1, 2, or 3 your code will still handle it gracefully...unless they input a char....then you'll still crash miserably... Link to comment Share on other sites More sharing options...
IG-64 Posted March 7, 2006 Share Posted March 7, 2006 Eh, i'll learn programming eventually. Link to comment Share on other sites More sharing options...
ET Warrior Posted March 7, 2006 Share Posted March 7, 2006 Here's a piece of code I've been working on the last week or so. It's meant to simulate the process manager aspects of an Operating System...it's terribly lame, and right now the file I/O isn't working at all, if anyone feels like looking over my get_code() function (which is hacked to pieces now with our debugging) and tell me why it fails miserably that would be super duper. /*File - Main.cxx Authors: AJ Lindell and Ryan Phillips Program - This is the file that will implement all of our actual processes. It creates the first process which spawns our process manager, which can spawn a reporter process. All of that code will be in here. Classes used: Queue QueueArray process_data */ #include <iostream> #include <queue> #include <assert.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <fstream> #include <iomanip.h> #include <string> #include "queuearray.h" #include "processdata.h" using namespace std; /*********************************************************/ //Function Prototypes //TODO: make functions void executeProcess(process_data* pcb[],process_data&cpu,queue<int>& bqueue, queuearray<int>& qarray, int& time, int& running, int& completed); //Unblock a command void unblock(queue<int> bqueue, queuearray<int>& qarray,process_data* pcb[]); //Reporter process void makeReporter(int time, int running, queue<int>& bqueue, queuearray<int>& qarray, process_data* pcb[]); //print const void print(int time, int running, queue<int>& bqueue, queuearray<int>& qarray, process_data* pcb[]); //Context Switch void context_switch(int& running,process_data& cpu,queuearray<int>& qarray, process_data* pcb[]); //read in the code for the PCB's void get_code(process_data* entry, char file); //Manage the scheduling void schedule(int& running, process_data* pcb[], process_data& cpu, queuearray<int>& qarray); //Create new simulated process void spawnProcess(int& running, process_data* pcb[], process_data& cpu, queuearray<int>& qarray, int time); /*********************************************************/ /*********************************************************/ int main(int argc, char **argv) { //Variable creation pid_t managerPid; int managerPipe[2]; int status; int runningState=0; int time = 0; int completed = 0; char buf[1]; char *message = new char(); ifstream program; queuearray<int> readyState(4); queue<int> blockedState; process_data* pcb[10]; process_data cpu; //Create the Pipe, and fork the process manager if(pipe(managerPipe) !=0) { perror("managerPipe"); exit(EXIT_FAILURE); } if( (managerPid = fork()) == 0) { //Code for the process manager cout << "mechild" << getpid() << endl; //create the first object in the pcb and load up //the first 'program' pcb[0] = new process_data(); pcb[0]->startTime = time; get_code(pcb[0],'A'); cpu = *pcb[0]; //Begin the main functionality of the process manager do { read(managerPipe[0],buf,1); switch(*buf) { case 'Q': cout << "Q" << endl; time ++; executeProcess(pcb,cpu,blockedState,readyState,time, runningState,completed); cout << "DID Q" << endl; break; case 'U': unblock(blockedState,readyState,pcb); break; case 'P': makeReporter(time,runningState,blockedState,readyState,pcb); break; case 'T': cout << "ITS OVAR" << endl; break; } }while(*buf != 'T'); } else { cout << "Child pid: " << managerPid << endl; cout << "My pid: " << getpid() << endl; do { //Code for the commander cin >> message; write(managerPipe[1],message,1); sleep(1); }while(*message != 'T'); } delete message; for(int i = 0;i<10;i++) delete pcb[i]; return 0; } /*********************************************************/ /*********************************************************/ //Reporter Process void makeReporter(int time, int running, queue<int>& bqueue, queuearray<int>& qarray, process_data* pcb[]) { print(time,running,bqueue,qarray,pcb); return; } /*********************************************************/ /*********************************************************/ const void print(int time, int running, queue<int>& bqueue, queuearray<int>& qarray, process_data* pcb[]) { int temp; queue<int> tempQ = bqueue; cout << "CURRENT TIME:" << time<<endl<<endl; cout << "RUNNING PROCESS:" <<endl; cout << pcb[running]<<endl<<endl; cout << "BLOCKED PROCESSES:"<<endl; while(!tempQ.empty()) { temp=bqueue.front(); cout << pcb[temp]<<endl; bqueue.pop(); } cout << "PROCESSES READY TO EXECUTE:"<<endl; qarray.PrintQueue(); cout << "Finished" << endl; } /*********************************************************/ /*********************************************************/ //Execute process void executeProcess(process_data* pcb[], process_data& cpu, queue<int>& bqueue, queuearray<int>& qarray, int& time, int& running, int& completed) { char command = cpu.programPtr[cpu.programCounter]; int value = cpu.argumentPtr[cpu.programCounter]; time ++; //get the next line to execute in the code section //////// cout << "Exeuction" << command << value<< endl; switch(command){ case 'S': cpu.value = value; cpu.usedTime ++; schedule(running, pcb, cpu, qarray); break; case 'A': cpu.value += value; cpu.usedTime ++; schedule(running, pcb, cpu, qarray); break; case 'D': cpu.value -= value; cpu.usedTime ++; schedule(running, pcb, cpu, qarray); break; case 'B': bqueue.push(running); pcb[running]->s = blocked; if(pcb[running]->priority < 4) pcb[running]->priority ++; context_switch(running,cpu,qarray,pcb); break; case 'E': completed++; delete pcb[running]; break; case 'F': spawnProcess(running, pcb, cpu, qarray, time); cpu.usedTime ++; schedule(running, pcb, cpu, qarray); break; case 'R': get_code(pcb[running],value); cpu.programCounter = 0; break; } cout << cpu.value << endl; } /*********************************************************/ /*********************************************************/ void unblock(queue<int> bqueue, queuearray<int>& qarray, process_data* pcb[]) { int i; if(bqueue.size() > 0) { i = bqueue.front(); bqueue.pop(); qarray.Enqueue(i,pcb[i]->priority); } } /*********************************************************/ /*********************************************************/ void context_switch(int& running,process_data& cpu,queuearray<int>& qarray, process_data* pcb[]) { *(pcb[running])=cpu; if(qarray.Dequeue(running) == 1) cpu=*(pcb[running]); } /*********************************************************/ /*********************************************************/ void get_code(process_data* entry, char file) { string* s = new string(1,file); ifstream fin; fin.open(s->c_str()); int i=0; char* tmp=NULL; string temp; vector<char> cmd; vector<int> arg; while(fin && !fin.eof()) { cout << "broken?" << endl; // fin >> *tmp; //cout << *tmp << endl; fin >> temp; cout << temp; // cmd.push_back(*tmp); if(fin.peek()==' ') { fin.ignore(); fin.getline(tmp,10); if(cmd[i] == 'R') arg.push_back(*tmp); else arg.push_back(atoi(tmp)); } i++; } entry->programPtr = cmd; entry->argumentPtr = arg; fin.close(); } /*********************************************************/ /*********************************************************/ void schedule(int& running, process_data* pcb[], process_data& cpu, queuearray<int>& qarray) { if(cpu.usedTime == cpu.timeSlice) { if(pcb[running]->priority > 0) pcb[running]->priority --; qarray.Enqueue(running,pcb[running]->priority); context_switch(running,cpu,qarray,pcb); } } /*********************************************************/ /*********************************************************/ void spawnProcess(int& running, process_data* pcb[], process_data& cpu, queuearray<int>& qarray, int time) { int i; for(i=0;i<10;i++) { if(pcb[i]!= NULL) { pcb[i] = new process_data(); break; } } pcb[i] = pcb[running]; pcb[i]->pid = i; pcb[i]->ppid = running; pcb[i]->startTime = time; pcb[i]->usedTime = 0; pcb[i]->programCounter ++; pcb[running]->programCounter += 1; //Fix this addition to the stuff qarray.Enqueue(i,pcb[i]->priority); } /*********************************************************/ Link to comment Share on other sites More sharing options...
BongoBob Posted March 7, 2006 Author Share Posted March 7, 2006 Thank you ET for making my brain hurt Actually, it does inspire me to keep going in my lessons. One day I'll understand more than just bits and pieces of that code. Link to comment Share on other sites More sharing options...
ET Warrior Posted March 7, 2006 Share Posted March 7, 2006 The code would probably be more readable if I'd done a decent job of commenting. But I get pretty sloppy on the comments when I'm writing homework, because it's unlikely that anyone will have to read and modify this code. I also didn't post the code for the process_data or queuearray classes we're utilizing, so the member functions and variables of those classes I'm accessing aren't exactly clear. #ifndef PROCESSDATA_H #define PROCESSDATA_H #include <iostream> #include <vector> enum state{running, blocked, ready}; struct process_data { public: std::vector<char> programPtr; std::vector<int> argumentPtr; int pid; int ppid; int startTime; int usedTime; int programCounter; int timeSlice; int value; int priority; state s; process_data() { pid=0; ppid=0; startTime=0; usedTime=0; programCounter=0; timeSlice=0; value=0; priority=0; s=ready; } ~process_data() { } process_data& operator =(const process_data& sorce) { this->programPtr = sorce.programPtr; this->argumentPtr = sorce.argumentPtr; this->pid = sorce.pid; this->ppid = sorce.ppid; this->startTime = sorce.startTime; this->usedTime = sorce.usedTime; this->programCounter = sorce.programCounter; this->timeSlice = sorce.timeSlice; this->value = sorce.value; this->priority = sorce.priority; this->s = sorce.s; return *this; } friend std::ostream& operator <<(std::ostream& outputStream, const process_data& elem); friend std::ostream& operator <<(std::ostream& outputStream, const process_data* elem); void print() { std::cout << this; } }; std::ostream& operator <<(std::ostream& outputStream, const process_data& elem) { outputStream << '<' << elem.pid << ' ' << elem.ppid <<' '<< elem.priority<<' '<< elem.value <<' '<< elem.startTime<<' ' << elem.usedTime << '>'; return outputStream; } std::ostream& operator <<(std::ostream& outputStream, const process_data* elem) { outputStream << '<' << elem->pid << ' ' << elem->ppid <<' '<< elem->priority<<' '<< elem->value <<' '<< elem->startTime<<' ' << elem->usedTime << '>'; return outputStream; } #endif That's the process_data class. If you want any explanations of any of the specifics of these code segments feel free to shoot me a PM, I rather enjoy assisting budding programmers. Link to comment Share on other sites More sharing options...
BongoBob Posted March 7, 2006 Author Share Posted March 7, 2006 What is Visual Basic used for? I keep begging my teacher to not use Visual Basic, and to use C++ instead, but she insists. And yes, the class is so stupid that we havn't written one single program, and we're nearing the end of the 3rd semester >< Link to comment Share on other sites More sharing options...
Joetheeskimo Posted March 7, 2006 Share Posted March 7, 2006 What is Visual Basic used for? Um, what is it used for...? Not sure what you mean by that? It allows you to write Windows programs and actually design how the window will look with drag-and-drop. I'm told that it's deeply discouraged my most seasonaed coders to learn Visual Basic first, beacuse it will teach you all the wrong things about programming. I've purchased a book on C++, but have yet to open it. I plan to soon thanks to Microsoft giving away Visual Studio free. Now I have Visual C++. Link to comment Share on other sites More sharing options...
Jeff Posted March 7, 2006 Share Posted March 7, 2006 I'm talking a VB class right now, and ironically the class is called "advanced visual basic." I've been into programming since I learned about it though, way back when. For my final project in the class I'm gonna design a 2D RPG using DirectX with this awesome book I got for Christmas, "Game programming with visual basic for teens." Perfect. This is probably something I'll be looking into doing at college, at least something in the computer science/information systems field... Link to comment Share on other sites More sharing options...
Det. Bart Lasiter Posted March 7, 2006 Share Posted March 7, 2006 @ET Warrior- What is the 'get_code()' function supposed to do? @BongoBob- VB is usually used to write programs where memory performance isn't really an issue, mostly programs that focus on ease of use for the end-user. Link to comment Share on other sites More sharing options...
ET Warrior Posted March 8, 2006 Share Posted March 8, 2006 We actually managed to fix the bugger. I honestly don't know what our problem was, but we arsed our way through it. Basically it was supposed to read in a file and store the data into two separate vectors....now it is mostly working happily. Link to comment Share on other sites More sharing options...
Det. Bart Lasiter Posted March 8, 2006 Share Posted March 8, 2006 Here's some code on the manipulation of files with the standard library. My compiler is acting quite buggy now though (it won't open <stdlib.h> or <stdio.h>, strange...), so there may be some minor bugs in it, however it should compile fine in VS or whatever. Here's the header file: #ifndef _FUNCTIONS_H_ #define _FUNCTIONS_H_ class CDataStructure { public: /** This is the data stucture to be read. */ struct sDataStructure { char *cString[10]; int nNumber; }; CDataStructure(); CDataStructure(char *cString[10], int nNumber); ~CDataStructure(); void readDataAtIndex(const char *pszPath, int nIndex); }; #endif // _FUNCTIONS_H_ And the source file: #include <stdio> #include <stdlib> #include "functions.h" CDataStructure::CDataStructure() { sDataStructure.cString = ""; sDataStructure.nNumber = 0; } CDataStructure::CDataStructure(char *cString[10], int nNumber) { sDataStructure.cString = cString; sDataStructure.nNumber = nNumber; } CDataStructure::~CDataStructure() { sDataStructure.cString = NULL; sDataStructure.nNumber = NULL; } void CDataStructure::readDataAtIndex(const char *pszPath, int nIndex) { FILE *f = fopen(pszPath, "rb"); for(int i = 0; i < nIndex; i++) { fread(sDataStructure.cString, 10, 1, f); fread(sDataStructure.nNumber, 8, 1, f); } } I'll probably post some DX3D code later, maybe physics-related or HDR or something. Link to comment Share on other sites More sharing options...
BongoBob Posted March 8, 2006 Author Share Posted March 8, 2006 Wow,there's alot more experienced programmers on here than I thought, keep up the discussion and help Glad to hear you got your program mostly working ET Link to comment Share on other sites More sharing options...
Sabretooth Posted March 8, 2006 Share Posted March 8, 2006 Wow, I made that Circum/Area thing with interaction, friendly text et all, but it's taking up 25+ lines of code! Unfortunately, it had a few bugs in there. Will fix when have time. Link to comment Share on other sites More sharing options...
BongoBob Posted March 8, 2006 Author Share Posted March 8, 2006 Hell, I could make my code 1 line, it just wouldn't be very readable. Anyhow, I was going to work on getting my program to loop and use switchcase and whatnot, but ET was helping me understand pointers and trees last night. Combine that with the fact that we had a near death in the family, and well, I'm hard pressed for time. I'll see if I can do some stuff on it when I get home today, but I don't know when I am gonna get home. I could get home around 3:00, I could get home around 8:00. Link to comment Share on other sites More sharing options...
Sabretooth Posted March 9, 2006 Share Posted March 9, 2006 I finally managed to develop a code that generates the Fibonacci sequence, all by myself. Here is the code, along with my official Sabre Code logo: Link to comment Share on other sites More sharing options...
BongoBob Posted March 9, 2006 Author Share Posted March 9, 2006 A little question for you all. What's the most complex program you've ever made? Link to comment Share on other sites More sharing options...
Det. Bart Lasiter Posted March 9, 2006 Share Posted March 9, 2006 It's unfinished now, however I'm writing a 3D game engine using DirectX 9.0c (February). When I finish it I'll probably just keep adding features onto it like AA, AN, HDR, and Dynamic Lighting. I'm writing it in unmanaged C++ and x86 assembly. Link to comment Share on other sites More sharing options...
BongoBob Posted March 9, 2006 Author Share Posted March 9, 2006 Well that's certainly a large task. I wish you the best and hope that you don't have too many problems EDIT: I'm going to be nothing for an hour and a half later today during school, and was wondering if anyone had an idea for a program that I could do. To know what I can do, I've completed everything up to strings on the cprogramming.com site. Link to comment Share on other sites More sharing options...
Prime Posted March 9, 2006 Share Posted March 9, 2006 A little question for you all. What's the most complex program you've ever made?Probably developing a real-time callP applications for next generation wireless networks Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.