Worksheet 3rd grade C++

Preview:

Citation preview

CHAPTER I

INTRODUCTION TO

PROGRAMMING LANGUAGES

UNA SANA COLLEGE 2012

What is a software (a program)?

It is a set of instructions (orders, commands, statements) which tells the computer what to do and how to do.

UNA SANA COLLEGE 2012

People who make computer programs are called programmers.

People who use the programs are called end-users.

Functions of a computer program

A computer program (software) contains a sequence of instructions for a computer. One program is usually composed of three parts: Input part gets the data from an input device. Our programs which we will do in our practice times, will get the data from keyboard or from a text file. Process part is the hardest working part of the program. It carries out the algorithm and finds out the desired result. Output part gives the result of the program. Our programs will display the result on the screen or print it into a text file.

UNA SANA COLLEGE 2012

INPUT OUTPUT PROCESSING or PROCESS

What is a programming language?

It is a program to write computer programs. C, C++, Pascal, Fortran, Basic, Cobol, Virtual Basic are

example of programming language.

UNA SANA COLLEGE 2012

Steps to make a program

• Understanding the problem

• Designing an algorithm

Algorithm – is a kind of process that connects inputs and outputs

• Implementation

• Testing and Debugging

UNA SANA COLLEGE 2012

Type of the programming language

i ) low – level programming languages

• Machine language

• Assemble language

ii ) high – level programming languages

e.g.: Pascal, C, Fortran

UNA SANA COLLEGE 2012

Low – level languages

it is a machine – oriented language.

A low-level language is not user-friendly, that is, makes it hard for the user to understand the structure of the program.

UNA SANA COLLEGE 2012

i) Machine language

ii) Assembly language

Machine languages are the only languages understood by the computers directly. While easily understood by computers, machine languages are almost impossible for humans to use because they consist entirely of numbers. Each type of CPU has its own machine language and assembly language, so an assembly language program written for one type of CPU won't run on another. Machine language performs much faster.

Assembly language is the other most-common low-level language. Assembly languages are similar to machine languages, but they are much easier to program in because they allow a programmer to use some written syntax rather than numbers.

UNA SANA COLLEGE 2012

High-level language

A high-level language it is a problem-oriented programming language. Pascal, C/C++, BASIC, COBOL, Fortran, etc.. are examples of high-level programming languages. High-level languages are more understandable to the programmer and are fairly easy to learn.

UNA SANA COLLEGE 2012

Which language is best? The question of which language is best is not have one answer. Every language has its strengths and weaknesses. • FORTRAN was the first widespread language. It is a particularly good language for processing numerical data, but it is not useful to write large programs. • COBOL is used for commercial applications that require precise and efficient manipulation of large amounts of data. Much business software is still programmed in COBOL. • Pascal is very good for writing well-structured and readable programs and to teach good programming techniques , but it is not as flexible as the C programming language. • C++ embodies powerful object-oriented features, but it is complex and difficult to learn. • Assembly program is very suitable when speed is essential. • Basic or Pascal will be good chose if you start learning programming because of their easy learn structures. • Java was originally designed to work on network and to control electronic devices on the network. • C is a good choice for programming Operating Systems. • Visual Basic, visual C++ and Delphi have GUI design elements and so are better suited for this type of task. • C++ is a general purpose language beside this there are some tasks that can be done in C++ but not very easily, for example designing GUI screens for applications.

UNA SANA COLLEGE 2012

What are compiler, interpreter, and assembler?

Regardless of what language you use, because machine language is only program that computer can understand directly you eventually need to convert (translate) your program into machine language so that the computer can understand it. If your program is written in any high- level language there are two ways to do this:

• compile the program by compiler.

• interpret the program by interpreter.

If your program is written in assembly language you can do:

• assemble the program with assembler.

UNA SANA COLLEGE 2012

