Welcome to your

WORKING PROGRAMs FOR DEV-C++ COMPILER

//Welcome1.cpp

#include <iostream>

using namespace std;

int main( )

{

cout << "Welcome to C++ World" << endl;

system("pause" );

return 0;

 }

// Sum.cpp

#include <stdlib.h>  

#include <iostream>

using namespace std;

int main()

{

    int integer1, integer2, sum;

    cout << "Enter an integer\n";

    cin >> integer1;

    cout << "Enter another integer\n";

    cin >> integer2;

    sum = integer1 + integer2;

    cout<< "The sum of the two integers is -- "<< sum <<endl;

    system("pause");

return 0;

}

 

//First Star Program

#include <iostream>

#include <stdlib.h>

using namespace std;

int main()

{   cout<<"*\n**\n***\n****\n*****\n******\n*******\n******\n*****\n****\n***\n**\n*\n";   

      system("pause");

return 0;

} 

 

Topic 1 : Basics

C++ Reserved Keywords

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t

Additionally, alternative representations for some operators do not have to be used as identifiers since they are reserved words under some circumstances:

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Escape Codes

\n

newline

\r

carriage return

\t

tabulation

\v

vertical tabulation

\b

backspace

\f

page feed

\a

alert (beep)

\'

single quotes (')

\"

double quotes (")

\?

question (?)

\\

inverted slash (\)

-------------------------------------------------

C++  DATA TYPES

Name

Bytes*

Description

Range*

char

1

character or integer 8 bits length.

signed: -128 to 127
unsigned: 0 to 255

short

2

integer 16 bits length.

signed: -32768 to 32767
unsigned: 0 to 65535

long

4

integer 32 bits length.

signed:-2147483648 to 2147483647
unsigned: 0 to 4294967295

int

*

Integer. Its length traditionally depends on the length of the system's Word type, thus in MSDOS it is 16 bits long, whereas in 32 bit systems (like Windows 9x/2000/NT and systems that work under protected mode in x86 systems) it is 32 bits long (4 bytes).

See short, long

float

4

floating point number.

3.4e + / - 38 (7 digits)

double

8

double precision floating point number.

1.7e + / - 308 (15 digits)

long double

10

long double precision floating point number.

1.2e + / - 4932 (19 digits)

bool

1

Boolean value. It can take one of two values: true or false NOTE: this is a type recently added by the ANSI-C++ standard. Not all compilers support it. Consult section bool type for compatibility information.

true or false

----------------------------------------------------------

Topic 2 : Hello World of C++

Becoming a C++ Programmer

 

--------------------------------------------------------

Topic 3: Simple Programs.

The problem

Write a program which prints a message on the screen asking the user to type in their age in years. When the user does this, the program is to calculate the approximate number of days old the user is and print this value on the screen.

Analysis

An analysis of the problem contains a statement of its essential input, output, process and any assumptions we make about it. In this case we can say:

Design

The design of the solution is best expressed as an algorithm which sets out the sequential steps the program will follow:

Begin
  print a message saying "How old are you in years?"
  get the user's age in years from the keyboard
  multiply the age by 365
  print the number of days on the screen
End

Data

The data of the program is how the program stores the values used in the calculations. In this case we will need to store two things:

Writing the source code

A C++ program which solves this problem is presented below. You should type this program, exactly as it is written here, into your editor.

 

 Sample Program

// A first program. Calculates the user's age in days
#include <iostream> 
int main(  ) {
  int years, days;
  cout << "How old are you in years? ";
  cin >> years;
  days = years * 365;
  cout << "Your age in days is about " << days << endl;}
 

Explanations of the lines in this topic's program.
You can jump to the specific explanation for any given line in the program by clicking on that line in the program.

Lines 1,2,3

These are introductory comments. Comments start with // and are not executed in the finished program. Every program should start with some explanatory comments.

Line 4

This instruction tells the compiler to read the file called iostream before processing any other statements. The iostream  file comes packaged with every C++ compiler and contains definitions of commonly used Input and Output (I/O) facilities.

Line 5

This is heading of the main function of our program. Every C++ program must have a main function. 

Line 6

The left brace {, marks the beginning of the body of our program.

Line 7

The two words "years" and "days" are variables. That is, they are containers of data. In C++ variables should always be given meaningful names. The term "int" written before the two variables tell the compiler that the variables are intended to hold whole numbers (integers).

Line 8

The word "cout" is a built-in object which is connected to your computer's screen. It means "console-out". The << symbol indicates that the message in quotation marks "How old are you in years? " should be sent to the console (the screen).

Line 9

The word "cin" is a built-in object which is connected to your computer's keyboard. It means "console-in". The " >> years " means that when the user types their age, its value will be stored in the variable years.

Line 10

This is a calculation. The value stored in the variable years is multiplied by 365 and the result is copied into the variable days.

Line 11

Here the message "Age in days is about" is sent to the screen via the cout object, then the value of the variable days is sent to the screen, and finally the endl symbol (meaning end-line) moves the cursor down to the next line on the screen.

Line 12

The closing brace }, marks the end of the body of the program.

Note that the whole source code is written in lower case. Lower case is the 'standard' in C++. You can use upper case or a mixture of cases if you like but the compiler will be case sensitive. Also, note that every line inside the body of the program is terminated with a semicolon (;), this is compulsory. You can have blank lines anywhere you like and they are recommended for presentation and readability purposes.

You should save the source code to disk. You should use a filename like FIRST.CPP. The CPP suffix identifies the file as a CPlusPlus file.

Compiling the program

Using your compiler package, compile the program. If there are error messages it is probably because you have mistyped something, so go back and edit the source code and compile again. When you write your own programs you will get plenty of error messages from the compiler. At first these seem too numerous and too complex to fix but as you progress you will learn to appreciate how the compiler detects syntax errors for you. A general word of advice is to fix the first error only and then compile again. This is usually effective because each error can cause a number of subsequent errors. Fixing the first error often removes many others.

In many modern PC based compiler packages, the linker is invoked automatically when you compile. In others, the linker activates when you choose the command "Make" or "Build". Sometimes the linker is called only when you want to run the program.

Running the Program

Run the program using a command provided by your compiler package. The running program should generate an interactive session which looks like this:

     How old are you in years? 31
     Age in days is about 11315

Here, the 31 shown above in bold face represents the age the user typed in. You may actually have entered a different age. Note the user must press the Enter key after typing their age.

If you have followed the steps above you should have achieved a breakthrough. You have successfully written, compiled and run your first program. All the rest of the work in this course is intended to allow you to continue to design, write and execute simple programs and to learn how to write simple programs in C++ as you go.

As you continue with the course you should also seek out small example problems from a text book and try to solve them. Remember, programming is 90% perspiration , so you must practice as you go.

The sample program I have provided uses simple sequential actions to do its tasks. All programs contain sets of sequential actions and, although it is fairly obvious, the computer will execute the sequential statements in the order you have provided them. That is, it works from the first action (or statement) down to the last, one after the other.

Equipped with this concept and some examples of standard input and output you should be able to write many programs which read and process data interactively (with the user).

The problems provided in the task below require this kind of interaction and they can be solved with short, straightforward sequential actions and simple variables. So, please try to do them now.

----------------------------------------------

Hand-in Programs to Write

  1.  Write a program which allows the user to enter the length of a square and which uses this number to calculate and display the area of the square.

 

  1. Write a program which accepts an amount of money from the user which represents the amount tendered for a purchase. Also, allow the user to enter the cost of the item being purchased. The program should calculate the change due and print this amount. The following could be used as sample output from your program:
  Enter the amount tendered: 20.00
         Enter the cost of the item: 16.95
          The change due is: 3.05

 

------------------------------------------------------

/

 Topic 4 :Making decisions                                         

You can write programs which make decisions by using the two words if and else in your programs. This topic introduces you to this form of decision making which is known as binary selection .

Binary selection, as the name implies, is always a choice of two alternatives. Which one is executed depends on whether a condition is met or not. It is one of the most frequently used structures in programming and a sound understanding of it is essential.

Example Problem

Here is a simple problem which needs a binary selection:

Write a program which allows the user to enter the number of hours they have worked during the past week. The program uses the number of hours to decide whether or not the person will be paid for overtime or not and prints a suitable message in each case. Let's assume that 40 hours per week is a standard load and anything over 40 hours will imply that overtime is necessary.

Solution

The program will look like this: (go ahead and type it, compile it and run it)

// Sample binary selection program

#include <iostream>
int main( ) 
  cout << "How many hours did you work? ";
{
  int hours;
  cin >> hours;
 if( hours > 40 )
    cout << "You will be paid for overtime" << endl;
  else
    cout << "Sorry, no overtime this week" << endl;
}

Notice that the binary selection is simply done by using an if/else statement. The message "You will be paid for overtime" is said to be in the true branch of the if/else structure because it's done when the condition ( hours > 40 ) is true. The message "Sorry, no overtime this week" is in the false branch.

Important notes

There are some important variations of the if/else structure that you must be aware of.

1. The else part is not always necessary.

Sometimes you want to do an action if a condition is true but not do anything special if the condition is false. Like this:

if( hours > 40 )
  cout << "You will be paid for overtime work" << endl;
cout << "Have a nice day" << endl;

In this case, the message "Have a nice day" will be displayed no matter how many hours were worked.

The message "You will be paid for overtime work" will only be displayed if the hours are more than 40.

Workers who worked more than 40 hours will therefore see both messages.

2. The word "then" is not used in C++.

In many other programming languages the binary selection structure uses the keywords if, then and else. If you have written programs in BASIC or Pascal then you might be tempted to put the word "then" into your programs - don't.

3. The examples above both have only one action in each of the branches of the selection.

Sometimes, we need to do more than one action in each branch. Like this:

if( hours > 40 )
{
 cout << "You will be paid for overtime" << endl;
  cout << "Aren't you lucky!" << endl;
}
else
{
  cout << "Sorry, no overtime this week" << endl;
  cout << "Maybe you'll get some next week" << endl;
}

When more than one action needs to be done in a branch of the if/else structure, we must use a pair of braces {} to group those actions together.

4. The brackets () after the word if, are compulsory.

Hand-in Programs to Write :

 3. Write a program which allows the user to enter their age. The program should then print either "You are still young" or "You are getting old" depending on whether the person's age is greater than 100 or not.

4. Write a program in which the user enters their salary. The program is to calculate and display the amount of tax payable on this salary. Use the (simple) tax rule: Salaries under $4000 pay 2% tax, salaries of $4000 or more pay 25% tax .

------------------------------------------------------

 

Topic 5: More about selection.

Nested Selection

If you have to decide between more than two alternatives, you can use more than one binary selection and nest one of these inside another. Here is an example in which a person's age is entered and used to select one of three appropriate messages.

#include <iostream>
int main( )
{
  int age;
  cout << "Enter your age ";
  cin >> age;
  if( age < 13 )
    cout << "You aren't even a teenager yet." << endl;
  else
    if( age < 60 )
      cout << "You are still young." << endl;
    else
      cout << "You are past middle age." << endl;
}

There is an if/else structure here which separates those people who are less than 13 years old from those who are 13 or over. Those who are less than 13 get the "teenager" message.

Those who are 13 or over are then further divided into two groups by the second if/else structure. Note that the (age < 60) selection is nested inside the else branch of the (age < 13) selection.

Careful use of indenting can help lead the reader's eye to which structure is nested within which. This is particularly important when the nesting of if/else structures becomes more complex.

Finally, here is a fragment of code which shows nesting at a deeper level.

if( condition )
  if( another condition )
    do action 1
  else
    do action 2
else
  if( yet another condition)
    do action 3
  else
    do action 4

Logical operators.

The conditions you've seen so far in the examples have used the greater than symbol (>) or the less than symbol (<). Here is a list of the various logical operators you can use in conditions with if statements:

Compound conditions.

The logical conditions you've seen so far have all used very simple boolean expressions (a boolean expression is one which has a value of either True or False). You can do more complex tests by combining expressions using and and or symbols. In C++, the symbol for and is && . The symbol for or is || .

Examples

Suppose we have a person's age in the variable age , and their height in the variable height . Here are some logical expresssions we could use:

age > 100 && height < 60

A person who is really old and very short. Example: someone who is 120 years old and is 40cm tall.

age < 5 || height < 60

A person who is either very young or very short. Example: someone who is 4 years old no matter how tall or short, or someone of any age who is 50cm tall.

height >= 170 && height <= 250

People who are in the height range 170 to 250 inclusive

age < 18 || age > 75

People who don't have to vote.

height < 160 || height > 100

Everyone!

age < 10 && age > 30

No-one!

 HAND-IN PROGRAMS TO WRITE:

5.)    Write a program which asks the user for their salary and their age. If the person is over 75, increase their salary by $10 for each year of age. Otherwise, increase their salary by $5 for each year of age. Print the new salary in either case.

 

6.    Write a program in which the user can enter two numbers (integers). If both numbers are zero then print the message "Two zeros". If the numbers are not both zero, then print either "FIRST" or "SECOND" depending on which number is bigger. If the numbers are the same (but not both zero) then print "EQUAL".

------------------------------------------------------------

Topic 6: Going Loopy.

Computer programs can be written to do a set of actions over and over. They do this by using loops.

There are three kinds of loops which can be used in C++ but I will emphasize one of these here and put the other two in later topics.

All loops must have a starting position, an ending position and something to do over and over. Let's start with an example problem.

Example

Write a program which uses a loop to print onto the screen all the odd numbers from 17 to 25 inclusive.

// Sample loop program

 
#include <iostream>
int main()
{
  int counter;
  counter = 17;           // Starting position
  while( counter <= 25 )  // Condition
  {
    // body of loop
    cout << "The counter is " << counter << endl;
    counter = counter + 2; //   SeeNote on incrementing variables
  }
  cout << "The loop is finished" << endl; 
}

The loop that I've used here is a pretested loop. The C++ keyword for pretested loops is while.

The line

  counter = 17;

has initialized the variable counter to 17. This is the starting position for our loop and matches the requirements of the question.

The next line

  while( counter <= 25 )

uses the keyword while at the top of the loop. The word while is followed by a condition which indicates that the actions inside the loop will execute "while" that condition is true. That is, while the variable counter is less than or equal to 25.

 

Incrementing Variables

**  counter = counter + 2; actually increments the variable counter by two. 
This statement can be interpreted as "take the current value of counter, 
increase it by 2, then copy the result back into counter". Similarly, we could write: 
  counter = counter + 1;

to increase the counter variable by 1, however, in C++, the shorthand expression

  counter++;

does this for us.

 

The body of the loop (the code inside the loop) is executed over and over again. Note that the statement

  counter = counter + 2;

actually increases the value of the counter variable by two each time it executes. So, eventually the counter will be bigger than 25 and when that happens the condition will become false. This causes the loop to stop repeating.

The statement

  cout << "The loop is finished" << endl; 

will execute only once - after the loop has finished.

You should type this program into your editor, compile it and run it.

Now, make a number of experimental modifications to the program which make it print out a different sequence of numbers. For example, you could change the starting value to something else or change the condition so that it is strictly less than 25 instead of less than or equal. You can also change the incrementing statement so that the loop iterates in steps other than 2. With a number of combinations of these changes you will get a variety of outputs and this should allow you to get used to how the loop operates.

Notes:

  1. It is most important that you get good at checking the first few iterations and the last few iterations of any loop you design, otherwise the loop may start or stop at the wrong place. Errors in loops usually occur at the beginning or ending of the loop often causing "off by one" errors.
  2. A while loop is called a pre-tested loop because the test or condition is checked before any of the statements inside the loop body are executed. This means that if the condition is false the first time it is checked, then the statements in the loop body will never be done. Here is an example:
3.               int counter = 10;
4.               while( counter > 20 )
5.               {
6.                 cout << "You won't ever see this message!" << endl;
7.                 counter++; // Note on incrementing variables
8.               }

Since the counter is initially 10, the condition (counter > 20) is initially false and the loop body is never executed.

  1. The line
10.            counter = counter + 2;

actually increments the variable counter by two. This statement can be interpreted as "take the current value of counter, increase it by 2, then copy the result back into counter".

Similarly, we could write:

  counter = counter + 1;

to increase the counter variable by 1, however, in C++, the shorthand expression

  counter++;

does this for us.

 

Write These Programs and Hand In

7)       Write a program which uses a while loop to print the numbers from 200 to 1200 inclusive, on the screen.

 

