Sie sind auf Seite 1von 21

C++ PROGRAMMING

BASIC TUTORIALS
TABLE OF CONTENTS

C++ Tutorials Description Page

• Introduction to C++ You will learn how to write your 1


very first program

• Variables You will learn what are Variables 2


and how to use them

• User Input This tutorial will teach you how to 3


let users interact with your program

• If Statements You will learn how to make decisions 4


based on the user input

• Loops In this tutorial you will learn about the 6


three different Loops and when to use them

• Intro to Functions This is going to teach what are functions 9


and how to use them

• I/O Stream with Example Learn how to read and write from files 10

• Arrays This tutorial will teach you about 13


Arrays and their advantages

• Structs You will learn about Structs 18

• Commands and Functions Some useful Commands and Functions 19


and their descriptions

No part of this book may be reproduced or copied in any form or by any means
without permission from Softnet ITC.
C++ PROGRAMMING 2

GOAL The purpose of this tutorial is to teach you how to write


your very first C++ Program: The Hello World.

The Hello World Program

#include <iostream.h>

int main()
{
// To print text to the screen you start by using cout,
// then you add <<, then you add ", then the text.
// after the text you put ", then <<, then endl;
// So the final line would look like
// cout<<"Hello World"<<endl;

cout<<"Hello World"<<endl;

// the endl means that it will end the line and


// go down to the next one.

return(0);
}

Printing Variables

List of Variables:
int
char
double
float

We will discuss about variables later on but for know lets see how to print them onto the screen.

#include <iostream.h>

int main()
{
int a = 1; //Declaring int a equal to 1
char b = a; //Declaring char b equal to a
double c = 1.3; //Declaring double b to equal 1.3
float d = 5353.733 //Declaring float d to equal 5353.733

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 3

//printing the variable on the screen


cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d;

return(0);
}

As you can see printing a variable is different than printing text. When printing a variable you
don't include " ".

But say you want to print text before the variable. What do you do?
This is also very simple you put cout, then <<"text”<<variable<<endl;
so then for your program you would do:

cout<<"This is an int: "<<a<<endl;


cout<<"This is a char: "<<b<<endl;
cout<<"This is a double: "<<c<<endl;
cout<<"This is a float: "<<d;

GOAL In this chapter you will learn what are Variables


and how to use them in your program.

What is a Variable?

A variable is a named memory location which stores a value. To use a variable in a program it
must be defined by giving its type and identifier. The type of the variable indicates what kind of
value it will store. The name of the variable, or identifier, is how the value will be referred to
within the program. For example:

double radius;

This example defines a variable named radius which stores data of type double. Once
defined, a variable must be given a value. One way of doing this is through assignment. For
example:

radius = 12.3

another way to do this is by allowing the user to enter in the value, for example you can use the
following code:

cin>>radius;

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 4

What can be done with Variables?

You can do a lot with variables such as: print them onto the screen and also +, / ,*, - with other
variables. For example if you have two int variables you can do

cout<<var1+var2;

List of Variables

Type Description Size Range


double real numbers, including decimals 8 bytes 1.7-308 to 1.7+308
long integers (no decimals) 8 bytes -2,147,483,647 to +2,147,483,647
float floating point numbers 4 bytes 3.4-38 to 3.4+38
int integers (no decimals) 4 bytes -32,767 to +32,767
bool boolean value 1 byte true or false
char characters 1 byte all typeable or displayable characters

Summary

You are now done with variables. I know this wasn't a big tutorial that's because variables are
such a small topic and you basically learn how to use as you continue to learn programming.

GOAL The purpose of this tutorial is to teach you how


to let the user interact with your program.

Your Program

In this tutorial you will create a simple program which will display the user with a statement:
"Enter any number:" then the user will be allowed to enter any number which they may
wish. After enter the number you will display another statement: "Your number was:"

Let’s Get Started

Here is the code:

#include <iostream.h>

int main()
{
int number;

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 5

cout<<"Enter any number: ";


cin>>number;
cout<<"Your Number Was: "<<number;

return(0);
}

There should be nothing really new here except: cin>>number. Well first what you are doing
is declaring a variable called number. Which is an int so it can only be a whole number? Then
you are displaying the text: "Enter any number".

Now for the new part, cin is the command used to allow the user to enter in data. As you can
notice the signs are pointing in the opposite direction >>. No, that is not a mistake. What you
are doing here is setting the variable number set equal to a different value which the user has
entered in.