Interpreters and Compilers Every high-level language has its own source which needs to be translated into the CPU's language - machine code. These translators are referred to as interpreters and compilers. A high-level language package contains either an interpreter, or a compiler, with which a high-level language uses to translate the source code into object code. An interpreter is more slower than a compiler, the fact that it has to be loaded into memory till the end of the translation of the program. It is less practical than the compiler. However, the interpreter can be helpful for correcting out errors in programs i.e. it is ideal for debugging. A compiler is faster due to its single, complete translation of the program into object code. A compiler, compiles the source code (with no syntax errors) and makes a copy of it. This copy is called the 'object code'. After it has been compiled, it does not need a recompilation (unless the source code is changed and a recompilation is required to affect the change). The object code used by the OS in order to execute the compiled program.

UNA SANA COLLEGE 2012

Examples for languages:

0010111110 0001000011

1111001010

0101010101

UNA SANA COLLEGE 2012

load 5

add 4

store C

program add;

begin

c:=5+4;

end.

Machine language

Assembly language

Pascal Language

If you write a program to add the number 5 and the number 4 in machine, assembly and Pascal language typical program codes will be following:

C++ Language

int main()

{

c=5+4;

}

Comparison of the machine language and high – level language

Here are two programs which accomplish the same thing. The first is in ML, and the second is in BASIC. They get results at very different speeds indeed, as you'll see: Machine Language 169 1 160 0 153 0 128 153 0 129 153 130 153 0 131 200 208 241 96 BASIC 5 FOR I=1 TO 1000: PRINT "A";: NEXT I These two programs both print the letter "A" 1000 times on the screen. The ML version takes up 28 bytes of Random Access Memory (RAM). The BASIC version takes up 45 bytes and takes about 30 times as long to finish the job.

UNA SANA COLLEGE 2012

ADVANTAGES OF

LOW – LEVEL LANGUAGE HIGH – LEVEL LANGUAGE

1. It occupies less space in memory.

2. It performs (runs) very fast.

3. Because it is only program that

computer can understand directly,

it doesn’t require any compiler

program.

1. It is easier to learn and closer to

human language.

2. It is easier to analyze to be partially

rewritten or updated to conform to

changing conditions.

3. It is simpler to debug to get all the

mistakes and problems ironed out.

Even it tell you your programming

mistakes by displaying error

mistakes by displaying error

messages on the screen while you

are typing your program.

4. It removes the programmer from

having to know the details of the

internal structure of a particular

computer.

UNA SANA COLLEGE 2012

What is C++? C++ is an ordinary high-level language which is widely used to writing programs. C++ is a general purpose programming language invented in the early 1980s by Bjarne Stroustrup at Bell Labs. It is similar to C, invented in the early 1970s by Dennis Ritchie using the UNIX operating system, but includes essential programming techniques such as object oriented programming. C is a structured language like Pascal. The most distinguishing feature of a structured language is that it uses blocks. A block is a set of statements that are logically connected. C++ is an expanded and enhanced version of C.

UNA SANA COLLEGE 2012

Java, C# and C++

UNA SANA COLLEGE 2012

Java was developed by Sun Microsystems and C# was made by Microsoft. C++ is the parent for both Java and C#. This means that once you know C++, you can easily learn Java or C#. The reverse case is also true. If you know Java or C#, learning C++ is easy.

The main difference between C++, Java, and C# is the type of computing environment for which each is designed. C++ was designed to produce high-performance programs for a specific type of CPU and operating system. For example, if you want to write a high-performance program that runs on an Intel Pentium under the Windows operating system, then C++ is the best language to use.

Java, C# and C++

UNA SANA COLLEGE 2012

Java and C# were developed in response to the unique programming needs of the highly distributed networked environment that typifies much of contemporary computing. Java was designed to enable the creation of cross-platform portable code for the Internet. Using Java, it is possible to write a program that runs in a wide variety of environments, on a wide range of operating systems and CPUs.

