'''DANGER WILL ROBINSON ...''' http://www.lostinspacetv.com/ART/download/E-Episodes/E16.jpg '''... DANGER WILL ROBINSON ...''' The following is a collection of early material intended as a tutorial in the C programming language. The original was well-intentioned, but written by someone assuming the reader was using Microsoft Windows, or even DOS, so much of it was unportable, and in places even wrong. Several people undertook to make the page more widely applicable, others took it on themselves to simply criticise those making the assumptions. The result is untidy, in place inaccurate, and in other places unpleasant. Perhaps someone can recover something useful from it. There are plenty of other, better researched and better presented tutorials out there, and perhaps this page would be better simply to point to them. ---- '''Presentation''' This program for beginners series proposes a series of elementary programs to introduce the users to the syntax of most programming languages. This is an introduction to the fundamental C syntax and then moving to C++. I've modified the examples below to suit Bloodshed... and to correct silly errors! The Pause line is just to allow results to be viewed before the DOS window closes, allowing the program to be tested from the development environment. For Microsoft Visual C++, add #include and omit the PAUSE. ''Why do you assume that the pupil is using DOS? You don't need a PAUSE if you're running your code from a console window.'' I don't assume DOS. I do assume some readers may not take the trouble to create such a window. ''You appear to have got the wrong end of the stick entirely. What do you mean, "create such a window"? I'm talking about someone using a UNIX-based system and typing code into an xterm, or similar.'' ''(Someone else) By using ''system("PAUSE");'' you're assuming a ''system'' that knows ''PAUSE''. DOS does, other systems may not. It's not a big thing, but it makes for poor portability.'' ---- '''Program # 1: Hello world. How to start and end a program; how to write something on the screen; how to compile a program''' '''Explanation''' '''Code''' #include #include int main() { printf("Hello world! \n"); system("PAUSE"); return 0; } ---- '''Program # 2: an input is asked from the user (a number); Defining a variable, putting it in memory and printing it on the screen''' '''Explanation''' * Let's put int main () and an opening curly bracket to start the program. * We are now asking the user his age: printf("Dude, how old might you be?") * He will answer with a number. It can be any number of course; since it is not set, fixed, we call it a '''variable'''. Therefore the first thing we'll do is tell the program that we'll have a number variable. The syntax to use to tell the machine we have a number variable is int Age; int stands for integer. Int Age; means we'll have an integer variable called Age. We call this action of putting Int Age: defining a variable. * We want to clear the screen to delete what was before. So we put clrscr(); [I took this out - it's possible (if conio.h is included), but non-standard. If you must, use system("CLS"); instead.] * Dude will enter a number. The rest is tricky. We have to tell the program to take his answer (a number) and to put it in memory. The syntax we'll use for that is: scanf("%d", &Age); It means: scan the answer and put the number variable in memory. * And finally we'll ask the program to put on the screen the variable stored in memory (Dude's age.) printf("Dude you are %d years old but you look older,\n", Age); * \n is the newline character '''The code''' #include #include int main() { int Age; printf("Hey dude, how old might you be?"); scanf("%d", &Age); printf("Dude you are %d years old but you look older\n", Age); system("PAUSE"); return 0; } '''Practice exercise''': Ask a person in which year he/she will retire. Remember: a name for a variable must not contain spaces. It is quite like a wiki word with the first letter of each word in upper case. Ex: RetirementYear. ---- '''Program # 3a: Very similar to # 2. But this time the variable will be a character or a series of characters''' '''Explanation''' In program # 2 we defined a number variable (int Age;), we put it in memory with scanf%d and we displayed it from memory with printf%d Today we'll do almost the same thing. Except that instead of having a number variable we'll have a character variable (a to z). It's roughly the same process except that we'll define the variable with char instead of int + we'll now have "s" instead of "d" in the scanf and printf functions. * We define the character variable this way: char Name; * We scan it and we put it in memory this way: scanf("%s", &Name) * We call if from memory and we print it this way: printf("%s", Name); '''The code''' #include #include int main() { char Name[100]; printf("And what's your name?"); scanf("%99s", Name); printf("\nPleased to meet you %s\n", Name); system("PAUSE"); return 0; } ---- '''Program # 3b: Same as 3a but this time with 2 variables: the name and the surname variables''' '''Explanation''' Notice we now cope with a name that contains first name and surname. '''The code''' #include #include int main() { char Name[60]; char Surname[60]; printf("And what's your complete name?"); scanf("%59s%59s", Name, Surname); printf("\nPleased to meet you %s %s\n", Name, Surname); system("PAUSE"); return 0; } ---- '''Program # 3c: Written in C++ style''' '''Explanation''' The code so far will exhibit undefined behaviour if the first name or last name overflow the length of the (fixed-size) arrays provided. Here's how to get around this problem by using C++ streams. This code is 100% conforming ISO C++. '''The code''' #include // for std::cout, std::cin #include // for std::string int main(void) { std::string name; // can be as long as we want! std::string surname; // can be as long as we want! std::cout << "And what's your complete name?\n"; std::cin >> name; std::cin >> surname; std::cout << "Pleased to meet you " << name << " " << surname << "\n"; system("PAUSE"); return 0; } Those "std::" parts look cluttered. You can get rid of them by adding a "using" directive, which drags in an entire namespace: '''Program # 3c-1: Written with a "using" directive''' #include // for std::cout, std::cin #include // for std::string using namespace std; // always look in std namespace int main(void) { string name; // can be as long as we want! string surname; // can be as long as we want! cout << "And what's your complete name?\n"; cin >> name; cin >> surname; cout << "Pleased to meet you " << name << " " << surname << "\n"; system("PAUSE"); return 0; } However, this drags in every name in "std". And "std" has a lot of names in it, some of which you might be using yourself. So it's better simply to explicitly state *which* names you're using: '''Program # 3c-2: Written with specific "using" declarations''' #include // for std::cout, std::cin #include // for std::string using std::string; using std::cout; using std::cin; int main(void) { string name; // can be as long as we want! string surname; // can be as long as we want! cout << "And what's your complete name?\n"; cin >> name; cin >> surname; cout << "Pleased to meet you " << name << " " << surname << "\n"; system("PAUSE"); return 0; } So if you just use some namespace feature once, you use "::" literature::Stylistic''''''Analysis my_analysis(text); But if you use such a feature many times, you unclutter the code by using that one feature explicitly: using literature::Stylistic''''''Analysis; Stylistic''''''Analysis my_analysis1(text1); Stylistic''''''Analysis my_analysis2(text2); // etc This makes the maximum use of namespaces unless some precise feature is used heavily (as cin and cout and string usually are!) with maximum avoidance of future name conflicts, while instilling good habits that won't lead to trouble later, even if you end up using dozens of packages, some of which inevitably have conflicting names. -- DougMerritt ---- For more on the difference between a using ''declaration'' and a using ''directive'', see http://burks.brighton.ac.uk/burks/language/cpp/cpptut/cplus003.htm#l43. ----- '''Program # 4: Text-based adventure (InteractiveFiction), using data-driven coding.''' '''Explanations''' ''The program is driven by a data type called Map. A Map knows three things: a description of a location and two choices you can make at each location. We've put the 'world' of the game into 9 Maps we call locations. We keep track of the locations with numbers. The number 20 represents a special location signifying the end of the game. We refer to the map which represents where we are as our current_location. As long as our current location is not 20, we tell the user our current_location's description and ask the user if they want to use the current_location's first choice or second choice. We've set things up so a Map's choices correspond to the names of locations. So to change locations, we just have to change our current_location to whatever location is pointed to by the same number as the result of the user's choice. (I wince whenever I proof that last sentence, someone explain it better than me.) We do this whenever the user makes a choice. If the special location number 20 crops up, we pause the program, then end when the user hits any key.'' '''So to change locations, we just have to change our current_location to whatever location is pointed to by the same number as the result of the user's choice. (I wince whenever I proof that last sentence, someone explain it better than me.)''' '''Elements of the program''' * using namespace std; * typedef struct {string message; int first_choice; int second_choice;} Map;. We have created a file/database called Map; it has 3 fields: ** message (defined as string); ** first_choice and second_choice (both defined as integers) * 'typedef' stands for "Type Definition"; it's creating a new type named Map. 'struct' stands for "Structure": it's saying that we want to group a bunch of related values together, so we can refer to them at once. Those variables will be a 'string' named 'message' that will be displayed to the user, and two integers named 'first_choice' and 'second_choice' that represent what we do if the user selects that option. * #define END 20; end will be at # 20 * Notice the program starts at the bottom at int main(); this is the way C works: you put the functions '''on top''' of the main and these functions are called by what is written after int main() because int main() is read first. '''Code''' #include #include using namespace std; typedef struct { string message; int first_choice; int second_choice; } Map; Map current_location; #define END 20 Map locations[9] = { {"You are on a footpath... To go to the forest enter 1, to go to the stream enter 2\n", 1, 4}, {"You are in the forest. Enter 1 to go to the clearing, Enter 2 to return to the footpath\n", 2, 0}, {"You are in the clearing. Enter 1 to go to the fairy circle or 2 to return to the forest.\n", 3, 1}, {"You are in the fairy circle. Enter 1 to leave the world or 2 to return to the clearing.\n", 8, 2}, {"You are standing next to a stream. Enter 2 to find a bridge or 1 to go back to the footpath.\n", 0, 5}, {"You have found a bridge. To cross the bridge to the fort enter 2 or 1 to go back to the stream.\n", 4, 6}, {"You have reached the fort. Enter 2 to go to bed or 1 to go back to the bridge.\n", 5, 7}, {"Night Night sleepy-head. Thank-you for playing.\n", END, END}, {"Thanks for playing. I hope you enjoyed exploring, see you soon.\n", END, END} }; int main() { int current_index = 0; int user_choice; while(current_index != END) { current_location = locations[current_index]; cout << current_location.message; cin >> user_choice; if(user_choice == 1) { current_index = current_location.first_choice; } else { current_index = current_location.second_choice; } } system("PAUSE"); return 0; } [Thanks to JonathanTang for coding all the logic in the above example.] ---- Contributors: SusannahWilliams, DougMerritt, JonathanTang, 217.137, RonJandrasi, JoeWeaver, DaveFayram See also: LearningCee IwannaLearnCeePlusPlus ---- CategoryCee CategoryCpp CategoryExample CategoryInManyProgrammingLanguages