8)       Write a program which prints the multiples of 5 from 5 to 100. That is,

   5
  10
  15
  ... etc

 

--------------------------------------------

Topic 7: Combining Structures

Every program from the simplest one to the program that manages a space shuttle is a combination of the control structures like the ones you have studied here.

You should consider the control structures of sequence , selection, and iteration  as being the building blocks of programs. These building blocks can be combined in a number of ways including placing them after each other in sequence and/or nesting one structure inside another.

As an example, a very typical combination is an if/else inside a while loop. In this situation, data is read, one item at a time using the loop, like this:

// Combining selection and iteration
#include <iostream >
int main()
{
  int number;


  cout << "Enter a number ";


  cin >> number;                // Note 1


  while( number != 999 )
  {

    cout << "You entered " << number << endl;


   cout << "Enter a number ";
    cin >> number;             // Note 2
  }
}

Then, inside the loop we nest an if/else structure so the program becomes:

// Combining selection and iteration
#include <iostream>
int main(  )
{

  int number;
  cout << "Enter a number ";

  cin >> number;

  while( number != 999 )

  {

    cout << "You entered " << number << endl;


    if( number % 2 == 0 )     // Note 3

      cout << "which is even" << endl;

    else

      cout << "which is odd" << endl;


    cout << "Enter a number ";


    cin >> number;


  }

}


