Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding Data Types, Input-Output Streams, and Basic Operations in C++, Study notes of Object Oriented Programming

An introduction to the fundamental concepts of C++ programming, including data types, input-output streams, and basic arithmetic operations. It explains how to define and use variables, print output using cout, and perform arithmetic operations using built-in functions. Additionally, it covers the use of const qualifier, formatted stream output, and decision making using if statements.

Typology: Study notes

2021/2022

Uploaded on 09/27/2022

ekani
ekani 🇺🇸

4.7

(26)

265 documents

1 / 31

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Chapter I
Basics of C++ Programming
C++ is an object oriented programming (OOP) language that can be extended through the
use of classes. A class defines a set of member variables and a set member functions. Member
functions define the various operations that can be carried-out on the member variables of the class.
In general, member variables can be accessed only through member functions of the same class. An
instance of a class is called an object and hence the term “object-oriented programming” or OOP.
An instance of a built-in type is called a variable.
Before we delve into OOP programming or class design we will cover the basics of C++
programming. A simple C++ program is shown next:
// A simple C++ program
#include <iostream.h>
#include <conio.h>
void main()
{
cout << "Hello " << endl;
cout << "In this book we will learn about OOP" << endl;
getch();
}
The above program begins with a comment statement preceded by //. In C++ you can include
comments by using one of the following forms:
// Comment, proceeds to the end of the line
or
/* multi-line
Comments. */
C++ programs for console type application, i.e. non Windows type application, must include
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f

Partial preview of the text

Download Understanding Data Types, Input-Output Streams, and Basic Operations in C++ and more Study notes Object Oriented Programming in PDF only on Docsity!

Chapter I

Basics of C++ Programming

C++ is an object oriented programming (OOP) language that can be extended through the use of classes. A class defines a set of member variables and a set member functions. Member functions define the various operations that can be carried-out on the member variables of the class. In general, member variables can be accessed only through member functions of the same class. An instance of a class is called an object and hence the term “object-oriented programming” or OOP. An instance of a built-in type is called a variable. Before we delve into OOP programming or class design we will cover the basics of C++ programming. A simple C++ program is shown next:

// A simple C++ program #include <iostream.h> #include <conio.h>

void main() { cout << "Hello " << endl; cout << "In this book we will learn about OOP" << endl; getch(); }

The above program begins with a comment statement preceded by //. In C++ you can include comments by using one of the following forms: // Comment, proceeds to the end of the line or /* multi-line Comments. */ C++ programs for console type application, i.e. non Windows type application, must include

a function main(). Execution of the program always starts from main(). The function main() returns by default an integer value. A return value is a value returned to the program in which execution of the function was initiated, in this case the operating system. You can override the default by preceding main() with the word void , i.e, no return value. The above simple C++ program contains two #include instructions. These are directives to the compiler to insert the file named between the brackets < > in the above code. The first include statement includes a file named iostream.h. This file defines the input-output streams used in transferring data from or to the program, such as in: cout << "Hello " << endl; cout is defined in iostream.h and the operator “<< ” is for inserting the string "Hello" in the output stream or basically on your computer monitor. The endl instructs the computer to move to the beginning of a new line after typing Hello. The insertion operator can be cascaded as shown in the above statement. A C++ statement is always terminated by a semicolon and can extend over several lines. The library function getch() waits for the user to press any key on the keyboard. Since getch() is the last instruction, once a key is pressed the program terminates. getch() is defined in conio.h. Braces { } are used to outline the start and end of a block of statements. In this case the start and end of the program.

1.1 Basics of number Representations.

Although you can develop programs without knowing anything about number representations. However, a basic understanding of how numbers are represented will clarify such computer terms as byte, bit, etc. The number system we are mostly accustomed to is the decimal number system. In this number system only the following digits are allowed:

0 1 2 3 4 5 6 7 8 9

Any number larger than 9 is written using multiple weights of 10. For example, the number 210 is

to precede the octal number with oct and hexadecimal with hex as follows: cout << oct << 01127; and cout << hex << 0x12EF; You can use: cout << dec << 01127; to print an octal number in decimal representation.

#include <iostream.h> #include <conio.h> main() { cout << 01127 << endl; // Octal number equal to 599 decimal cout << 0x12EF << endl; // Hexadecimal number equal to 4847 decimal getch(); }

Internally all numbers are stored in the computer as binary numbers, e.g. 01101110. Each digit of a binary number is called a bit. An 8 bit number is called a byte (Figure 1.)

7 6 5 4 3 2 1 0

1.2 Built-in variable types in C++