Next you are only display text and the variable to the screen. This shouldn't be anything new to
you.

Summary

This was a really easy tutorial. In this tutorial you learned how to get user input by using the cin
command.

GOAL The goal of this tutorial is for you to know how


to use if statements in your programs.

if Statements

if statements allows a program to make decisions. For example:

if(temp<50)
cout<<"It's a nice day!"<<endl;

When the if statement executed the flow depends of the value of temp. If the value of temp is
less than 50 the program will then skip the cout statement. If the value of temp is greater than
50 then the program will display: "It's a nice day!".

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 6

Note

There are five different operators in addition to the < operator.

Operator Meaning
== equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
!= not equal to

if-else Statements

The if statement can include an else clause which is executed if the condition in the if
statement is false. For example:

if(temp<50)
cout<<"Its cold outside, wear a jacket."<<endl;
else
cout<<"It's nice outside."<<endl;

The first statement is only displayed if the value of temp is less than 50. The second
statement which is after the else is displayed when the value of temp is not less than 50.

Compound Statement

A compound statement is more than one statement that is enclosed by curly braces. For
example:

if(temp<50)
{
cout<<"Its cold outside, wear a jacket."<<endl;
cout<<"You can't manage without it."<<endl;
}
else
{
cout<<"It's nice outside."<<endl;
cout<<"You don't need a jacket."<<endl;
}

A compound statement can include as many statements as desired. The curly braces don't slow
down program execution and can be inserted even there is one statement.
Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 7

The else-if Ladder

The else-if ladder is a format which has been developed for writing if statements that are
used to decide among three, four, or more actions. For example:

if(temp<=32)
cout<<"It's cold!"<<endl;
else if(temp<=60)
cout<<"It’s cool!"<<endl;
else if(temp<=80)
cout<<"It’s hot!"<<endl;
else
cout<<"It’s very hot!"<<endl;

GOAL In this tutorial you will learn about the 3 different loops and how
to use each one. The three loops are: do-while, while, and for.

Looping

Program flow can be controlled through iteration which means to repeat one or more statements
during program execution. Iteration is often referred to as looping.

do-while Loop

The first of three loops is the do-while which has the form:

do
{
statement;
} while(condition);

where statement is one or more c++ statements that form the body of the loop. The condition is
an expression used to determine in the loop is to be repeated. The do-while loop is executed
at least once because the condition is not evaluated until after the first iteration of the loop. If the
condition is true, statement is executed again and then the condition reevaluated. This looping
process is repeated until the condition is evaluated and found to be false.

#include <iostream.h>

int main()
{
char answer;

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 8

do
{
double pi = 3.14;
double radius;

cout<<"Enter the radius: ";


cin>>radius;
cout<<"Area is: "<<(pi * radius * radius)<<endl<<endl;

cout<<"Do you want to do another one (y/n)? “;


cin>>answer;
} while(answer == 'y');

return(0);
}

pi and radius are declared within the loop body which means they are accessible by the
statement in the loop only. The variable answer is accessed by the while condition outside the
loop and therefore must be declared outside the loop body. Declaring answer in the loop body
will lead to an "Undefined symbol" compilation error.

while Loop

The do-while loop is always executed at least once because its condition is not evaluated until
after an iteration. A second looping statement is the while loop which evaluates its condition
before each iteration. Therefore, the while loop body may execute zero or more times. The
while loop has the form:

while(condition)
{
statement;
}

where statement is one or more c++ statements that form the body of the loop. The condition is
an expression used to determine if the loop is to be executed. If the condition is true, statement
is executed and then the condition reevaluated. This looping process is repeated until the
condition is evaluated and found to be false.

#include <iostream.h>

int main()
{
int number;

cout<<"Enter a positive number: ";


Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 9

cin>>number;
while(number < 0)
{
cout<<"Number must be positive."<<endl;
cout<<"Please re-enter: ";
cin>>number;
}

return(0);
}

for Loop

The third looping statement is the for loop which is generally used to execute a loop body a
fixed number of times. The for loop has the form:

for(initialization; condition; increment)


{
statement;
}

The initialization is performed only once when the for loop is first executed. The condition is
an expression evaluated before each iteration of the loop body. Statement may be a single
statement or a compound statement executed only when condition is true. The increment is
performed after each iteration of the loop body, and usually advances a counter. Any of these
can be left out by leaving the semicolons as markers.

