Gillius's Programming

The main function is the place where the code exectuion begins. Unlike BASIC and Pascal, a function needs to be declared for code execution. There are only two valid declarations for the main function:

int main() {
  return 0;
}

and

int main( int argc, char** argv ) {
  return 0;
}

The int means that the function returns an integer (a positive or negative whole number). The main is its name, and the () state that this function takes no parameters. The brackets indicate the beginning and end of the function/procedure. The second form takes command line information, and is not discussed at this time. For our first examples we will use the first form. The return statement ends the function, returning the value given (in this case, 0). When the main function returns, this error code is passed back to the operating system. In modern environments, this code is not always used, but scripts and programs occassional use it, espically those in UNIX or Linux environments where this code usually signifies if the program ran successfully. Returning 0 indicates the program terminated without error.


Comments in C help to explain what a program is doing. The syntax is fairly simple:

/*This is a comment in the
    C or C++ language*/
int main() { //Comments like these appear in C++
}

The /* */ method works for multiple lines. C++ has a shortcut method, using just //, which is like the single quote from BASIC, and only comments until the end of a line. Mostly I will be using the // comments which are much faster and easier to type.

ADDEDENUM: The newest standard for C, C99, allows // comments. All modern compilers I have used support // style comments even in C mode.


Simple output to a text screen is achieved in C through the printf statement and in C++ with cout.

/* C code */
#include <stdio.h>

int main() {
  printf("Hello World!\n");
  return 0;
}

If using C++, you can use the above program (REMEMBER: virtuall all of C commands work with C++), but C++ allows for an extra feature called cout, which is really an instance of a class. Cout will be discussed in depth in a later tutorial.

//C++ Code
#include <iostream>
using namespace std;

void main() {
  cout << "Hello World!" << endl;
}

An explanation of #include is needed here. C starts with no basic commands, and includes what you use, to include only what files are absolutely necessary to run the program. The file stdio.h has printf and iostream (C++ ONLY) has cout.

Includes work a little differently in C++ than in C. Firstly, none of the C++ headers have an .h extension. Secondly, the standard symbols in C++ are all inside of the std namespace. This was a change made in the 1998 standard for C++. To be able to use these symbols without qualifying their names, we use using namespace std; to import the std namespace to the global namespace. If this confuses you for now, just make sure to put using namespace std; after all of your #include statements in each C++ source file. This tutorial will use this technique as it was written before the standard had been implemented and later converted to the new standard. When using C headers in C++ (like stdio.h), be sure to apply the following conversions:

  1. Remove the ".h" extension from the file name.
  2. Add a c to the start of the file name.

Example: stdio.h becomes cstdio and string.h becomes cstring. Throughout the rest of this tutorial we will use the C++ style includes even if we are not using features exclusive to C++, unless otherwise stated. The previous program using printf would be rewritten for C++ in the following way:

#include <cstdio>
using namespace std;

int main() {
  printf("Hello World!\n");
  return 0;
}

The programs above output the string indicated inside the quotes. The C-style version ends the current line with \n and the C++ version with endl. As you can notice each line of code ends with a semicolon. Whitespace does not matter in C++ whatsoever between tokens and theoricially an entire program can be written on each line or an entire program with only one word per line, like this perhaps:

#include <iostream>
using namespace std;

void main() {
  cout << "Hello World!"
       << endl;
}

As you can see the line does not really end until the compiler encounters a semicolon. Some programmers prefer to seperate the lines like that on long output statements.

Some programmers from other languages might recognize the << and >> as bitwise shifts. This is true when used with numeric variables, and this concept will be explained in later lessons.

Now an explanation how these statements work. Printf is much like print using from BASIC or write from Pascal. The reason why printf is like BASIC's print using instead of just print will be explaned in the Output II lesson. Each parameter for cout is seperated by <<, in this example the string "Hello World!" and the end-of-line manipulator, endl. endl in C++ differs very simply from "\n" in C in that it forces the text to be displayed to the screen immediately.