Variables in C++ can be of type integer (declared as int ) or real (declared as float ) or character (declared as char ) or wide character (declared as wchar_t ). All variables to be used in a program must be declared prior to usage. Thus:

Most significant bit Least significant bit MSB LSB Bit Figure 1. A one byte = 8 bits

int i, j; // i and j are variables of type integer float a, k; // a and k are variables of type float char ch, c; // ch and c are variables of type character Variables can be declared anywhere in the program prior to usage, but usually are declared at the beginning of the program. C++ is case sensitive, that is, variable I is a different variable than i, and variable MAX is different than Max or mAx. Variable names can be up to 32 characters and can start with any character from the alphabet or the underscore character ‘_’. Variable names can include numbers, such as _Max1 or var2. int can be of type short , long , unsigned , or long unsigned. Thus integer variables can be declared as follows: short int i, j, k; // i, j and k are short integers short i, j; // same as short integer In 32 bit C++, short is 2 bytes, int and long are 4 bytes and unsigned and long unsigned are 4 bytes. The following table summarizes the different types: Table I Type size in bytes Range int short int or short int long int or long unsigned long unsigned

4 bytes 2 bytes 4 bytes 4 bytes 4 bytes 4 bytes

-32,768 to 32, -2,147,483,648 to 2,147,483, -2,147,483,648 to 2,147,483, 0 to 4,294,967, 0 to 4,294,967, float float

double

long double

4 bytes 4 bytes (allows 7 digit precision) 8 bytes (allows 15 digit precision) 10 bytes (allows 18 digit precision)

3.4×10-38^ to 3.4×10^38

1.7×10-308^ to 1.7×10^308

3.4×10-4932^ to 1.1×10^4932

#include <iostream.h> #include <conio.h> #include <math.h>

void main() { float a; cout << "Enter a number --> "; cin >> a; cout << "The square root of " << a << " = " << sqrt(a); getch(); }

C++ has a math library containing the standard math functions. These are listed in Table II. Table II

Math function

library function

Argument(s) type Return type

cos -1x acos( x ) acosl( x)

double long double

double (radians) long double (radians)

sin-1x asin(x) asinl(x)

double long double

double (radians) long double (radians)

tan-1x

tan-1(x/y)

atan(x) atanl(x) atan2(x,y) atan2l(x,y)

double long double double long double

double (radians) long double (radians) double (radians) long double (radians)

round to the next higher integer

ceil(x) ceill

double long double

double (not integer) long double

x

cos(x) cos(x) cosl(x)

double (radians) long double (radians)

double long double hyperbolic cosine

cosh(x) coshl(x)

double long double

double long double ex^ exp(x) expl(x)

double long double

double long double absolute value

fabs(x) fabsl(x)

double long double

double long double truncate to nearest lower integer

floor(x) floorl(x)

double long double

double long double

loge (x) log(x) logl(x)

double long double

double long double log 10 (x) log10(x) log10l(x)

double long double

double long double x y^ pow(x,y) powl(x,y)

double long double

double long double sin(x) sin(x) sinl(x)

double long double

double long double hyperbolic sin

sinh(x) sinhl(x)

double long double

double long double sqrt(x) sqrtl(x)

double long double

double long double

1.2.1 The const qualifier A constant value like B can be declared as a constant to prevent an accidental modification of its value. The following code demonstrates the use of const. The program changes an angle specified in degrees to radians.

1.2.4 Increment operator The following expressions are equivalent: a = a + 1; ø a ++; or ++a; where the variable “ a ” is an integer (short, long, unsigned or just int). If the ++ precedes the variable then we call this a prefix increment operator and if it follows the variable we call that postfix increment operator. If the variable is incremented by itself in a single statement i.e., a++; or ++a, then there is no difference between postfix and prefix, it basically means add one to the variable. However, if used in a mathematical expression the difference is as follows: Postfix increment (i++) means utilize the variable in the expression before incrementing it, and use the incremented value in the following statements. Prefix increment (++i) means increment the variable and use it in the expression and the following expressions. The following program illustrates this:

#include <iostream.h> #include <conio.h>

void main() { int k=2, j=5; // declare and initialize the variables

int i = k * (j++); // postfix increment cout << " result of 2*(5++)" << endl; cout << "i = " << i << endl; cout << "j = " << j << endl;

j=5; i = k * (++j); // prefix increment

cout << "result of 2*(++5)" << endl;

cout << "i = " << i << endl; cout << "j = " << j << endl; getch(); }

The print-out of the above program is: result of 2(5++) i = 10 j = 6 result of 2(++5) i = 12 j = 6 Note that you are not allowed to increment a constant such as 5 by typing 5++ or ++5. You can, however, assign 5 to an integer variable and then increment the variable as shown in the above program. The expression i=k(j++) multiplies k by j, assigns the result to i and then increments j. The expression i=k(++j) increments j, multiples k by j and then assigns the result to i.