#include <iostream.h>

int main()
{
for (int x =1; x<=10; x++)
{
cout<<x<<endl;
}

return(0);
}

Summary

In this tutorial you have the 3 loops in c++: for, do-while, and while. You also learned
how these loops are used and also how they run.

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 10

FUNCTIONS

This is our function called HelloWorld(). This will be called by the main() function.
Remember that main() is required because the program will need to know which function will
be executed first. You can have as many functions as you want in your program. A function can
be named anything you would like. Here is our function...

#include<iostream.h>

void HelloWorld()
{
// All our function will be doing is printing out this line
cout<<"Hello World!"<<endl;
}

// Our main function that is required in every C/C++ program.


int main()
{
// In order to execute our new function we must call it
HelloWorld();

return(0);
}

And that’s all there is to it. The function called HelloWorld() will do all the work that this
tutorial will need to do. If you was to type HelloWorld() again under the first one, the
function will run again. So you can call multiple functions multiple times.

Another way to do this is:

#include<iostream.h>

void HelloWorld();

int main()
{
HelloWorld();

return(0);
}

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

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 11

In this example you changed only two things. You put your HelloWorld() function at the
end of your program and you put a declaration of the function above your main.

I/O STREAM

C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the
header file fstream.h. ifstream handles file input (reading from files), and ofstream
handles file output (writing to files). The way to declare an instance of the ifstream or
ofstream class is:

ifstream a_file;
//or
ifstream a_file("filename");

The constructor for both classes will actually open the file if you pass the name as an argument.
As well, both classes have an open command (a_file.open()) and a close command
(a_file.close()). It is generally a good idea to clean up after yourself and close files once
you are finished.

The beauty of the C++ method of handling files rests in the simplicity of the actual functions
used in basic input and output operations. Because C++ supports overloading operators, it is
possible to use << and >> in front of the instance of the class as if it were cout or cin.

For example:

#include <fstream.h>
#include <iostream.h>

int main()
{
char str[10]; //Used later
//Creates an instance of ofstream, and opens example.txt
ofstream a_file("example.txt");

//Outputs to example.txt through a_file


a_file<<"This text will now be inside of example.txt";

a_file.close(); //Closes up the file

//Opens for reading the file


ifstream b_file("example.txt");

b_file>>str; //Reads one string from the file

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 12

cout<<str; //Should output 'this'


b_file.close(); //Do not forget this!

return 0;
}

The default mode for opening a file with ofstream's constructor is to create it if it does not
exist, or delete everything in it if something does exist in it. If necessary, you can give a second
argument that specifies how the file should be handled. They are listed below:

ios::app Opens the file, and allows additions at the end


ios::ate Opens the file, but allows additions anywhere
ios::trunk Deletes everything in the file
ios::nocreate Does not open if the file must be created
ios::noreplace Does not open if the file already exists

For example:

ifstream a_file("entry.txt", ios::nocreate);

The above code will only open the file entry.txt if that file does not already exist.

Here is one more example:

#include <process.h>
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>

char first1[10],
last1[20],
phone1[20],
add1[20],
city1[20],
state1[20],
code1[20];

ofstream outfile("entry.dat",ios::out);

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 13

int main()
{
//Makes a new entry
cout<<"Enter First Name: ";
char first1[20];
cin.getline(first1,20,'\n');

cout<<"Enter Last Name: ";


char last1[20];
cin.getline(last1,20,'\n');

cout<<"Enter Home Phone Number: ";


char phone1[20];
cin.getline(phone1,20,'\n');

cout<<"Enter Home Address: “;


char add1[20];
cin.getline(add1,20,'\n');

cout <<"Enter City: ";


char city1[20];
cin.getline(city1,20,'\n');

cout <<"Enter State: ";


char state1[20];
cin.getline(state1,20,'\n');

cout <<"Enter Postal Code: ";


char code1[20];
cin.getline(code1,20,'\n');
cout <<"Press Any Key To Save";
getchar();

//writes to file
outfile <<"FirstName: " << first1 << endl;
outfile <<"LastName: " << last1 << endl;
outfile <<"HomePhone: " << phone1 << endl;
outfile <<"Address: " << add1 << endl;
outfile <<"City: " << city1 <<endl;
outfile <<"State: " << state1 << endl;
outfile <<"PostalCode: " << code1 << endl;
outfile <<""<<endl;

return 0;
}

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 14

