Sei sulla pagina 1di 8

08.

402 COMPUTER PROGRAMMING & NUMERICAL METHODS

Module I INTRODUCTION TO C++ PROGRAMMING

Introduction C++ is an object oriented language. It is an expanded version of C language.C++ was invented by Bjarne Stroustrup in 1979 at Bell laboratories in Murray Hill, New Jersy. C++ was originally called as C with classes , however the name was changed to C++ in 1983. C++ is a superset of C, hence almost all concepts available in C is also available in C++.

Basic Console I/O Statements in C++ Since C++ is a superset of C, all elements of the C language are also contained in the C++ language. Therefore, it is possible to write C++ programs that look just like C programs

The output operator is <<. To output to the console, we write cout << expression; Where expression can be any valid C++ expression, including another output expression. cout << Hello World .\n; cout << 236.99; The input operator is >>. To input values from keyboard, use cin >> variables; For example: cin>>a>>b.

Example 1: The following C++ program makes use of the basic Console I/O statements to read and print two integer variables. #include < iostream.h> int main( ) { // variables declaration int i,j; cout << Enter two integers \n ; // input two integers cin >> i ; cin>>j; // output i then j and newline cout << i= << i cout<< j= << j << \n; return 0; }

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 1

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

Output of the Program Enter two integers 10 20 i=10 j=20 DATA TYPES C++ supports three categories of data types.They are Built in Data types User Defined Data types Derived Data types BUILT IN DATA TYPES Signed integer: The signed integer types are short int (abbreviation short), int and long int (abbreviation long). Optionally the keyword signed can be used in front of these definitions, e.g. signed int. The size of these variables depends on the implementation of the compiler. The only rule for the length of short, int, long is: short<= int<=long, i. e. they may have all the same size. Examples for signed integer variable declarations are listed below. int x,y long int a; Unsigned integer: The unsigned integer types are unsigned short int (abbreviation unsigned short), unsigned int and unsigned long int (abbreviation unsigned long). The sizes follow the same rules as for singed integers. Examples for unsigned integer variable declarations are listed below. unsigned short a; unsigned long x; Character type: Character type variables can hold a single character. The character types are char, signed char and unsigned char. Note that a simple char can mean either signed or unsigned, as this is not defined in ANSI C. It depends therefore only on the implementation of the compiler. A variable can be declared as character type as given below. char x Floating point types: The floating point types are float, double and long double. A float variable has a single precision value. A double or long double variable has at least single precision, but often has double precision (however, this depends on the implementation). The rule for the size of floating point types is: float <= double<=long double. Examples for floating point variable declarations are listed below. double m

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 2

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

float f Boolean type: Standard C++ has an explicit boolean type bool. (C only has an implicit boolean type: 0 = logical false, nonzero = logical true). This type is used to express results of logical operations. The value of the Boolean type is symbolic, either false or true. To ensure compatibility with C and older C++ compiler, the Boolean type is automatically converted to/from integer values. In these cases an integer value of 0 indicates false and a nonzero value indicates true. A variable can be declared as boolean type as given below. bool logic Empty type: The special type void is used for three occasions: defining a function without parameters, defining a function that has no return value and for generic pointers. Example void func() Enumeration Data Type An enumeration is a set of named integer constants that specify all the allowable set of values a variable of that type may have.The general syntax of enumeration data type is enum enum-name{enumeration values} ; Example enum states{Andhara,Karnataka,Kerala,Tamilnadu} ; enum currency { dollar,euro,rupees} Once the enumeration is created, we can declare variables of that type. Example coin money; states s; C++ Tokens In C++ every statement is made up of smallest individual elements called tokens. Tokens are the basic lexical elements. Tokens in C++ include the following Keywords Identifiers Constants Operators

Keywords The list given below contains all the C++ keywords. Every keyword will perform a specific operation in C++. Keywords in C++ cannot be redefined by a programmer; further keywords cannot be used as identifier name. and bool compl and_eq break const asm case const_cast auto catch continue bitand char default bitor class delete

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 3

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

do export goto namespace or_eq return struct try using xor

double extern if new private short switch typedef virtual xor

dynamic_cast false inline not protected signed template typeid void eq

else float int not_eq public sizeof this typename volatile

enum for long operator register static throw union wchar t

explicit friend mutable or reinterpret_cast static_cast true unsigned while

Identifiers Every named program component in C++ like variables, functions, arrays, classes etc. must have legal identifier (name) .In C++ all variables must be declared before they are used. Furthermore, variables must be used in a manner consistent with their associated type. An identifier is formed with a sequence of letters (including _ ) and digits. The first character must be a letter. Identifiers are case sensitive, i.e., first_name is different from First_name.

Examples of valid variable names are myname, jj, name123 Examples of invalid variables 12B Basic pay ABC,1 Invalid variable name since its starts with a number. Invalid variable name since it has a space Invalid variable name since , is a special character

Constants Constants refer to values that do not change during the execution of the program. Examples for constants are 1998 25.789 Hello World a Integer constant Floating point constant String constant Character constant

Operators The data items that operators act upon are called operands. Some operators require two operands, while others act upon only one operand. Most operators allow the individual operands to be expressions. A few operators permit only single variables as operands

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 4

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