Although this example is small, it has the same structure as many 
common data processing applications.

Program formatting.--When your programs include a number of control structures it is easy for them to look messy. The mess doesn't matter to the compiler but it certainly does matter to a reader of your program (this is often just you, but you will appreciate readability too). It is important that you use indentation and spacing to help the reader see what statements belong to what structure - for example, which of the following is the more readable?

Version 1.

#include <iostream > int main( ) { int number; cout <<
"Enter a number "; cin >> number; while( number != 999 )
{ cout << "You entered " << number << endl;
if( number % 2 == 0 ) cout << "which is even" <<
endl; else cout << "which is odd" << endl;
cout << "Enter a number "; cin >> number; } }

or

Version 2.

#include <iostream >
int main( )
{

  int number;


  cout << "Enter a number ";


  cin >> number;


  while( number != 999 )

  {

    cout << "You entered " << number << endl;


    if( number % 2 == 0 )


     cout << "which is even" << endl;


   else

      cout << "which is odd" << endl;

      cout << "Enter a number ";

    cin >> number;
  }
}

Both versions compile and run correctly but if they didn't, 
which would you rather fix?

Notes:

Note 1.

In an interactive loop such as this one, we read data before the while loop performs its first test. If we did not do this, we would not have a reliable test. Reading data before starting a loop is called a Priming Read.

