You are on page 1of 72

FUNDAMENTALS OF C++

Objective
Become familiar with fundamental tokens and data types Write simple computer program in C++ Use simple Output statements

1/23/2011 10:12:26 PM

Dept of CSE

History of C
C is a high level language.
o o o o o o

Evolved by Dennis Ritchie and Brain Kernighan(1978) from two previous programming languages, BCPL (Basic Combined Programming Language ) and B Used to develop UNIX system software routines Is implemented on UNIX operating system Structural / Modular Programming Portable & have compilers for almost all architectures.

1/23/2011 10:12:26 PM

Dept of CSE

C++
C with classes (1979) C++ (1983)
Superset of C developed by Bjarne Stroustrup at Bell Labs and provides object-oriented capabilities named c with classes. o Object-oriented design is very powerful
o

10 to 100 fold increase in productivity


o

Dominant language in industry and academia.

1/23/2011 10:12:26 PM

Dept of CSE

Simple C++ program


// Display This is my first C++ program // Single line comment #include <iostream.h> // preprocessor directive void main( ) // Entry point for program execution { // block of statements: Begin clrscr( ); //Each Statement ends with ; cout << This is my first C++ program; } // block of statements: End

1/23/2011 10:12:26 PM

Dept of CSE

Simple C++ Programs..


// Multi lines comment /* Find the avg. of three marks and display pass or fail */

#include <iostream.h> void main() { cout << Enter Roll Number and marks of three subjects; int RollNo,marks1, marks2, marks3; float avg = 0; const minimum = 35.0; cin >> marks1>> marks2>> marks3; avg = (marks1+marks2+marks3)/avg; if (avg < minimum ) cout << RollNo << fail<< end; else cout << RollNo << pass<<end; }
1/23/2011 10:12:26 PM Dept of CSE

Analogy between learning English Language and C++


Steps in learning English Language:
o o o o

Alphabets Words Sentence Paragraphs Alphabets, Digits, Special Symbols Constants, Variables, Keywords Instructions Programs
Dept of CSE

Steps in learning C++


o o o o

1/23/2011 10:12:26 PM

THE C++ CHARACTER SET, IDENTIFIERS KEYWORDS, CONSTANTS DATA TYPES, VARIABLES

1/23/2011 10:12:26 PM

Dept of CSE

The C++ Character Set


Consists of letters, digits, special characters, white spaces. (i) Letters a, b, c,..z Or A, B, C,.Z (ii) Digits 0, 1, 2,9 (iii) Special characters ;, ?, >, <, &,{, }, [, ] (iv) White spaces New line (\n), \t,

1/23/2011 10:12:26 PM

Dept of CSE

C++ Tokens
Tokens Special Symbols

Keywords

Identifiers

Operators

Strings

constants

Keywords words that are basically sequence of characters defined by a computer language that have one or more fixed meanings. They are also called as reserve words. Key words cannot be changed. Eg. int, float, do-while, if, else,..

1/23/2011 10:12:26 PM

Dept of CSE

Keywords
Each keyword has a predefined purpose in the language. Do not use keywords as variable and constant names!! Some of the C/C++ keywords are
auto, bool, break, case, catch, class, char, const, continue, do, default, delete, double, else, extern, enum, false, float, for, friend, goto, if, int, inline, long, namespace, new, operator, private, protected, public, register, return, short, static, struct, sizeof, switch, template, this, throw, try, typedef, true, unsigned, virtual, void, volatile, while

1/23/2011 10:12:26 PM

Dept of CSE

C++ Tokens
Identifiers allow us to name data and other objects in the program. Each piece of data is stored at unique address instead of using addresses, names are used
Example: user defined names like amount, avg,