ARITHMETIC OPERATORS There are five arithmetic operators in C++. They are Operator + * I % UNARY OPERATORS C++ includes a class of operators that act upon a single operand to produce a new value. Such operators are known as unary operators. Unary operators usually precede their single operands, though some unary operators are written after their operands. Perhaps the most common unary operation is unary minus, where a numerical constant, variable or expression is preceded by a minus sign. (Some programming languages allow a minus sign to be included as a part of a numeric constant. In C, however, all numeric constants are positive. Thus, a negative number is actually an expression, consisting of the unary minus operator, followed by a positive numeric constant.) Note that the unary minus operation is distinctly different from the arithmetic operator which denotes subtraction (-). The subtraction operator requires two separate operands There are two other commonly used unary operators: The increment operator, ++, and the decrement operator, --. The increment operator causes its operand to be increased by 1, whereas the decrement operator causes its operand to be decreased by 1. The operand used with each of these operators must be a single variable. Purpose addition subtraction multiplication division remainder after integer division (modulus operator)

RELATIONAL AND LOGICAL OPERATORS There are four relational operators in C. They are Operator < <= > >= Meaning less than less than or equal to greater than greater than or equal to

These operators all fall within the same precedence group, which is lower than the arithmetic and unary operators. The associativity of these operators is left to right. Closely associated with the relational operators are the following two equality operators, Operator == != Meaning equal to not equal to

The equality operators fall into a separate precedence group, beneath the relational operators. These operators also have a left-to-right associativity. These six operators are used to form logical expressions, which represent

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 5

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

conditions that are either true or false. The resulting expressions will be of type integer, since true is represented by the integer value 1 and false is represented by the value 0.

ASSIGNMENT OPERATORS There are several different assignment operators in C. All of them are used to form assignment expressions, which assign the value of an expression to an identifier. The most commonly used assignment operator is =. Assignment expressions that make use of this operator are written in the form i d e n t i f i e r = expression where i d e n t i f i e r generally represents a variable, and expression represents a constant, a variable or a more complex expression.

CONDITIONAL OPERATOR Simple conditional operations can be carried out with the conditional operator (? :). An expression that makes use of the conditional operator is called a conditional expression. Such an expression can be written in place of the more traditional if -else statement A conditional expression is written in the form expression 1 ? expression 2 : expression 3 When evaluating a conditional expression, expression 1 is evaluated first. If expression 1 is true (i.e., if its value is nonzero), then expression 2 is evaluated and this becomes the value of the conditional expression. However, if expression 7 is false (i.e., if its value is zero), then expression 3is evaluated and this becomes the value of the conditional expression. Note that only one of the embedded expressions (either expression 2 or expression 3) is evaluated when determining the value of a conditional expression.

Operator precedence groups

Operator category unary operators arithmetic arithmetic relational operators equality operators != logical and logical or conditional operator assignment operators && || ?:

Operators - ++ ! sizeof (type) multiply, divide and remainder * I % add and subtract + < <= > >= L->R

Associativity R->L L->R L->R L->R

L-> R L->R R->L R->L

= += -= *= /= %=

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 6

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

LOOPING STATEMENTS C++ supports three type of looping statements as C language .They are While Loop DoWhile Loop For Loop

While Loop The Syntax of while loop is while (expression) { statements ; } the expression is evaluated. If it is non-zero(i.e. if the condition given in the expression is true) , statement s is executed and expression is re-evaluated. This cycle continues until expression becomes zero (false).

Example i=0; //initial value while(i<100) //condition { cout<<i; i=i+2 //increment } Here in this example the while loop prints all the even numbers between 0 and 100.Note the while loop checks for the condition i<100 every time when the loop iterates.

For Loop The for statement is given below for (expr1; expr2; expr3) { statements ; } is equivalent to the while statement given in the previous example expr1 while (expr2) { statement expr3; }

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 7

08.402 COMPUTER PROGRAMMING & NUMERICAL METHODS

Example for (i=0 ;i<100 ;i=i+2) cout<<i ; This is the for loop version of the previous program for printing even numbers between 0 and 100.Here we can note that in for loop the initilaization, condition and increment statements are kept together in the for statement.

Do...while Loop The while and for loops test the termination condition at the top. But the dowhile, tests at the bottom after making each pass through the loop body; the body is always executed at least once. The Syntax of do while statement is do { Statements ; }while (expression); The statement is executed, and then expression is evaluated. If it is true, statement is evaluated again, and so on. When the expression becomes false, the loop terminates. do...while loop is essential when we expect the loop to be executed at least once irrespective of the condition. Example i=0; //initialization do { cout<<i; i+=2; //increment }while(i<100); //condition

Break and Continue Statements The break statement provides an early exit from for, while, and do, just as from switch. A break causes the innermost enclosing loop or switch to be exited immediately. The example given below helps a better understanding about break statement. while (i<100) { cout<<ENTER NEGATIVE NUMBER TO EXIT; cin>>a; if(a < 0) break; sum+=a; } In this example the while loop is writtern to execute 100 times but however when the user gives a negative input the break statement causes the loop to make an early exit

Adarsh. S, Asst. Prof., Dept of CSE, SBCE

Page 8

Potrebbero piacerti anche