121
CHAPTER I INTRODUCTION TO PROGRAMMING LANGUAGES UNA SANA COLLEGE 2012

Worksheet 3rd grade C++

Embed Size (px)

Citation preview

Page 1: Worksheet 3rd grade C++

CHAPTER I

INTRODUCTION TO

PROGRAMMING LANGUAGES

UNA SANA COLLEGE 2012

Page 2: Worksheet 3rd grade C++

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.

Page 3: Worksheet 3rd grade C++

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

Page 4: Worksheet 3rd grade C++

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

Page 5: Worksheet 3rd grade C++

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

Page 6: Worksheet 3rd grade C++

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

Page 7: Worksheet 3rd grade C++

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

Page 8: Worksheet 3rd grade C++

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

Page 9: Worksheet 3rd grade C++

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

Page 10: Worksheet 3rd grade C++

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

Page 11: Worksheet 3rd grade C++

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

Page 12: Worksheet 3rd grade C++

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

Page 13: Worksheet 3rd grade C++

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;

}

Page 14: Worksheet 3rd grade C++

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

Page 15: Worksheet 3rd grade C++

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

Page 16: Worksheet 3rd grade C++

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

Page 17: Worksheet 3rd grade C++

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.

Page 18: Worksheet 3rd grade C++

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#.

Page 19: Worksheet 3rd grade C++

CHAPTER II

Your first C++ program

Page 20: Worksheet 3rd grade C++

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.

Page 21: Worksheet 3rd grade C++

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.

Page 22: Worksheet 3rd grade C++

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.

Page 23: Worksheet 3rd grade C++

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

Page 24: Worksheet 3rd grade C++

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

Page 25: Worksheet 3rd grade C++

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.

Page 26: Worksheet 3rd grade C++

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!

Page 27: Worksheet 3rd grade C++

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

Page 28: Worksheet 3rd grade C++

Output Operation

An example

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

Sample program codes

Screen Output

Page 29: Worksheet 3rd grade C++
Page 30: Worksheet 3rd grade C++

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

Page 31: Worksheet 3rd grade C++
Page 32: Worksheet 3rd grade C++

new line with \n

Page 33: Worksheet 3rd grade C++

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.

Page 34: Worksheet 3rd grade C++

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.

Page 35: Worksheet 3rd grade C++

You will hear a beep sound.

Page 36: Worksheet 3rd grade C++

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

Page 37: Worksheet 3rd grade C++
Page 38: Worksheet 3rd grade C++

• Make a program that displays a picture of a

house that looks like the following figure?

C++ LAB WORK

Page 39: Worksheet 3rd grade C++
Page 40: Worksheet 3rd grade C++
Page 41: Worksheet 3rd grade C++

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.

Page 42: Worksheet 3rd grade C++

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.

Page 43: Worksheet 3rd grade C++

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.

Page 44: Worksheet 3rd grade C++

• 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

Page 45: Worksheet 3rd grade C++

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.

Page 46: Worksheet 3rd grade C++

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.

Page 47: Worksheet 3rd grade C++

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.

Page 48: Worksheet 3rd grade C++

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

Page 49: Worksheet 3rd grade C++

Using Variables in C++

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

initialize them.

Page 50: Worksheet 3rd grade C++

• 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

Page 51: Worksheet 3rd grade C++

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

Page 52: Worksheet 3rd grade C++

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

Page 53: Worksheet 3rd grade C++

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.

Page 54: Worksheet 3rd grade C++

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.

Page 55: Worksheet 3rd grade C++

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; =

Page 56: Worksheet 3rd grade C++

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;

Page 57: Worksheet 3rd grade C++

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.

Page 58: Worksheet 3rd grade C++

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

Page 59: Worksheet 3rd grade C++

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.

Page 60: Worksheet 3rd grade C++

Determining the size of the variable types on your computer

Using the variables

Page 61: Worksheet 3rd grade C++
Page 62: Worksheet 3rd grade C++

Determining the size of the variable types on your computer

Page 63: Worksheet 3rd grade C++

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

Page 64: Worksheet 3rd grade C++

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

Page 65: Worksheet 3rd grade C++

Using constants

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

1st METHOD

Page 66: Worksheet 3rd grade C++

Using constants

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

2nd METHOD

Page 67: Worksheet 3rd grade C++
Page 68: Worksheet 3rd grade C++

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.

Page 69: Worksheet 3rd grade C++

Input Operation

The input commands in C++ is

• cin >> ……;

Page 70: Worksheet 3rd grade C++

Input Operation

Syntax of cin

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

cin >> variable;

Page 71: Worksheet 3rd grade C++

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.

Page 72: Worksheet 3rd grade C++

Input Operation

Using cin

is equivalent to

Page 73: Worksheet 3rd grade C++

Input Operation

Using cin

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

result.

Page 74: Worksheet 3rd grade C++
Page 75: Worksheet 3rd grade C++

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.

Page 76: Worksheet 3rd grade C++

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

Page 77: Worksheet 3rd grade C++

• 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.

Page 78: Worksheet 3rd grade C++
Page 79: Worksheet 3rd grade C++

• 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.

Page 80: Worksheet 3rd grade C++
Page 81: Worksheet 3rd grade C++

• 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.

Page 82: Worksheet 3rd grade C++

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

Page 83: Worksheet 3rd grade C++
Page 84: Worksheet 3rd grade C++

Arithmetic Operators

Page 85: Worksheet 3rd grade C++

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

Page 86: Worksheet 3rd grade C++
Page 87: Worksheet 3rd grade C++
Page 88: Worksheet 3rd grade C++
Page 89: Worksheet 3rd grade C++
Page 90: Worksheet 3rd grade C++
Page 91: Worksheet 3rd grade C++

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

Page 92: Worksheet 3rd grade C++
Page 93: Worksheet 3rd grade C++
Page 94: Worksheet 3rd grade C++

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

Page 95: Worksheet 3rd grade C++

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.

Page 96: Worksheet 3rd grade C++

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.

Page 97: Worksheet 3rd grade C++

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.

Page 98: Worksheet 3rd grade C++

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.

Page 99: Worksheet 3rd grade C++

Using ASCII codes

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

Page 100: Worksheet 3rd grade C++
Page 101: Worksheet 3rd grade C++

UNA SANA

ASCII code table part I

Page 102: Worksheet 3rd grade C++

ASCII code table part II

Page 103: Worksheet 3rd grade C++

Extended ASCII code Table

Page 104: Worksheet 3rd grade C++

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 . . .

Page 105: Worksheet 3rd grade C++
Page 106: Worksheet 3rd grade C++
Page 107: Worksheet 3rd grade C++

Using ASCII codes

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

Page 108: Worksheet 3rd grade C++
Page 109: Worksheet 3rd grade C++

• 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>

Page 110: Worksheet 3rd grade C++

• 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.

Page 111: Worksheet 3rd grade C++

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.

Page 112: Worksheet 3rd grade C++
Page 113: Worksheet 3rd grade C++
Page 114: Worksheet 3rd grade C++

• 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

Page 115: Worksheet 3rd grade C++
Page 116: Worksheet 3rd grade C++
Page 117: Worksheet 3rd grade C++

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>

Page 118: Worksheet 3rd grade C++

• 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.

Page 119: Worksheet 3rd grade C++

• 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.

Page 120: Worksheet 3rd grade C++
Page 121: Worksheet 3rd grade C++