Cee Programs For Beginners

DANGER WILL ROBINSON ...

... 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 <stdafx.h> 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 <stdio.h>
 #include <stdlib.h>

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

The code

 #include <stdio.h>
 #include <stdlib.h>

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.

The code

 #include <stdio.h>
 #include <stdlib.h>

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 <stdio.h> 
 #include <stdlib.h>

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 <iostream> // for std::cout, std::cin
 #include <string> // 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 <iostream> // for std::cout, std::cin
 #include <string> // 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 <iostream> // for std::cout, std::cin
 #include <string> // 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::StylisticAnalysis my_analysis(text);

But if you use such a feature many times, you unclutter the code by using that one feature explicitly:

  using literature::StylisticAnalysis;
  StylisticAnalysis my_analysis1(text1);
  StylisticAnalysis 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

Code

 #include <iostream>
 #include <string>
 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


EditText of this page (last edited August 15, 2005) or FindPage with title or text search