Thus, a Java program can move about freely on the Internet. C# was designed for Microsoft’s .NET Framework, which supports mixed-language, component-based code that works in a networked environment. Java programs execute slower than do C++ programs. The same is true for C#. Thus, if you want to write high-performance software, use C++. If you need to make highly portable software, use Java or C#.

CHAPTER II

Your first C++ program

Basic elements of C++

• Semantics - is a vocabulary of commands that humans can understand and that can be converted into machine language, fairly easily • Syntax - This is a language structure (or grammar) that allows humans to combine these C++ commands into a program that actually does something Think of the semantics as the building blocks of your C++ program and the syntax as the correct way to put them together.

What is a C++ program?

A C++ program is a text file containing a sequence of C++ commands put together according to the laws of C++ grammar. This text file is known as the source file (probably because it’s the source of all frustration). A C++ source file carries the extension. CPP just as a Microsoft Word file ends in .DOC The point of programming in C++ is to write a sequence of commands that can be converted into a machine-language program that actually does what we want done.

Writing your first C++ program 1. Click Start➪Programs➪Bloodshed Dev-C++➪Dev-C++ to start up the Dev-C++ tool. 2. Choose File➪New➪Source File. 3. Enter the following program exactly as written.

Notice: Don’t worry too much about indentation or spacing — it isn’t critical. C++ is case sensitive, however, so you need to make sure everything is lowercase.

4. Choose Save As under the File menu. Then type in the program name and press Enter.

Breaking a Text into Multiple Lines

Use end of line "endl" or new line '\n' characters with in a cout statement to make a new line. '\n' characters are inherited from C programming. We prefer to use "endl" notation.

Sample program codes Screen Output

Building your program

To build your Conversion.cpp program, you choose Execute➪Compile from the menu or press Ctrl+F9 — or you can even click that cute little icon with four colored squares on the menu bar In response, Dev-C++ opens a compiling window

To execute the Conversion program, click Execute➪Run or press Ctrl+F10. Or All in one you can Compile and Run at the same time clicking on icon or press F9

Output Operation

The output command in C++ is

• cout cout is a predefined identifier that stands for console output, which most generally refers to the computer’s screen.

Output Operation

Using cout function

When using ‘cout’, you must type in any message (text information) between the double quotes " ".

cout << " Hello world!"

But you can type numbers and any arithmetical or logical expression without double quotes " ".

cout << 3; cout << -5; cout << 3+5; cout << 3-5;

3 -5 8 -2

Sample program

codes Screen Output

Hello world!

Output Operation Using cout function

Any number value which you are not going to planning to use them in calculations, can be typed between double quotes " ".

cout << 3; cout << -3; cout << " -5 "; cout << " 3+5 "; cout << " 3-5= ";

3 -3 -5 3+5 3-5=

Sample program

codes Screen Output

Output Operation

An example

The program below shows the result of the expression 5 + 3.

Sample program codes

Screen Output

Output Operation Practice: Breaking a Text into Multiple Lines Use end of line "endl" or new line '\n' characters with in a cout statement to make a new line. '\n' characters are inherited from C programming. We prefer to use "endl" notation.

Sample program codes Screen Output

new line with \n

Output Operation

Formatting output in “cout” function

For formatting output to the screen you can use formatting keys (also called escape keys or backslash keys) . This table provides a summary of the escape characters you can use.

Output Operation

Formatting output in cout function For example if you entered the following code in properly you will see something similar to the image shown on the right hand side and hear a beep sound.

You will hear a beep sound.

Practice: • Make a program that displays the following output?

• Make a program that displays a picture of a

house that looks like the following figure?

C++ LAB WORK

Data types

Numerical values

Any number which can be used in

mathematical calculations.

Alpha-numerical values

Characters (any single letter, numbers, symbols), text

(strings), and any number which can not be used in mathematical calculations or any number will

not be used in calculations.

VARIABLES What is variable?