1.3 Formatted Stream Output

The output can be printed using cout and the insertion operator <<. This form, however, does not provide the programmer with much control over the appearance of the printed result. To format outputs you can use the member functions of the object cout, width() and precision() as follows:

#include <iostream.h> #include <conio.h>

void main() { int i = 34,j = 65; float a=5.6789;

#include <iostream.h> #include <conio.h> #include <math.h>

void main() { double x; cout << "Enter a number: "; cin >> x; if( x>0) // x greater than 0 cout << "square root of " << x << " = " << sqrt(x); getch(); }

1.4.2 if-else The general structure of an if-else appears as follows: if ( condition ) { ....... } else { ......} The above structure means that if the condition is satisfied, i.e. true , then the first block statements between the brackets { } are executed, else if the condition is false the block of statements after the else are executed. 1.4.3 Multiple if-else One can cascade if-else structures as follows:

#include <iostream.h> #include <stdlib.h> #include <conio.h>

void main() { float x,y,z; char ch; cout << "Enter two numbers: "; cin >> x >> y; cout << "Enter operator to be carried
out on x and y (+, /, -, ) "; cin >> ch; if(ch=='+') z=x+y; else if (ch=='-') z=x-y; else if (ch=='/') z=x/y; else if (ch=='') z=x*y; else { cout << "unrecognized operator" << endl; getch(); exit(1); //defined in stdlib.h } cout << x << ch << y << " = " << z; getch(); }

Note that in C++ single characters are enclosed between single quotes and a string of characters are enclosed between double quotes. Thus the single character + is written as ‘+’ whereas the string "unrecognized operator" is between double quotes. Note also that the statement: cout << "Enter operator to be carried
out on x and y (+, /, -, *) "; is the same as: cout << "Enter operator to be carried out on x and y (+, /, -, *) ";

#include <stdlib.h> #include <conio.h>

void main() { float x,y,z; char ch; cout << "Enter two numbers: "; cin >> x >> y; cout << "Enter operation (+, -, /, ) -->"; cin >> ch; switch(ch) { case '+': z=x+y; break; case '-': z=x-y; break; case '/': z=x/y; break; case '': z=x*y; break; default: cout << "No such operation" << endl; getch(); exit(1); }

cout << x << ch << y << " = " << z; getch(); } 1.4.5 Logical and bit manipulation operators The following table describes the various logical and bit manipulation operators. Operator Description && AND operator. || (^) OR operator. | Bitwise OR ’ing. & Bitwise AND ’ing. << Shift left.

Shift right. ^ (^) Bitwise exclusive OR

The bitwise logical operators work on individual bits of variables types int or char as follows:

Bit value Result of E1 E2 E1&E2 E1^E2 E1|E 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1

An AND operator results in 1 only if E1 and E2 are both 1's. An exclusive OR results in 1 only if E1 and E2 are different. An OR results in 0 only if both E1 and E2 are 0's. The && and || logical operators work as follows:

1.4.6 The ternary operator ?: The ternary operator ?: has the syntax: var1 = ( test )? var1 : var2 ; which means that var1 = var2 if test = true, otherwise var = var. For example the statement: y = (x > 0)? x:-x; assigns to y the absolute value of x.

1.5 Loops

1.5.1 The for loop The for loop is used for repeating a statement or block of statements several times based on preset conditions. The structure of a for statement is as follows. for (< initialization 1>, ,..; < condition for termination >; < modification 1>, < modification2 >, ..); All statements between < > are considered optional. Examples of for loops: for (i=0; i<10; i++) { statements ;} for ( ; ; ) { statements ;} for (i=0, j=5; i<5; i+=2, j++) { statements ;} The following program illustrates usage.

//Computing factorial #include <iostream.h> #include <conio.h>

void main() { double f=1; int n;

cout << "Enter a number from 1 to 30: "; cin >> n; if(n>0 && n<=30) { for(int i=1; i<=n; i++) f*=double(i); //i is casted to double

cout << n << "!=" << f << endl; } else cout << "Sorry! number out of range" << endl;

getch(); }

The statement f= double (i); transforms an int value into a double through casting. Built-in types (int, float, char, etc.) can be casted into one another using the same approach as in the above statement. The above statement can be rewritten in several ways: f=( double )i; f=f* double (i); f=f( double )i; The for loop can also be written in several ways: for (i=1; i<n; ) f= double (i++);

int i= for ( ; i<n; ) f*= double (i++);