Note 2.

This read statement occurs as the last action in the body of the loop. It is used to load the variable used in the loop test with new data. If we forgot this reading statement, we could not get out of the loop because the variable used in the test would not change. This kind of reading statement is often called a Follow-Up Read

Note 3.

The % as used in the expression num % 2 is called a modulus operator. It gives the remainder (only) after dividing. It is used here to determine if the remainder when dividing by 2 is 0 or 1, thus indicating that num is even or odd respectively.

Write this Program

Program #9 - - - Write a program which allows the user to enter a number of pollution readings (integers). As each pollution reading is entered the program should test the reading and print one of the following messages:

The program should stop when the user enters any negative pollution reading.

----------------------------------

Topic # 8    Even More Loopy

The do-while loop

Its format is:

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

// number echoer


 
#include <iostream>

using namespace std;


 
int main ()

{

  unsigned long n;

  do {

    cout << "Enter number (0 to end): ";

    cin >> n;

    cout << "You entered: " << n << "\n";

  } while (n != 0);

  return 0;

}

Enter number (0 to end): 12345

You entered: 12345

Enter number (0 to end): 160277

You entered: 160277

Enter number (0 to end): 0

You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.

Write this Program:

Make up your own looping program:

#10  using the 'do-while' control statement

 

The for loop

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.

It works in the following way:

1.   initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.

2.   condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).

3.   statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.

4.   finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:

// countdown using a for loop

#include <iostream>

using namespace std;

int main ()

{

  for (int n=10; n>0; n--) {

    cout << n << ", ";

  }

  cout << "FIRE!\n";

  return 0;

}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:

for ( n=0, i=100 ; n!=i ; n++, i-- )

{

   // whatever here...

}

This loop will execute for 50 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

Write this Program:

Make up your own looping program:

#11  using the 'for' control statement

Congratulations, you have mastered the basics of C++, (we hope.)

 

Back to Home Page