Variables are the reserved placed in the RAM to stores temporarily values during the execution of the commands in a running program.

Every variable has three properties: I. Name of the variable (identifier of the variable) II. Type of the variable III. Value of the variable.

I - Name of the variable

• You can give any name to your variable only by considering the naming rules of the identifiers.

• Give variables meaningful names, which will help to make the program easier to read and follow. This simplifies the task of error correction.

• Identifiers can be from one to several characters long. The first 1024 characters will be significant.

• Variable names may start with any letter of the alphabet or with an underscore. Next may be either a letter, a digit, or an underscore. The underscore can be used to enhance the readability of a variable name, as in first_name. Don’t use space for this purpose.

• Uppercase and lowercase are different; that is, to C++, number1 and Number1 can be used as the separate names.

• You cannot use any of the C++ keywords as identifier names. Also, you should not use the name of any standard function, such as abs, for an identifier.

Naming Rules

II - Type of the variable

1. Integer variables store whole numbers (-4, 3, 51, etc). Unsigned integer type variables cannot have negative values, whereas other integer type variables (signed integers) may have negative and positive values.

2. Floating-point variables store decimal numbers (3.5, -5,123, 4.0, etc).

3. Logical variables store the result of logical expressions and get only the values true and false. False is represented with 0 and true is represented with 1 in C++. Logical expressions are usually used in decision and repetition structures to control the flow of the program.

II - Type of the variable

4. Character variables are used to store characters (any single letter, number, punctuation character, etc). Characters are enclosed with a pair of single quotes in C++, like 'a', 'B', '7', '+', etc.

5. String variables are used to store text longer than one characters. Strings are enclosed with a pair of double quotes in C++, like " Hello world ", "College", etc.

and

III - Value of the variable: Variables according to their type can get any values in the ranges which is listed in the following table.

Classify each of the following according to the four

basic data types: Answer key:

Practice

34.276

-37

H

<

dd

5.09E+27

0

0.0

34.276 float

-37 integer

H character

< character

dd string

5.09E+27 float

0 logical

(bool) or integer

0.0 float

Using Variables in C++

To use variables in C++ you should i. Declare the variables ii. Assign values to the variables and

initialize them.

• To define or identify the name and type of the variables is called declaration of the variables.

• Some declarations are shown here, for example:

• int A;

• int B,C;

• char ch, chr ;

• float f, balance;

• double d;

I - Declaration of the Variables

II – Assigning values

To give values to decelerated variables are called assigning values. In C++,

we use equal sign as the assignment operator =.

In a C++ program, you can declare your variables where you want.

Using the variables

II – Assigning values

int A; float B; char C; string D; A= 9; B=3.3; C= '$'; D='' College '';

When assigning values to char variables, enclose

inside single quotes ( ' ' ). When assigning values to string variables, enclose inside double

quotes ( '' '' ).

Using the variables

II - Initialize and assign values to the variables

To give any value to a variable is called assigning value. Giving the initial value (first value) to the variable is called

initialization. Actually initializing look very much declaration. Initializing is the first assignment and it should done during

the declaration. Initializing is optional if you want you can assign a value later

to a variable any where in your program codes. But declaration should done before assignment.

Using the variables

The following statements demonstrates how to declare type and name of a variable and than to initialize it.

II - Initialize and assign values to the variables

Using the variables

int A; A=3;

Name of

the

variable is

A.

Type of

the

variable

is int.

Initial value

of A is 3.

Initialization of Variables

In C++, You can declare and initialize at the same time.

int A=3;

Name of the

variable is A. Type of

the

variable

is int. Initial value of

A is 3.

Using the variables

int A; A=3;

int A=3; =

Initialization of Variables

You can mix declaration (definition) and initialization;

int A=3, B, C=5;

Using the variables

At the same time you can declare (define) more variables;

int A, B, C;

You can declare (define) just before calculation;

int A,B; A=3; B=2; int C=A+B;