ARRAYS

Part One

Arrays allow you to store data items of a similar type. You can picture an array in the computer's
memory as a row of consecutive spaces, each of which can store a data item, known as an
ELEMENT.

Declaring Arrays

To declare an array you need to specify its data type, its name and, in most cases, its size. Make
sure the array has a valid name. Here's an example:

int arrayOfInts[5];

This reserves memory for an array that is to hold five integer values. The number of elements
should be enclosed in the square brackets. However, if you don't specify the number of elements,
when you initialize the array, the computer will work out how many elements it holds.

Initializing Arrays

You can assign values to the array in several ways. For example, if I wanted an array to hold the
numbers 1 through to 10, I could do either of these:

int arrayOfInts[10] = {1,2,3,4,5,6,7,8,9,10};

/* Assume that the array has been declared! */


arrayOfInts[0] = 1;
arrayOfInts[1] = 2;
arrayOfInts[2] = 3;
arrayOfInts[3] = 4;
arrayOfInts[4] = 5;
arrayOfInts[5] = 6;
arrayOfInts[6] = 7;
arrayOfInts[7] = 8;
arrayOfInts[8] = 9;
arrayOfInts[9] = 10;

/* an unsized array */
int arrayOfInts[] = {1,2,3,4,5,6,7,8,9,10};

int arrayOfInts[10];
int i;

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 15

for(i=0 ; i<10 ; i++)


arrayOfInts[i] = i + 1;

You may have noticed that the first element of an array is indexed 0 rather than 1. This is a
simple yet important idea you need to take into account. I mean, once you've initialized 10 or so
arrays it becomes a lesser problem!

Printing Out Arrays

One of the commonest ways to print out the contents of the array is to use a for loop like this:

#include <stdio.h>

main()
{
int anotherIntArray[5] = {1,2,3,4,5};
int i;

for(i=0 ; i<5 ; i++)


printf("anotherIntArray[%d] has a value of %d\n", i,
anotherIntArray[i]);

return 0;
}

Entering arrays elements can also be achieved:

#include <stdio.h>