Operators +, -, *, %, /, Strings Manipal Constants -15, 10 Special Symbols { } (,

1/23/2011 10:12:26 PM

Dept of CSE

Identifiers
An identifier is a name for a variable, constant, function, etc. It consists of a letter followed by any sequence of letters, digits, and underscores.

1/23/2011 10:12:26 PM

Dept of CSE

Identifiers rules
A valid identifier is a sequence of one or more letters, digits or underscore character (_). Neither spaces nor punctuation marks or symbols can be part of an identifier Only letters, digits and underline characters are valid variable identifiers always have to begin with a letter They can also begin with an underscore character (_ ), but this is usually reserved for compiler specific keywords or external identifiers.

1/23/2011 10:12:26 PM

Dept of CSE

Identifiers rules
They can not begin with a digit. The C/C++ is a "case sensitive" language. An identifier written in capital letters is not equivalent to another one with the same name but written in small letters. The RESULT variable is not the same as the result variable or the Result variable They cannot match any keyword of the C++ language or your compiler's specific ones since they could be confused with these.

1/23/2011 10:12:26 PM

Dept of CSE

Identifiers
Examples of valid identifiers: First_name, age, y2000, y2k Examples of invalid identifiers: 2000y Identifiers cannot have special characters in them. For example: X=Y, J-20, ~Ricky,*Michael are invalid identifiers. Identifiers are case-sensitive. For example: Hello, hello, WHOAMI, WhoAmI, whoami are unique identifiers.

1/23/2011 10:12:26 PM

Dept of CSE

Constants
A value that IS NOT going to be changed during the execution of our program; Constant are specific values that are used in arithmetic expressions or assigned to variables, e.g. 2, 5, -10, 2.e+6, 3.14159, and so forth; Sometimes a constant represents truly a constant value in nature such as: Pi 3.14159 speed of light 2.99792+E8 meters/sec

1/23/2011 10:12:26 PM

Dept of CSE

Constants

1/23/2011 10:12:26 PM

Dept of CSE

Numeric Constants
Integer Constants
Refers to a sequence of digits. Decimal, Octal , Hexadecimal. o Decimal: set of digits 0 to 9, preceded by optional or + sign o Octal: digits 0 to 7 with a leading 0 o Hexadecimal: digits 0 to 9, char A to F preceded by 0x
E.g.: 143, -564, 0346, 0x34, 0x8AF

1/23/2011 10:12:26 PM

Dept of CSE

Floating Point Constant


Used to represent numbers with fractional part E.g.; 213.45, .456,234. Another form mantissa e exponent 0.56e4, 3.12E4 , -4.6E-1

Character Constants
Single character Single character with in a pair of single quote ( ) marks, having integer values known as ASCII values. E.g.: d, t, 9
1/23/2011 10:12:26 PM Dept of CSE

String Constants
A sequence of characters enclosed in double quotes ( ). Characters may be letters, numbers, special characters and blank space. E.g.: hello, 2007, T, 4+5 Backslash character constants Used in output functions E.g.: \n new line, \0 null char, \a, \b, \t, \ Also known as escape characters.

1/23/2011 10:12:26 PM

Dept of CSE

Symbolic Constants
Which helps us to associate an identifier with a constant value in your program; The advantage is that you can refer to the identifier any time you need to use the constant value instead of having to repeat writing the value; To declare a symbolic constant you must do it as follows: const data type identifier = value;

1/23/2011 10:12:26 PM

Dept of CSE

Symbolic Constant - example


Consider the Example below: void main() { float area, perimeter; float radius; const double Pi = 3.14159; area = radius * radius * Pi; perimeter = 2 * Pi * radius; cout <<Area equals <<area << Perimeter equals <<perimeter; }

1/23/2011 10:12:26 PM

Dept of CSE

Variables
A variable is a data name that may be used to store a data value. A variable may take different values at different times during execution. Variable name chosen by the programmer in a meaningful way. Each variable needs an identifier that distinguishes it from the others. ( rules similar to identifier)

1/23/2011 10:12:26 PM

Dept of CSE

C++ data Types

1/23/2011 10:12:26 PM

Dept of CSE

Data types
C++ Language is rich in its data types Mainly 4 classes of data types Primary (fundamental or Built-in type) data types, User defined Data types Derived Data types The fundamental or Built-in data types fall into one of three categories Integer type Floating-point type Character type
Empty data set.

1/23/2011 10:12:26 PM

Dept of CSE

Primary (built-in or Basic) Data types


INTEGRAL TYPE INTEGER
SIGNED TYPE UNSIGNED TYPE
INT UNSIGNED INT SHORT INT UNSIGNED SHORT INT LONG INT UNSIGNED LONG INT

CHARACTER
SIGNED CHARCATER UNSIGNED CHARACTER

FLOATING POINT TYPE


FLOAT DOUBLE LONG DOUBLE
1/23/2011 10:12:26 PM Dept of CSE

void

Integer Types
The basic integer type is int
o

The size of an int depends on the machine and the


On PCs it is normally 16 or 32 bits short int int long int

Modifiers
o o o o

Different types allow programmers to use resources more efficiently. Standard arithmetic and relational operations are available for these types.

short: typically uses less bits long: typically uses more bits unsigned signed

1/23/2011 10:12:26 PM

Dept of CSE

SIZE AND RANGE OF VALUES FOR A 16-BIT MACHINE (INTEGER TYPE)


Type short int or signed short int unsigned int integer int or signed int unsigned int long int or signed long int unsigned long int
1/23/2011 10:12:26 PM

Size
(bits)

Range -128 to 127 0 to 255 -32,768 to 32,767 0 to 65,535 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295

short

8 8 16 16 32 32

long

Dept of CSE

Character Types
Character type char is related to the integer types Modifiers unsigned and signed can be used char 1 byte(-128 to 127) signed char 1 byte(-128 to 127) unsigned char 1 byte(0 to 255) Characters are encoded using a scheme where an integer represents a particular character ASCII is the dominant encoding scheme
(American Standard Code for Information Interchange ) Examples
o o o

' ' encoded as 32 '+' encoded as 43 'A' encoded as 65 'Z' encoded as 90 'a' encoded as 97 'z' encoded as 122

1/23/2011 10:12:26 PM

Dept of CSE

Floating-Point Types
Floating-point types represent real numbers
o o

The number 108.1517 breaks down into the following parts


o o o o o

Integer part Fractional part

C provides three floating-point types


float double long double
float double long double
1/23/2011 10:12:26 PM Dept of CSE

108 - integer part 1517 - fractional part

SIZE AND RANGE OF VALUES FOR 16-BIT MACHINE (FLOATING between Single 32 bits Numbers POINT)
Precision Double Precision float 4 bytes 3.4 E-38 and 3.4E+38 64 bits Numbers between 1.7E8 bytes 308 and 1.7E+308 double

Type

Size

Range

Long Double 80 bits Numbers between 3.4Elong double Precision 10 bytes 4932 and1.1E+4932

1/23/2011 10:12:26 PM

Dept of CSE

void
2 uses of void are
To specify the return type of a function when it is not returning any value o To indicate an empty argument list to a function
o

1/23/2011 10:12:26 PM

Dept of CSE

Boolean
Logical or Boolean data- named after French Mathematician/philosopher George Boole
o o o

Consists of only two values: true and false Nonzero number can be used to represent true Zero is used to represent false

1/23/2011 10:12:26 PM

Dept of CSE

Declaration of variables

In order to use a variable in C++, we must first declare it. It does two things Tells the compiler the variable name. Specifies the type of data. Primary Type declaration: write the specifier of the desired data type (like int, char, float...) followed by a valid variable identifier. i.e data-type V1, V2,,Vn ; For example: int a; float mynumber, sum;

1/23/2011 10:12:26 PM

Dept of CSE

Declaration of variables
The integer data types short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero).