Variables Using the variables

When you declare (define) variables, complier reserve space in RAM memory depending on the type of the variable.

If you look at the table you can see how many bytes space you need for a specific variable.

But size of the variables can change depending on the complier and the computer you are using.

Variables Using the variables

int A, B, C; A=3; B=5; C=A+B;

Complier reserves 2 bytes space for each integer variables in RAM

Values of A,B,C is stored in RAM temporarily

Determining the size of the variable types on your computer

Using the variables

The sizes of variables might be different from those shown in the table, depending on the compiler and the computer you are using.

Use sizeof() operator to find out the sizes of variable types in your system.

The sizeof() operator returns the number of bytes in variable or type.

Determining the size of the variable types on your computer

Using the variables

Determining the size of the variable types on your computer

Using constants

Like variables, constants are data storage locations. Unlike variables, constants don't change.

You must initialize a constant when you declare (define) it, and you cannot assign a new value later.

Most of the common constants have already been defined in C++.

For the user defined constants, there are two main techniques used to define constant values.

Constants

Using constants

i. using the define keyword #include <iostream> #define PI 3.14 ….. ii. using the const keyword … int main() {… const float PI= 3.14;

….}

User defined constants

Using constants

In this method, constant is declared and initialized inside the main program block.

1st METHOD

Using constants

In this method, constant is declared and initialized header part of the program.

2nd METHOD

Getting Data from the User (Input) • Programs usually read the input data from the

standard input (keyboard) or from an input file.

• "cin" command is used to read data from the standard input.

Input Operation

The input commands in C++ is

• cin >> ……;

Input Operation

Syntax of cin

When using cin, you must identify variable or a list of variables next to the extraction (>>) operator.

cin >> variable;

Input Operation

• The first statement declares a variable of type int called a, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable.

• cin can only process the input from the keyboard once the enter key has been pressed.

• Extraction (getting data) from cin will not be done until the user presses enter key after the typing completed.

Input Operation

Using cin

is equivalent to

Input Operation

Using cin

A sample program codes • The following program reads two integers, calculates their sum and then outputs the

result.

Input Operation

Using cin

Typical screen

As seen on the typical screen outputs, cin extract (get in) data after pressing ENTER key and every cin extraction stops reading as soon as if finds any blank space character.

• The following program also reads two integers, calculates their sum and then outputs the result.

• int num1, num2, sum; declares three variables.

• The names of the variables are num1, num2 and sum.

• A variable is a named storage location that can contain data that can be modified during program execution.

• This declaration specifies that those variables can contain integer values (-45, 0, 11, 37, etc.). "num1" and "num2" will be used to store the input data, and "sum" will be used to keep the sum of input values in the program.

• Besides the program codes, the program has some comments.

• C++ has two ways to insert comments into source code: Single line comment and multiple line comment.

• Single line comments are written behind the double slash characters ("//") and multiple line comments are enclosed between slash and asterisk ("/*") and asterisk and slash ("*/") characters.

• Comments are ignored by the compiler.

• sum = num1 + num2; • first computes the sum of the values of

num1 and num2 then assigns the result to the variable sum.

• We have used an arithmetic operator (+) and assignment operator (=) in this statement.

Practice: • Make a program that displays the following output?

Arithmetic Operators

• Demonstrating arithmetic operators. Calculating sum, difference, product, quotient, and remainder. Using (float) casting to get floating-point quotient.

Exercise: Rectangle

Make a program to calculate area and perimeter of a rectangle. Input: length of side1 and length of side2. Process: area = side1*side2 perimeter = 2*(side1+side2) Output: area and perimeter

ASCII Codes

• There are only 1s and 0s in a computer system. Computers work with binary numbers.

• We can convert binary numbers into their equivalent decimal numbers that are the numbers we use in our daily life. But what about other characters, letters, punctuation marks, and special characters.

• How can we present them to the computers?