Variables in C need to be declared, but unlike Pascal, can be declared at any time during a procedure in C++, but unfortunately in C it must be declared at the beginning of the procedure. The program below shows valid delcarations in C++:

int main() {
  int c;            //This declares an integer
  c = 50;           //This sets c to 50
  int d = 75;       //Combonation of declaration and initalization
  float f = 17.235f;//A real number type variable
  char g = 'g';     //A character type variable
  return 0;         //Returns from main (ends the program) with code of 0
}

However, to do this in C, where the variables have to be first, you must convert the program to this, since all declarations must come before any executable code. This is also good programming style, to always declare variables first anyways, despite the language, however there are times where you only need a variable temporarily for a very short time (such as a for loop described later), where C++'s declarations can come handy.

int main() {
  int c;            //This declares an integer
  int d = 75;       //Combo declaration and initalization
  float f = 17.235f;//A real number type varaible
  char g = 'g';     //A character type varaible
  //Declarations complete, now to executable code:
  c = 50;           //This sets c to 50
}

Variables are pretty straight forward and do not need much explanation, but a few notes on variable types. Integers in most compilers can only handle ranges of -2^32 to 2^32-1, which is roughly +/- 2 billion. This is good for most applications but they cannot handle decimals, like float can. Floats can store pretty much any number to a certain accuracy, since they are basically stored like scientific notation. Char variables only hold a letter or a small integer, but notice that characters are in single quotes and not double quotes, which are strings. The standard does not specify if the char type is signed or unsigned, so it depends on your compiler if the range for char is (-128 to 127) or (0 to 255). You can use signed char or unsigned char to ask for a specific type. Strings, despite what BASIC/Pascal lead you to believe, are really arrays of characters where the last character has a value of 0 (the NULL character, \0), and will be discussed in a later section. You will notice that we appended the letter f to the real numbers in the previous program. That is because the number 17.235 is of type double, and 17.235f is of type float. Double is always equal or higher precision than float, so it is valid to implicitly convert from a float to a double but not vice-versa. Some, but not all compilers will give a warning if you forget to place the f.

Any name given to something in C is case-sensitive, unlike in BASIC. Many characters can be used in the names, however most programmers only use the letters, and the underscore, _, for spaces. Numbers can be used in the names, but the name cannot start with one.

//Valid Names
 MyFunction
 My_Procedure
 Display600Variables
 ProfitMargin
//Invalid Names
 600Variables

Most programmers, when using multiple words in a name, capitalize each word, or use the underscore, _.

Converting a character to its ASCII value or vice versa is much simpler in C than in BASIC or Pascal, since in reality they are the same thing. Char variables always store a number--it's just that the compiler interprets it as a character. So the two statements below are the EXACT same thing:

int main() {
  char x = 65; //ASCII 65 is 'A'
  char g = 'A';//x and g are the same thing now
  return 0;
}

Working with varaibles in C is much like any other language:

int main() {
  int x = 0; int y = 5; /* Notice multiple commands on one
                           line, since whitespace does not
                           count*/
  x = y; //Some obvious operation examples follow
  x = y + 5;
  x = 500 * 50;
  y = x / 50;
  y = y + 1; //Adds one to y
  x = 10 % 3 //% returns the remainder, in this case x will be 1
  return 0;
}

Output with variables with C are a little more complex than in C++. The C++ method will be shown first since it is simpler to understand.

#include <iostream> //For std::cout
using namespace std;

int main() {
  int x = 50; int y = 10;
  x = x + y;
  cout << "The current value of x is: " << x << endl;
    //Each part of the output seperated by <<'s
  return 0;
}

This is similar to Pascal's writeln statement, which took basically any parameter seperated with commas, except these are just <<'s. BASIC's output is also similar to this. In C-style code this process is a little more like print using from BASIC, and a little more complex:

#include <cstdio> //for std::printf
using namespace std;

int main() {
  int x = 50; int y = 10;
  x = x * y;
  printf("The current value of x is: %i\n", x);
  return 0;
}

The printf takes a format string like BASIC's print using. The %i is replaced by the value of x, the first parameter. Extra parameters to printf are passed in the order the variables appear in the format string, for example:

printf("The value of x is: %i and the value of y is: %i\n", x, y);

There are more format specifiers than %i. These get more complex, but these are the simple and most used ones:

In addition to the % format specifiers there are special characters which can appear in any string, not just in a printf. These are a few of them:

Throughout the rest of the tutorial I will mostly be using couts, since they are easier to understand. However even for C++ programmers it is important to understand printf, since it is used in many programs.


There are some more complex and shortcut ways to work with variables than specified in Variables I. Also variables can be compared and used in if statements. If statements in C work just like those in BASIC or Pascal but just with a few syntactial changes.

#include <iostream>
using namespace std;

int main() {
  int x = 5;
  int y = 10;
  x *= 5;    //This is the same as x = x * 5;
  x += y;    //Same as x = x + y;
  x %= 3;    //x = x % 3; This shortcut works for all operators,
             //  even the odd ones like %.
  --x;       //This simply subracts 1 from x like x=x-1;
  ++x;       //Adds one to x

  if (x > 0) //Let's see what we've done
    cout << "X is positive";
  else if (x < 0)
    cout << "X is negative";
  else
    cout << "X is zero";
  cout << endl;
  return 0;
}

Shortcuts can come in handy, espically the ++ and -- operators, which usually execute faster as most CPUs have a special increment/decrement operation just for this case. The if statement is not new to experienced programmers, and even the syntax is very similar. Notice that the endl is on its seperate line -- this is not nessacary, but it is faster for the programmer to type and a little less redundant. Notice there are no braces, {}, on the if statements, but that is because they are only one line long (remember a line is defined as a semi-colon NOT with the enter key!) But if a more complex structure is needed the syntax is not much different:

int x = 50; int y = x + 10;
if (x > 10) {
  cout << "X is over 10";
  y = x;
}

The only thing needed for multiple statements is the braces.


Input in C-style programs using scanf is difficult and personally I don't use it over cin from C++, however both topics will be covered here. Cin will be covered first again due to simplicity.

#include <iostream>
using namespace std;

int main() {
  int x;
  cout << "Enter an integer: ";
    //endl not needed since cin will end it when the user
    //presses the enter key
  cin >> x; //Notice the opposite direction of the operator
  if (x < 0)
    cout << "You entered a negative integer!" << endl;
  return 0;
}

Cout uses the insertion operator <<, while cin uses the extraction operator, >>. Really these are operators like + or - in C++, but are used only with instances of classes (like cout and cin). The names for the operators come from the fact that in C++, cout and cin are streams, and the data is "inserted" to or "extracted" from the stream. However, in C the input is a little changed.

/* C-only Code */
#include <stdio.h>

int main() {
  int x; char f;
  printf("Enter an integer: ");
  scanf("%i", &x);
  if (x < 0)
    printf("You entered a negative integer!\n");
  return 0;
}

Notice that scanf, which reads data from the keyboard, is much like printf and needs format specifiers, which is why C input/output is harder than cin/cout with C++. Also notice the & in front of the variable name, which is NOT part of the name. What this does is send a pointer to the variable to the function so it can modify it. Pointers are an advanced topic and will be discussed in a much later section.

Multiple input can be entered on one line but it is not reccomended since it is confusing for the user, but in C++ the data should be entered with a space between each variable.

cout << "Enter two integers seperated by spaces: ";
cin >> x1 >> x2; //The user should enter something like 50 90

In C it gets a little more complicated:

printf("Enter two integers seperated by spaces: ");
scanf("%i %i", &x1, &x2);

Notice again how scanf works like printf.