1/23/2011 10:12:26 PM

Dept of CSE

Declaration of variables
Signed and unsigned can be specified by using either the specifier signed or the specifier unsigned before the type name. For example: unsigned short int NumberOfSisters; signed int MyAccountBalance By default most compiler settings will assume the type to be signed(exception is char).

1/23/2011 10:12:26 PM

Dept of CSE

Short and long can be used alone as type specifiers.


o

Declaration of variables
short Year; short int Year;

The following two variable declarations are equivalent:

Signed and unsigned may also be used as standalone type specifiers.


o

The following two declarations are equivalent:


unsigned NextYear; unsigned int NextYear;

1/23/2011 10:12:26 PM

Dept of CSE

Declaration of variables
Floating point: keywords float, double, long double Character Type: keywords char, unsigned char, signed char. Eg: double deviation; char p, q;

1/23/2011 10:12:26 PM

Dept of CSE

Assigning values to variables


Values can be assigned using the assignment operator = o It is possible to assign at the time of declaration.
data-type varaiable-name=constant ; int final_value = 100, p = 20; char yes = m; The process of giving initial values to variables Initialization. external & static variables initialized to zero by default. Assigning values to variables after declaration Eg: initial = 1; area = 23.89; const int class_size = 40; const tells the compiler the value of variable class_size must not modified by the program. It can be used on the right hand side of any assignment statement.