main()
{
int anotherIntArray[5];
int i;

printf("Enter 5 integers one by one,


pressing return after each one:\n");

for(i=0 ; i<5 ; i++)


scanf("%d", &anotherIntArray[i]);

for(i=0 ; i<5 ; i++)


printf("anotherIntArray[%d] has a value of %d\n", i,
anotherIntArray[i]);

return 0;
}
Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 16

Character Arrays

So far I've included examples of arrays of integers - probably the one I've been using the most.
You can use arrays for floats and doubles as well as chars. Each element of the array can
hold one character. But if you end the array with the NULL CHARACTER, denoted by \0 (that
is, backslash and zero), you'll have what is known as a STRING CONSTANT. The null
character marks the end of a string - useful for functions like printf. Time for an example…

#include <stdio.h>

main()
{
char charArray[8] = {'F','r','i','e','n','d','s','/0'};
int i;

for(i=0 ; i<8 ; i++)


printf("charArray[%d] has a value of %c\n",
i, charArray[i]);

/* Alternative way */
printf("My favorite comedy is %s\n", charArray);

return 0;
}

Notice that I enclosed each of the characters with single quote marks - double quote marks are
reserved for strings. I also used the character and string format specifiers (%c and %s
respectively).

Warning: Stupid person I am. I accidentally used the wrong slash symbol for the null character
with the above example!! I've learned my lesson now.

Multidimensional Arrays

So far, I've been giving you examples which contain one dimensional arrays. But sometimes,
using multidimensional arrays is more convenient, like when using coordinates for example.
This might sound silly, but I'm just going to focus on 2D arrays for now.

You already know how to declare a 1D array, but what about 2D? Simple. Take this example:

int array2D[3][5];

This tells the computer to reserve enough memory space for an array with 15, that is, 3 x 5
elements.

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 17

One way to picture these 15 elements is an array with 3 rows and 5 columns.

But there are times when you don't know the size, so you'd want to use an unsized array.

However, you must specify every dimension size except the left one. Like this:

int array2D[][5];

Initialization

Methods used are similar to those of the 1D arrays:

#include <stdio.h>

void main()
{
int first[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

/* a clearer definition than the first */


int second[3][4] = {0, 1, 2, 3,
4, 5, 6, 7,
8, 9,10,11};

int third[][5] = {0,1,2,3,4};

int fourth[][6] = {0,1,2,3,4,5,6,7,8,9,10,11};

int i,j;

int fifth[5][4];

for(i=0 ; i<5 ; i++)


{
for(j=0 ; j<4 ; j++)
fifth[i][j] = i * 4 + j;
}

int sixth[2][6];

for(i=0 ; i<2 ; i++)


{
printf("Enter 6 integers separated by spaces: ");

for(j=0 ; j<6 ; j++)


scanf("%d" , &sixth[i][j]);

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 18

printf("\n");
}

int seventh[2][3];

seventh[0][0] = 0;
seventh[0][1] = 1;
seventh[0][2] = 2;
seventh[1][0] = 3;
seventh[1][1] = 4;
seventh[1][2] = 5;
}

For loops are dead handy. And not just for initialization - they are commonly used for printing
out arrays. I tend to iterate the rows in the first loop, then the columns. Whichever way round
you chose, keep it consistent!

Array Sizes

If you ever wanted to find out how much memory your arrays (1D or multidimensional), you can
use the sizeof operator like this:

#include <stdio.h>

void main()
{
char arrayChar[] = {'A','r','r','a','y','\0'};

int arrayInt[5] = {1,2,4,8,16};

float arrayFloat[3] = { 1.24 , 2 , 4.68756 };

double arrayDouble[2];

arrayDouble[0] = 23.23456532;
arrayDouble[1] = 2.3422267;

int arrayInt2D[][4] = {1,6,3,7,


6,3,8,9,
2,5,2,3};

printf("The size of arrayChar[] is %d\n",


sizeof(arrayChar));
printf("The size of arrayInt[] is %d\n", sizeof(arrayInt));
printf("The size of arrayFloat[] is %d\n",
sizeof(arrayFloat));
Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 19

/* Alternative way */

printf("The size of arrayDouble[] is %d\n",


sizeof(double) * 2);
printf("The size of arrayInt2D[] is %d\n",
sizeof(arrayInt2D));
}

Most of the time I stick the array name in between the brackets of the sizeof operator.

GOAL The goal of this tutorial is for you


to learn what is a Struct and how to use them.

Let’s Get Started

A struct is a user-defined type that is in a simpler form of a class. A struct type is often created
so that related data can be stored in one structure. A struct can store many values of different
types. For example, rather than storing the data about a person in separate variables, a struct can
be used to create a type that allows all the data to be stored under one identifier, for example:

struct Person
{
char first[10];
char last[10];
int age;
};

Note: There must be a semicolon at the end of the type definition.

A struct type must be defined before any functions that uses it. Most people place struct types
before any function definitions.

The Person struct has 3 data members which could be accessed using dot notation. For example:

Person myFriend;
cout<<"Enter First Name: ";
cin>>myFriend.first;

What your doing is declaring a struct myFriend of the type Person and you ask the user
for the value to assign to the first data member of Person.

As you will see in this example a struct can be passed in as a parameter.

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 20

#include <iostream.h>

struct Person
{
char first[10];
char last[10];
int age;
};

void getPersonInfo(Person &myFriend);

int main()
{
Person myFriend;
getPersonInfo(myFriend);

return(0);
}

void getPersonInfo(Person &myFriend)


{
cout<<"Enter First Name: ";
cin >> myFriend.first;
cout<<"Enter Last Name: ";
cin >> myFriend.last;
cout<<"Enter Age: ";
cin >> myFriend.age;
}

SOME USEFUL COMMANDS AND FUNCTIONS

Command/Function Description Header File

cout<<data outputs data on the screen iostream.h


cin>>variable inputs data to the variable specified iostream.h
strlen(string) calculates the length of a string string.h
strupr(string) converts lowercase letters in a string to uppercase
string.h
strlwr(string) converts uppercase letters in a string to lowercase
string.h
clrscr() clears the text-mode window conio.h
gotoxy(x,y) positions cursor to the specified x and y point conio.h
random(int) random number generator stdlib.h

Reference Book
Softnet I.T. Center
All Rights Reserved
C++ PROGRAMMING 21

randomize() initializes the random number generator with a random


value stdlib.h

Reference Book
Softnet I.T. Center
All Rights Reserved

Das könnte Ihnen auch gefallen