• Character encoding (character set) tables are used to represent the characters with number codes.

• ASCII (1963) and EBCDIC (1964) are two international standard character sets.

Using ASCII codes

Using ASCII codes

ASCII (Pronounced ask-ee) is an acronym for American Standard Code for Information Interchange.

In ASCII, every letter, number, and punctuation symbol has a corresponding number, or ASCII code.

For example, the character for the number 1 has the code 49, capital letter A has the code 65, and a blank space has the code 32.

This encoding system not only lets a computer store a document as a series of numbers, but also makes it possible to transfer data from one computer to another.

Using ASCII codes

In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number (a string of seven 0s or 1s). 128 possible characters are defined.

There are also ASCII extensions in use which utilize 8 bit codes to represent international characters in addition to the standard ASCII scheme.

Using ASCII codes

• EBCDIC (Extended Binary Coded Decimal Interchange Code) is an 8-bit character encoding (code page) used on IBM mainframe operating systems as well as IBM minicomputer operating systems.

• It is also employed on various non-IBM platforms such as Fujitsu-Siemens and Unisys MCP.

• Although it is widely used on large IBM computers, most other computers, including PCs and Macintoshes, use ASCII codes.

Using ASCII codes

cout prints the ASCII character of an ASCII code with “char” casting. The following program prints ASCII code of the number 65 as a character.

ASCII code of the capital letter A is number 65.

Using ASCII codes

The following program reads an ASCII code (an integer) and prints its character.

UNA SANA

ASCII code table part I

ASCII code table part II

Extended ASCII code Table

Exercise: ASCII Character

Make a program to print code of an ASCII character. Input: an ASCII character. Output: ASCII code of the input character. Sample Output: Enter an ASCII character A The ASCII code of A is 65 Press any key to continue . . .

Using ASCII codes

The following program demonstrates how to draw a table by using extending ASCII code characters.

• In programming, a string is an ordered series of characters. You can consider them words and sentences. They are represented with enclosed double quotes in a C++ program code, like "Hello!" or "I am learning C++".

• C++ provides string class for string operations. S string class is defined in the <string> standard library. The instances of variable types are called variables, whereas the instances of classes are called objects. We are going to study classes and objects in the later chapters of this book.

Reading and Printing Strings

#include <string>

• cin reads only the first word of a string, and cout prints all characters of a string.

• The string class has its own methods (functions) for string manipulation. We are going to study string class later in this book.

• The '+' is called string concatenation operator with strings and is used to concatenate two string objects. Do not confuse the string concatenation and arithmetic addition operator.

Examine the following two operations.

• 57 + 33 is 90 Here '+' is addition operator.

• "57" + "33" is "5733„ Here '+' is string concatenation operator.

• The following example reads name and surname of the user, and then prints a hello message.

• You can give the initial values to the variables during the declaration in C++. The following program demonstrates how to declare different type of variables.

• Notice that string objects can be initialized in two ways. You may use either of them in your programs.

Initialization of Variables

Using Text Files as Input and Output

• C++ provides two functions to read from a text file and to write into a text file.

• Those functions are ifstream() and ofstream(). Both functions are declared in the <fstream> header.

• ifstream opens an existing input file whereas, ofstream creates or recreates and opens the output file.

#include <fstream>

• Data input and output operations on text files are performed in the same way we operated with “cin” and “cout”.

• ifstream() function defines an identifier to read from a file, and the name and location (path) of that file. In the same way, ofstream() function defines an identifier to write into a file, and the name and location (path) of the file.

• I prefer to use "fin" and "fout" identifiers in my programs fin takes the role of cin and fout takes the role of cout.

• After you have finished with the input and output files you should close them so that their resources become available again for the system. close() function is used to close the open files.

• The following program read two integers (num1 and num2) from the file numbers.in.

• Computes sum, difference, product and quotient of those two numbers and then writes the result into the file numbers.out.

Recommended