1/23/2011 10:12:26 PM

Dept of CSE

Initialization of variables example


#include <iostream.h> void main () { int a=5; // initial value = 5 int b; b=2; // initial value = 2 int result; // initial value undetermined a = a + 3; result = a - b; cout << result; }

1/23/2011 10:12:26 PM

Dept of CSE

User defined Type declarations


typedef
o

enum
o

Type definition - lets you define your own type identifiers. Enumerated data type - a type with restricted set of values.

1/23/2011 10:12:26 PM

Dept of CSE

User defined Type Declaration


typedef : general declaration format
typedef type identifier; The type refers to an existing data type and identifier refers to the new name given to the data type.
After the declaration, we can use the identifier to declare variables.

typedef int marks; typedef float units; marks m1,m2; //m1 & m2 are declared as integer variables units u1, u2; //u1 & u2 are declared as floating point variables
The main advantage of typedef is that we can create meaningful data type names for increasing the readability of the program.

1/23/2011 10:12:26 PM

Dept of CSE

User defined Type Declaration


enum data type : general declaration format
enum identifier {value1, value2,..,valuen}; The identifier is a user defined enumerated data type which can be used to declare variables that can have one of the values known as enumeration constants. After this declaration as follows: enum identifier v1,v2,vn; enumerated variables v1,v2,..,vn can only have one of the values value1, value2,,valuen

1/23/2011 10:12:26 PM

Dept of CSE

User defined Type Declaration


E.g.: enum day {Mon, Tue, Wed, Thu, Fri, Sat, Sun} ; enum day week_st, week_end, Today; week_st = Mon; week_end= Sat; if(Today == Fri) cout<<I got CP Lab
Compiler automatically assigns integer starting with 0 to all enumeration constants. But can be overridden.

E.g.: if you give enum day {Mon=2, Tue, Wed, Thu, Fri, Sat, Sun};
Mon is assigned 2 & subsequent constants incremented by one.
1/23/2011 10:12:26 PM Dept of CSE

