C-PROGRAM
THE ORIGIN OF C++
The C programming language was developed at AT&T for the purpose of writing the operating system for the PDP-11 series of computers which ultimately became the UNIX operating system. C was developed with the primary goal of operating efficiency. Bjarne Stroustrup, also of AT&T, developed C++ in order to add object-oriented constructs to the C language. Because object-oriented technology was new at the time and all existing implementations of object-oriented languages were very slow and inefficient, the primary goal of C++ was to maintain the efficiency of C.
C++ can be viewed as a traditional procedural language with some additional constructs. Beginning with C, some constructs are added for object-oriented programming and some for improved procedural syntax. A well-written C++ program will reflect elements of both object-oriented programming style and classic procedural programming. C++ is actually an extendible language since we can define new types in such a way that they act just like the predefined types which are part of the standard language. C++ is designed for large scale software development.
C++ syntax
By definition, syntax is the rules governing the formation of statements in a programming language. In other words, it is the specific language (code) you use to turn algorithms into programs and specific rules you have to follow when programming with C++. As you will find out, if you make one small mistake when writing code, the compiler will notify you of the syntax error when you try to run it. C++, like all languages, is very picky when it comes to syntax. Let’s look at a simple example program written in C++.
For now, notice how each executable statement in the program is ended with a semi-colon. Every executable statement must always be terminated with a semi-colon, which signals that it is the end of the statement. Any code placed after // will not affect the code; // is used for comments and documentation. Also notice that text is always enclosed in parentheses. Let’s dig deep into the code to find out why you need to use certain code statements.
- cout – console output – It is simply letting the compiler know that something is being sent into the output stream (normally the screen).
- << – insertion operator – cout and the insertion operator go hand in hand; you must use it whenever you issue a cout command.
- cin – console input – It is simply letting the compiler know that something is being sent into the input stream (normally into the memory of a computer).
- >> – extraction operator – cin and the extraction operator go hand in hand; you must use it whenever you issue a cin command.
- endl – end line – basically the same as pressing the return key in a text editor; returns down to the next line.
Lexical Conventions
Introduces the fundamental elements of a C++ program as they are meaningful to the compiler and are used to construct statements, definitions, declarations, and so on, which are used to construct complete programs.
The fundamental elements of a C++ program are called “lexical elements” or “tokens” to construct statements, definitions, declarations, and so on, which are used to construct complete programs. The following lexical elements are discussed in this chapter:
1. Tokens
A token is the smallest element of a C++ program that is meaningful to the compiler. The C++ parser recognizes these kinds of tokens: Identifiers, Keywords, Literals, Operators, Punctuators, and Other Separators. A stream of these tokens makes up a translation unit.
2. Comments
A comment is text that the compiler ignores but that is useful for programmers. Comments are normally used to annotate code for future reference.
A C++ comment is written in one of the following ways:
- The
/*(slash, asterisk) characters, followed by any sequence of characters (including new lines), followed by the*/characters. - The
//(two slashes) characters, followed by any sequence of characters. A new line not immediately preceded by a backslash terminates this form of comment. Therefore, it is commonly called a “single-line comment.”
Example:
/*This is an example of comments in a program */
File Name = String(“hello.day”); // Initialize file string
3. Identifiers
An identifier is a sequence of characters used to denote one of the following:
- Object or variable name
- Class, structure, or union name
- Enumerated type name
- Member of a class, structure, union, or enumeration
- Function or class-member function
- typedef name
- Label name
The first character of an identifier must be an alphabetic character, either uppercase or lowercase, or an underscore (_). Because C++ identifiers are case sensitive, fileName is different from FileName.
4. C++ keywords
Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program.
The following keywords are reserved for C++:
5. Punctuators
Punctuators in C++ have syntactic and semantic meaning to the compiler but do not, of themselves, specify an operation that yields a value. Some punctuators, either alone or in combination, can also be C++ operators or be significant to the preprocessor. The punctuators are:
! % ^ & * ( ) – + = { } | ~ [ ] ‘ : ” << >> ? , . / #
The punctuators [ ], ( ), and { } must appear in pairs.
6. Operators
An operator is a symbol that causes specific mathematical or logical manipulations to be performed. A combination of constants and variables together with the operators is called an expression. An expression that involves only constants is called a constant expression. An expression that involves only arithmetic operators is called an arithmetic expression.
Eight types of operators:
- Arithmetic Operators
- + Addition
- – Subtraction
- * Multiplication
- / Division
- % Modulo Division
- Relational operators: used to make comparisons
- < less than
- > greater than
- <= Less than or equal to
- >= greater than or equal to
- == Equal to
- != not equal to
- Logical operators: logical operators && and || are used when more than one condition is to be tested to make decisions
- && AND
- || OR
- ! NOT
- Assignment operators
- = equal to
- C supports a set of shorthand assignment operators, e.g., +=, -=, *=, /= etc.
- A = A + 1 equals A += 1
- S = S * (k + p) equals S *= (k + p)
- Increment or Decrement Operators
- ++ increment
- — Decrement
- Prefix operator: first adds one to the operand and stores the result to the variable on the left. Suffix operator: first assigns value to the variable on the left and then increments the operand.
- Conditional Operator
A ternary operator “?:” is available in C to construct conditional expressions of the form:
exp1 ? exp2 : exp3;
- Bitwise operators
- & Bitwise and
- | Bitwise or
- ^ Bitwise Ex-Or
- << Shift Left
- >> Shift Right
- ~ Complement
- Special Operators
C++ supports some special operators such as comma (,), size-of operator (determines the length of arrays and structures), pointer operator (*), and member selection operators ( . and → ).
Comma operators are used to link related expressions together. A comma-linked list of expressions is evaluated left to right. The value of the rightmost expression is the value of the combined expression.
Example: value = (x = 10, y = 5, x + y);
Then value will be equal to the result of the last expression, i.e., 15.
Types
C++ supports three kinds of object types:
- Fundamental types are built into the language (such as int, float, or double). Instances of these fundamental types are often called “variables”.
- Derived types are new types derived from built-in types.
- Class types are new types created by combining existing types.
Fundamental Types of the C++ Language
| Category | Type | Contents |
|---|---|---|
| Integral | char | Type char is an integral type that usually contains members of the execution character set — in Microsoft C++, this is ASCII. The C++ compiler treats variables of type char, signed char, and unsigned char as having different types. Variables of type char are promoted to int as if they are type signed char by default, unless the /J compilation option is used. In this case, they are treated as type unsigned char and are promoted to int without sign extension. |
| short | Type short int (or simply short) is an integral type that is larger than or equal to the size of type char, and shorter than or equal to the size of type int. Objects of type short can be declared as signed short or unsigned short. Signed short is a synonym for short. | |
| int | Type int is an integral type that is larger than or equal to the size of type short int, and shorter than or equal to the size of type long. Objects of type int can be declared as signed int or unsigned int. Signed int is a synonym for int. | |
| Long | Type long (or long int) is an integral type that is larger than or equal to the size of type int. Objects of type long can be declared as signed long or unsigned long. Signed long is a synonym for long. | |
| Floating | float | Type float is the smallest floating type. |
| double | Type double is a floating type that is larger than or equal to type float, but shorter than or equal to the size of type long double. | |
| long double | Type long double is a floating type that is equal to type double. |
Sizes of Fundamental Types
| Type | Size |
|---|---|
| char, unsigned char, signed char | 1 byte |
| short, unsigned short | 2 bytes |
| int, unsigned int | 4 bytes |
| long, unsigned long | 4 bytes |
| float | 4 bytes |
| double | 8 bytes |
| long double | 8 bytes |
OOPS
Object-oriented programming is known as OOPs.
OOP is a method of implementation in which programs are organized as co-operative collections of objects, each of which represents an instance of some class and whose classes are all members of a hierarchy of classes united through the property called inheritance.
Three important concepts about OOP are objects, classes and inheritance.
Structured Programming views the two core elements – Data & Functions as two separate entities. Object-oriented programming views them as a single entity. OOP is a new way of solving problems with computers. OOP languages provide the programmer the ability to create class hierarchies, instantiate co-operative objects collectively working on a problem to produce the solution and send messages between objects to process themselves.
The fundamental features of the OOPs are the following:
- Encapsulation
- Data Abstraction
- Inheritance
- Polymorphism
- Message Passing
Encapsulation:
A mechanism that associates the code and the data it manipulates into a single unit and keeps them safe from external interference and misuse.
Data Abstraction:
The technique of creating new data types that is well suited to an application to be programmed. It provides the ability to create user-defined data types, for modeling a real-world object, having the properties of built-in data types and a set of permitted operators.
Inheritance:
It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes (derived classes) from the existing ones (base classes), thus enabling the creation of a hierarchy of classes that simulate the class and subclass concept of the real world. The new derived class inherits the members of the base class and also adds its own.
Polymorphism:
It allows a single name/operator to be associated with different operations depending on the type of data passed to it. In C++ it is achieved by function overloading, operator overloading, and dynamic binding (virtual functions).
Message Passing:
The process of invoking an operation on an object. In response to a message, the corresponding method (function) is executed in the object.
OBJECTS
An object can be a person, a place, or a thing with which the computer must deal. Some objects may correspond to real-world entities such as students, employees, bank accounts, inventory items, etc. Every object will have data structures called attributes and behavior called operations.
Consider the object having the attributes: Account Number, Account type, Name, Balance and Operations: Deposit, Withdraw, Inquire.
CLASSES
The objects with the same data structure (attributes) and behavior (operations) are grouped into a class. All those objects possessing similar properties are grouped into the same unit.
Every object is associated with data and functions which define meaningful operations on that object. Related objects exhibiting the same behavior are grouped and represented by class as shown below:
Control Structures
Controlling the flow of a program is a very important aspect of programming. There may be many different ways to find the solution to a particular problem, but you will want to look for the best and fastest way. C++ has four types of control structures: sequential, selection (decision), repetition (loops), and subprograms (functions). These structures simply control the execution of a program.
Sequential
Sequential means the program flow moves from one statement to the next, that statement moves to the next, and so on. It is the simplest form of structures, and it is not likely to use sequential structuring when developing complex programs.
Selection (decision)
Selection structures make decisions and perform commands according to the decision making. Selection structures involve “if statements” which are statements like “if this, then do that” and “if not this, then do that”. With “if statements”, we can also include “nested if statements”, which are “if statements” inside other “if statements”. Another form of selection structures is called a “switch statement”, which is very powerful for certain situations but not others. “Switch statements” focus on the value of a particular variable and perform different “cases” accordingly.
Repetition (Loops)
Repetition structures are used when something needs to be repeated a certain number of times through the use of “loops”. A loop is simply a statement that completes iterations or cycles until a certain value is reached and then execution moves to the next executable statement. For instance, if you were to ask the user to enter ten values to find the average of the numbers, you could write a loop that would continue letting the user enter numbers until ten numbers had been entered.
Subprograms (functions)
A function is a subprogram that performs a specific task and may return a value to the statement that called or invoked it. Functions make programming very powerful because once you develop a function to handle a particular situation, you can use that function for other programs. A function can call another function, which may call another function, and so on. It is a great way to organize your program and break your program down into logical steps.
After a very brief intro to the different types of control structures, it’s time to move on and find out how you can use each type. We will skip over sequential structures since they are pretty much self-explanatory and elementary and move on to selection statements. Read on for more about selection structures and “if statements”…
Selection Statements
When dealing with selection statements, there are generally three versions: one-way, two-way, and multi-way. One-way decision statements do some particular thing or they don’t. Two-way decision statements do one thing or do another. Multi-way decision statements can do many different things depending on the value of an expression.
One-Way Decisions
One-way decisions are handled with an “if statement” and either do some particular thing or do nothing at all. The decision is based on a logical expression which either evaluates to true or false. If the logical expression is evaluated to true, then the corresponding statement is executed; if the logical expression evaluates to false, control goes to the next executable statement. The form of a one-way decision statement is as follows:
if (logical expression) stmtT;
The stmtT can be a simple or compound statement. Simple involves 1 single statement. Compound involves 1 or more statements enclosed with curly braces { }. A compound statement is called a block statement.
Example 1: simple statement
int c = 3;if (c > 0) cout << "c = " << c << endl;
Example 2: compound statement
int c = 10;if (c > 5){ b = 2 * b + c; cout << c * c * b << endl;}Two-Way Decisions
Two-way decisions are handled with “if / else statements” and either do one particular thing or do another. Similar to one-way decisions, the decision is based on a logical expression. If the expression is true, stmtT will be executed; if the expression is false, stmtF will be executed. The form of a two-way decision is as follows:
if (logical expression) stmtT;else stmtF;
stmtT and stmtF can be simple or compound statements. Remember that compound statements are always enclosed with curly braces { }.
Multi-Way Decisions
Multi-way decision statements involve using “if / else if” statements, “nested ifs”, or “switch” statements. They are all used to evaluate a logical expression that could have several possible values. “if / else if” statements are often used to choose between ranges of values.
The form of a multi-way decision using “if / else if” statements is as follows:
if (logical expression) stmtT1;else if (logical expression) stmtT2;else if (logical expression) stmtT3;...else if (logical expression) stmtTN;else stmtF;
If the first logical expression is evaluated to true, then stmtT1 is executed. If the second logical expression is true, then stmtT2 is executed and so on down the line. If none of the logical expressions are true, then the statement after “else” is executed which is stmtF.
The form of a multi-way decision using “nested ifs” is as follows:
if (condition A){ if (condition B) stmtBT; else stmtBF;}else stmtAF;If condition A is evaluated to true, then execution moves into the nested if and evaluates condition B. If condition A is evaluated to false, then stmtAF is executed.
Example 1:
int x;if (x > 0) cout << "x is positive" << endl;else if (x == 0) cout << "x is zero" << endl;else cout << "x is negative" << endl;
Example 2:
char ch;if ((ch >= 'A' && ch = 'a' && ch <= 'z')) cout << "ch contains a letter" <= '0' && ch <= '9') cout << "ch represents a digit" << endl;else if (ch == ' ' || ch == 't' || ch == 'n') cout << "ch is white space" << endl;else cout << "ch is a misc. character" << endl;
Switch Statements
A switch statement is yet another option for writing code that deals with multi-way decisions. I saved it for a section by itself because some programmers feel using a switch statement is not good programming style. With 1 semester of programming under my belt and a few years of fooling around with different programming languages, I haven’t encountered any problems with using a switch statement. I haven’t written too many programs using switch statements, but when I have, the programs have seemed to run smoothly. Maybe I’ll see why programmers don’t like to use switch statements in later programming experiences. For now, let’s explore the ins and outs of a switch statement.
Switch statements offer an alternative to an “else if” structure which has multiple possible paths based on the value of a single expression. A revised form for a switch statement is as follows:
switch (int expression){ case label-1: stmt-list-1; break; case label-2: stmt-list-2; break; case label-3: stmt-list-3; break; ... case label-n: stmt-list-n; break; default: stmt-list;}During execution, the expression is evaluated. If the value of the expression matches label-1, then stmt-list-1 (and perhaps all lists below) will be executed. If not, execution will move on to check label-2 and so on. If no labels match the expression, default will be executed. Inside each case and at the end of every statement list (except default) there must be a break statement, which terminates the innermost enclosing switch or loop statement (not recommended with loops).
Here are some final notes about switch statements: the expression being tested must result in an integral value (int or single char), case labels must be integral constants (either literals or named constants), each label within a switch should be unique, and each stmt-list may contain 0 or more stmts which do not need to be enclosed with curly braces { }.
Example:
Suppose a variable named score is an int variable that contains the number of points scored on a football play. Consider the following code:
switch (score){ case 1: cout << "Extra Point" << endl; break; case 2: cout << "Safety or two point conversion" << endl; break; case 3: cout << "Field Goal" << endl; break; case 6: cout << "Touchdown" << endl; break; default: cout << "Invalid score on a football play." << endl;}With selection statements out of the way, it’s time to talk about iteration (or looping) in a program. This, of course, involves using loop statements. Read on to explore the world of looping…
While Loops
A loop is a statement of code that does something over and over again until the logical expression of the loop evaluates to false. It is simply a way of repeating code over and over again until some particular value is reached. It can also be an effective way of making sure the user is inputting the correct type of input (data validation).
A loop is different from an if statement in that if the logical expression is true, the stmt will be executed and control will go back to check the logical expression again, …, and again, until eventually the logical expression becomes false.
One thing to avoid is writing code that produces an infinite loop, which is a loop that never stops until you press Ctrl-Break on your keyboard. In order to avoid infinite loops, you need a statement(s) inside the body of the loop that changes some part of the logical expression. We will talk about three types of loops: while, do while, and for.
The form of a while loop is as follows:
while (logical expression) stmt;
Example 1:
int x = 7;while (x > 0){ cout << x << endl; x--;}Example 2 using data validation:
Suppose the user of a program is to input an integer in the range -10 to 10 (inclusive). Using data validation, write a section of code to input this value:
int k;k = -99;while (k 10){ cout <> k;}Example 3:
Write a section of code that will display all multiples of 5 that are less than 500.
int x = 5;while (x < 500){ cout << x << endl; x = x + 5;}That wraps up all I have to say about while loops so let’s move on to the next loop of interest. Read on for more about do while loops…
Do While Loops
A do while loop is another type of repetition statement. It is exactly the same as the while loop except it does something and then evaluates the logical expression of the loop to determine what happens next. Normally with a while loop, a part of the logical expression in the loop must be initialized before execution of the loop. A do while loop lets something be performed and then checks the logical expression of the loop. I like to use a do while loop when using data validation during a program. The form of a do while loop is as follows:
do stmt(s);while (logical expression);
The stmt in the loop may be single or complex. Complex statements must be enclosed with curly braces { }. Let’s look at a couple of examples of do while loops.
Example 1:
int number;do{ cout <> number;}while (number <= 0 || int(number) != number);Example 2:
int number;do{ cout <> number;}while (number = 100);Having discussed while and do while loops, there is one more loop I would like to cover: for loops. Read on for more about for loops…
For Loops
A for loop is another way to perform something that needs to be repeated in C++ (repetition). Most programmers like to use for loops because the code can be written in a more compact manner compared to the same loop written with a while or do while loop. A for loop is also important to understand because they are used when dealing with arrays and other topics in C++ [for info on arrays see One-Dimensional Arrays (section 8) and Two-Dimensional Arrays (section 8)]. A for loop is generally used when you know exactly how many times a section of code needs to be repeated. The general form of a for loop is as follows:
for (expression1; expression2; expression3) stmt(s);
where stmt(s) is a single or compound statement. Expression1 is used to initialize the loop; expression2 is used to determine whether or not the loop will continue; expression3 is evaluated at the end of each iteration or cycle.
NOTE 1: expression2 is tested before the stmt and expression3 are executed; it is possible that the body of the loop is never executed or tested.
NOTE 2: Any or all of the 3 expressions in a for loop can be omitted, but the 2 semi-colons must remain. If expression1 is omitted, there is no initialization done in the loop, but you might not need any initialization for your program. If expression2 is omitted, there is no test section so you will essentially have an infinite loop. If expression3 is omitted, there is no update as part of the for statement, but the update could be done as part of the statement in the body of the loop.
In general, a for loop can be written as an equivalent while loop and vice versa.
for (expression1; expression2; expression3) stmt; is equivalent to...expression1;while (expression2){ stmt(s); expression3;}Example 1:
Write a for loop that will display all odd integers between 1 and 51:
for (int k = 1; k <= 51; k += 2) cout << k << endl;
Example 2:
Write a for loop that will display a “countdown” of integers from 20 to 1:
for (int k = 20; k >= 1; k--) cout << k << endl;
Structures
Before discussing classes, this portion will be an introduction to data structures similar to classes. Structures are a way of storing many different variables of different types under the same name. This makes it a more modular program, which is easier to modify because its design makes things more compact. It is also useful for databases.
The format for declaring a structure (in C++, it is different in C) is:
structure NAME{ VARIABLES;};Where NAME is the name of the entire type of structure. To actually create a single structure the syntax is NAME name_of_single_structure; To access a variable of the structure it goes name_of_single_structure.name_of_variable;
For example:
structure example{ int x;};example an_example; // Treating it like a normal variable typean_example.x = 33; // How to access itHere is an example program:
structure database{ int id_number; int age; float salary;};int main(){ database employee; // There is now an employee variable that has modifiable // variables inside it. employee.age = 22; employee.id_number = 1; employee.salary = 12000.21; return 0;}The structure database declares that database has three variables in it: age, id_number, and salary.
You can use database like a variable type like int. You can create an employee with the database type as I did above. Then, to modify it you call everything with the ’employee.’ in front of it. You can also return structures from functions by defining their return type as a structure type. Example:
structure database fn();
I suppose I should explain unions a little bit. They are like structures except that all the variables share the same memory. When a union is declared the compiler allocates enough memory for the largest data-type in the union. It’s like a giant storage chest where you can store one large item, or a bunch of small items, but never both at the same time.
The ‘.’ operator is used to access different variables inside a union also.
As a final note, if you wish to have a pointer to a structure, to actually access the information stored inside the structure that is pointed to, you use the -> operator in place of the . operator.
A quick example:
#includestructure example{ int x;};int main(){ example structure; example *ptr; structure.x = 12; ptr = &structure; // Yes, you need the & when dealing with structures and using pointers to them cout << ptr->x; // The -> acts somewhat like the * when used with pointers // It says, get whatever is at that memory address // Not "get what that memory address is" return 0;}
Array basics
Arrays are useful critters because they can be used in many ways. For example, a tic-tac-toe board can be held in an array. Arrays are essentially a way to store many values under the same name. You can make an array out of any data-type including structures and classes.
Think about arrays like this:
[][][][][][]
Each of the bracket pairs is a slot (element) in the array, and you can put information into each one of them. It is almost like having a group of variables side by side.
Let’s look at the syntax for declaring an array.
int example_array[100]; This declares an array.
This would make an integer array with 100 slots, or places to store values (also called elements). To access a specific part element of the array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The one trick is that the first index number, and thus the first element, is zero, and the last is the number of elements minus one. 0-99 in a 100 element array, for example.
char string[100];
will allow you to declare a char array of 100 elements, or slots. Then you can receive input into it from the user, and if the user types in a long string, it will go in the array. The neat thing is that it is very easy to work with strings in this way, and there is even a header file called string.h. There is another lesson on the uses of string.h, so it’s not necessary to discuss here.
The most useful aspect of arrays is multidimensional arrays.
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]
This is a graphic of what a two-dimensional array looks like when I visualize it.
For example:
int two_dimension_array[8][8];
Declares an array that has two dimensions. Think of it as a chessboard. You can easily use this to store information about some kind of game or to write something like tic-tac-toe. To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot. You can even make a three-dimensional array, though you probably won’t need to. In fact, you could make a four-hundred dimensional array. It would be confusing to visualize, however.
Arrays are treated like any other variable in most ways. You can modify one value in it by putting:
array_name[array_index_number] = whatever; or, for two-dimensional arrays
array_name[array_index_number1][array_index_number2] = whatever;
However, you should never attempt to write data past the last element of the array, such as when you have a 10 element array, and you try to write to the 11th element. The memory for the array that was allocated for it will only be ten locations in memory, but the twelfth could be anything, which could crash your computer.
#include
int main(){ int x, y, an_array[8][8]; // declares an array like a chessboard for (x = 0; x < 8; x++) { for (y = 0; y < 8; y++) { an_array[x][y] = 0; // sets the element to zero; after the loop all elements == 0 } } for (x = 0; x < 8; x++) { for (y = 0; y < 8; y++) { cout << "an_array[" << x << "][" << y << "]=" << an_array[x][y] << endl; } } return 0;}Here you see that the loops work well because they increment the variable for you, and you only need to increment by one. It’s the easiest loop to read, and you access the entire array.
One thing that arrays don’t require that other variables do, is a reference operator when you want to have a pointer to the string. For example:
char *ptr;char str[40];ptr = str; // gives the memory address without a reference operator (&)
As opposed to:
int *ptr;int num;ptr = # // Requires & to give the memory address to the ptr