enum example
If declared; enum day { Monday=1, Tuesday,, Sunday};
cout<<"\n\nEnter n >1 &<7., 0 for Exit:- "; cin>>i; switch(i) { case Monday: cout<<Monday."; break; case Tuesday cout<< Tuesday."; break; case Wednesday: cout<< Wednesday."; break; case Thursday: cout<< Thursday."; break;
1/23/2011 10:12:26 PM

case Friday: cout<< Friday."; break; case Saturday: cout<<\Saturday."; break; case Sunday: cout<<Sunday."; break; case 0: exit(0); default: cout<<"\nInvalid Entry. Enter 0-7."; break; }

Dept of CSE

Review of Data Types


What is a data type? List the different category of data tyes? Name the types under Built-in Data types. Discuss the variations of the following: int, char, float What is void? Why it is required? How you can declare variables? What is initialization? Why it is required? List the six different steps involved in executing a program.

1/23/2011 10:12:26 PM

Dept of CSE

Typical C++ Program Development Environment


Phases of C++ Programs: 1. Edit Preprocess Compile Link Load Execute

1/23/2011 10:12:26 PM

Dept of CSE

A Simple C++ program


1 // Program: first.cpp 2 // My first program in C++. 3 #include <iostream> 4 5 // function main begins program execution 6 int main() 7{ 8 cout << "Welcome to C++!\n"; 9 10 return 0; // indicate that program ended successfully 11 12 } // end function main

Welcome to C++!

1/23/2011 10:12:26 PM

Dept of CSE

Comments
These are single line comments. All lines beginning with two slash signs (//) are considered comments They do not have any effect on the behavior of the program The programmer can use them to include short explanations or observations within the source code itself.

// Program: first.cpp // my first program in C++

1/23/2011 10:12:26 PM

Dept of CSE

#include <iostream.h>
Lines beginning with a sign (#) are directives for the preprocessor. They are not regular code lines. directive #include <iostream.h> tells the preprocessor to include the iostream standard header file. This specific file (iostream.h) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later.

1/23/2011 10:12:26 PM

Dept of CSE

void main ()
The main function is the point where all C++ programs start their execution, independently of its location within the source code. it is essential that all C++ programs have a main function. The word main is followed in the code by a pair of parentheses (). That is because it is a function declaration. Optionally, these parentheses may enclose a list of parameters within them. Right after these parentheses we can find the body of the main function enclosed in braces{ }.
1/23/2011 10:12:26 PM Dept of CSE

cout <<Welcome to C++!\n;


This line is a C++ statement. A statement is a simple or compound expression that can actually produce some effect. cout represents the standard output stream in C++. meaning of the entire statement is to insert a sequence of characters into the standard output stream (which is usually the screen). (;) This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements [other than control structures & main()] in all C+ + programs.
1/23/2011 10:12:26 PM Dept of CSE

cin>> Rules
>> known as extraction or get from operator. It extracts the value from keyboard & assign it to the variable on its right. Integer read o Ignores/skips leading white space characters (space, tab, new line) o Begins collecting digits, stops at the first non-digit character (leaving that character in the buffer) Character read o Ignores/skips leading white space characters (space, tab, new line) o Reads next character (any valid ASCII character)
1/23/2011 10:12:26 PM Dept of CSE

cin>> Rules
String read
Ignores/skips leading white space characters (space, tab, new line) o Collects characters and stops at the first white space character E.g.: cin>>a; cin>>b>>c;
o

1/23/2011 10:12:26 PM

Dept of CSE

cout<< Operator
<< is called the insertion or put to operator.
It inserts the contents of the variable on its right to the object on its left. E.g.: cout<<enter two numbers \n; cout<<Sum =<<sum<<\n;

1/23/2011 10:12:26 PM

Dept of CSE

A Simple C++ program


1 // Program: Second.cpp 2 // Printing a line with multiple statements. 3 #include <iostream> 4 5 // function main begins program execution Multiple stream 6 int main() insertion statements 7{ produce one line of 8 cout << "Welcome "; output. 9 cout << "to C++!\n"; 10 11 return 0; // indicate that program ended successfully 12 13 } // end function main

Welcome to C++!
1/23/2011 10:12:26 PM Dept of CSE

A Simple C++ program


1 // Program: third.cpp 2 // Printing multiple lines with a single statement 3 #include <iostream> 4 Using newline 5 // function main begins program execution 6 int main() characters to print 7{ multiple lines. 8 cout << "Welcome\nto\n\nC++!\n"; 9 10 return 0; // indicate that program ended successfully 11 12 } // end function main

on

Welcome to C++!
1/23/2011 10:12:26 PM Dept of CSE

1 // Program: Add.cpp 2 // Addition program. 3 #include <iostream> 4 5 // function main begins program execution 6 void main() 7{ 8 int integer1; // first number to be input by user Enter first integer 9 int integer2; // second number to be input by user 45 int sum; // variable in which sum will be stored 10 Enter second integer 11 72 cout << "Enter first integer\n"; // prompt 12 Sum is>> integer1; // read an integer 13 cin 117 14 15 cout << "Enter second integer\n"; // prompt 16 cin >> integer2; // read an integer 17 18 sum = integer1 + integer2; // assign result to sum 19 20 cout << "Sum is " << sum << endl; // print sum 21 22 } // end function main

A Simple C++ program

OUTPUT

1/23/2011 10:12:26 PM

Dept of CSE

WAP to read and display a number


Algorithm : read and display a no.
Step1: Read a no. Step 2: [display it on the screen] Print the no. is =, no. Step 4: [End of algorithm] Stop
Input a no. Start

Print the no.

Stop

1/23/2011 10:12:26 PM

Dept of CSE

Program to read and display a number

#include<iostream.h> // header file for input/output #include<conio.h> // header file for clrscr() & getch() void main() //main function { //program body begins clrscr(); //in-built function int a; //variable declaration cout<<enter number ; // user friendly info display cin>>a; // reading or input value to the variable cout<<\nthe no. is\n<<a; //writing or output variable value getch(); } // end of program

1/23/2011 10:12:26 PM

Dept of CSE

Write C++ Programs


[algorithm, flowchart & program]
To convert seconds into minutes & seconds To convert Celsius to Fahrenheit & vice versa

1/23/2011 10:12:26 PM

Dept of CSE

WAP to convert seconds into hours, minutes & seconds


Algorithm : conversion of secs into hr, min, secs
Step1: Read secs Step 2: [do conversions] hr= sec/3600 sec=sec mod 3600 hr= sec/3600 min= sec/60 min= (sec mod 3600)/60 sec= sec mod 60 sec= (sec mod 3600) mod 60 Step 3: print hours= hr, minutes= min, seconds= sec Step 4: [End of algorithm] Stop
Print hr, min and sec Stop
1/23/2011 10:12:26 PM Dept of CSE

Start Input sec

Program to to convert seconds into Hours, minutes & seconds #include<iostream.h>


#include<conio.h> void main( ) { int sec, hr, min; cout<<enter seconds; cin>>sec; hr= sec/3600; sec = sec % 3600; min= sec/60; sec= sec % 60; cout<<\n<<hour=<<hr<<minutes=<<min; cout<<seconds=<<sec; }

1/23/2011 10:12:26 PM

Dept of CSE

WAP to convert Celsius to Fahrenheit & vice versa


Algorithm : To convert Celsius to Fahrenheit & vice versa
Step1: Read celsius Step 2: Fahrenheit =(9.0 / 5.0) * celsius + 32.0 Step 3: Print temp in Fahrenheit= Fahrenheit Step 4: Read Fahrenheit Step 5: celsius =(Fahrenheit 32) * (5.0 / 9) Step 6: Print temp in celsius= celsius Step 7: Stop

1/23/2011 10:12:26 PM

Dept of CSE

Flowchart

Start Read Celsius

Fahrenheit =(9.0 / 5.0) * celsius + 32.0 print Fahrenheit

Read Fahrenheit celsius =(Fahrenheit 32) * (5.0 / 9) Print Celsius Stop


1/23/2011 10:12:26 PM Dept of CSE

Program to convert Celsius to Fahrenheit & vice versa


#include<iostream.h> #include<conio.h> void main() { float faren , cel; cout<<enter temperature in Celsius; cin>>cel; faren=(9.0 / 5.0) * cel + 32.0; cout<<fahrenheit =<<faren; cout<<enter temperature in fahrenheit ; cin>>faren; cel=(faren 32) * (5.0 / 9); cout<<celsius= <<cel; }

1/23/2011 10:12:26 PM

Dept of CSE

Write C++ Programs


To exchange memory variable a and b To display a triangle of * on the screen Find the sum of digits of a 4-digit number

1/23/2011 10:12:26 PM

Dept of CSE

Program to exchange memory variables a, b


# include<iostream.h> # include<conio.h> void main( ) { int a,b; cout<<"enter 2 numbers: "; cin>>a; cin>>b; a=a + b; b=a-b; a=a-b; cout<<"after interchange the values are<<a<<"\t"<<b; }

1/23/2011 10:12:26 PM

Dept of CSE

Program to display a triangle of *s on the screen


#include<iostream.h> #include<conio.h> void main() { clrscr(); cout<<" * "; cout<<"\n ***"; cout<<"\n *****"; }

1/23/2011 10:12:26 PM

Dept of CSE

Program to compute sum of digits of a 4-digit number


#include<iostream.h> #include<conio.h> void main(){ clrscr(); int num, digit, sum=0; cout<<enter 4 digit no.; cin>>num; digit= num%10; sum=sum + digit; num=num/10; digit= num%10; num=num/10; sum=sum + digit; digit= num%10; num=num/10; sum=sum + digit + num; cout<<\n<<sum of digits=<<sum; getch(); }

1/23/2011 10:12:26 PM

Dept of CSE

Try the Following problems


1. Write a C++ program to read the price of an item in decimal form(like 15.95) and print the output in paise(like 1595 paise). 2. Write a C++ program to covert distance in mm to cm, inch, feet (1 cm =10mm, 1inch=2.5cm, 1 feet =12 inches).

1/23/2011 10:12:26 PM

Dept of CSE