C++ Fundamentals

73
FUNDAMENTALS OF C++

description

c++

Transcript of C++ Fundamentals

Page 1: C++ Fundamentals

FUNDAMENTALS OF C++

Page 2: C++ Fundamentals

Objective

• Become familiar with fundamental tokens and data types

• Write simple computer program in C++

• Use simple Output statements

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

2

Page 3: C++ Fundamentals

History of C C is a high level language.

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

3

Page 4: C++ Fundamentals

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

Object-oriented design is very powerful

10 to 100 fold increase in productivity

Dominant language in industry and academia.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

4

Page 5: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

5

Page 6: C++ Fundamentals

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)/3; if (avg < minimum ) cout << RollNo <<“ fail”<< end; else cout << RollNo << “pass”<<end; }

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

6

Page 7: C++ Fundamentals

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

9

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 ex. New line (\n)

The C++ Character Set

Page 8: C++ Fundamentals

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

10

C++ Tokens

Tokens

Keywords Identifiers Operators Strings constants Special

Symbols

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.

ex. int, float, do-while, if, else,…………..

Page 9: C++ Fundamentals

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 …

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

11

Page 10: C++ Fundamentals

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

12

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

int amount, float avg, …

Operators +, -, *, %, /, …

Strings “Manipal”

Constants -15, 10

Special Symbols { } (, …

C++ Tokens

Page 11: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

13

Page 12: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

14

Page 13: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

15

Page 14: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

16

Page 15: C++ Fundamentals

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

17

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

Constants

Page 16: C++ Fundamentals

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

18

Constants

Numeric Constants

Integer constants

Real Constants

Character Constants

Single character constants

String constants

Constants

Page 17: C++ Fundamentals

Numeric Constants Integer Constants

Refers to a sequence of digits.

Decimal, Octal , Hexadecimal.

Decimal: set of digits 0 to 9, preceded by optional “–” or “+” sign

Octal: digits 0 to 7 with a leading “0”

Hexadecimal: digits 0 to 9, char A to F preceded by “0x”

E.g.: 143, -564, 0346, 0x34, 0x8AF

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

19

Page 18: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

20

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’

Page 19: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

21

Page 20: C++ Fundamentals

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)

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

22

Variables

Page 21: C++ Fundamentals

C++ data Types

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

23

C++ Data Types

User Defined Type Structure, Union, Class

enumeration Built-in-type

Integral type

int char

void Floating Type

float double

Derived Type Array, Function, Pointer

Page 22: C++ Fundamentals

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

Empty data set.

The fundamental or Built-in data types fall into one of

three categories

Integer type

Floating-point type

Character type

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

24

Page 23: C++ Fundamentals

Primary (built-in or Basic) Data types

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

25

void

SIGNED TYPE UNSIGNED TYPE INT UNSIGNED INT

SHORT INT UNSIGNED SHORT INT

LONG INT UNSIGNED LONG INT

SIGNED CHARCATER

UNSIGNED CHARACTER

FLOAT

DOUBLE

LONG DOUBLE

INTEGER CHARACTER

FLOATING POINT TYPE

INTEGRAL TYPE

Page 24: C++ Fundamentals

Integer Types The basic integer type is int The size of an int depends on the machine and the

On PCs it is normally 16 or 32 bits

Modifiers short: typically uses less bits

long: typically uses more bits

unsigned

signed

Different types allow programmers to use resources more efficiently.

Standard arithmetic and relational operations are available for these types.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

26

short int int

long int

Page 25: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

27

Type Size (bits)

Range

short

short int or signed short int 8 -128 to 127

unsigned int 8 0 to 255

integer int or signed int 16 -32,768 to 32,767

unsigned int 16 0 to 65,535

long

long int or signed long int 32

-2,147,483,648 to 2,147,483,647

unsigned long int 32 0 to 4,294,967,295

Page 26: C++ Fundamentals

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 ' ' encoded as 32 '+' encoded as 43

'A' encoded as 65 'Z' encoded as 90

'a' encoded as 97 'z' encoded as 122

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

28

Page 27: C++ Fundamentals

Floating-Point Types Floating-point types represent real numbers

Integer part

Fractional part

The number 108.1517 breaks down into the following parts

108 - integer part

1517 - fractional part

C provides three floating-point types

float

double

long double

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

29

float double

long double

Page 28: C++ Fundamentals

SIZE AND RANGE OF VALUES FOR 16-BIT MACHINE (FLOATING POINT)

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

30

Type Size Range

Single Precision

float 32 bits 4 bytes

Numbers between 3.4 E-38 and 3.4E+38

Double Precision

double 64 bits 8 bytes

Numbers between 1.7E-308 and 1.7E+308

Long Double Precision

long double 80 bits

10 bytes Numbers between 3.4E-

4932 and1.1E+4932

Page 29: C++ Fundamentals

void

2 uses of void are

To specify the return type of a function when it is not

returning any value

To indicate an empty argument list to a function

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

31

Page 30: C++ Fundamentals

Boolean

• Logical or Boolean data- named after French

Mathematician/philosopher George Boole

• Consists of only two values: true and false

• Nonzero number can be used to represent true

• Zero is used to represent false

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

32

Page 31: C++ Fundamentals

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;

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

33

Page 32: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

34

Page 33: C++ Fundamentals

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

35

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

Declaration of variables

Page 34: C++ Fundamentals

Declaration of variables Short and long can be used alone as type specifiers.

The following two variable declarations are equivalent:

short Year;

short int Year;

Signed and unsigned may also be used as standalone type

specifiers.

The following two declarations are equivalent:

unsigned NextYear;

unsigned int NextYear;

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

36

Page 35: C++ Fundamentals

Declaration of variables

Floating point:

keywords float, double, long double

Character Type:

keywords char, unsigned char, signed char.

Eg:

double deviation;

char p, q;

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

37

Page 36: C++ Fundamentals

Assigning values to variables Values can be assigned using the assignment operator ‘ = ’

It is possible to assign at the time of declaration.

data-type varaiable-name=constant

Eg: initial = 1;

area = 23.89;

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.

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

38

Page 37: C++ Fundamentals

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;

}

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

39

Page 38: C++ Fundamentals

User defined Type declarations

typedef

Type definition - lets you define your own identifiers.

enum

Enumerated data type - a type with restricted set of

values.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

40

Page 39: C++ Fundamentals

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 as follows:

typedef int marks;

typedef float units;

we can use these to declare variables as shown

marks m1,m2[10]; //m1 & m2[10] 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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

41

Page 40: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

42

Page 41: C++ Fundamentals

User defined Type Declaration E.g.: enum day {Monday, Tuesday,… ,Sunday} ; enum day week_st, week_end; week_st = Monday; week_end= Friday; if(week_st == Tuesday) week_end = Saturday;

Compiler automatically assigns integer starting with 0 to all enumeration constants. But can be overridden.

E.g.: if you give enum day { Monday=1, Tuesday,…, Sunday};

Monday is assigned 1 & subsequent constants incremented by one.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

43

Page 42: C++ Fundamentals

7/5/2014 7:43:31 AM Dept of CSE 45

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;

Symbolic Constants

Page 43: C++ Fundamentals

7/5/2014 7:43:31 AM Dept of CSE 46

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;

}

Symbolic Constant - example

Page 44: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

47

Page 45: C++ Fundamentals

Typical C++ Program Development Environment

7/5

/20

14

7:4

3:3

1 A

M

De

pt o

f C

SE

48

Phases of C++ Programs:

1. Edit

2. Preprocess

3. Compile

4. Link

5. Load

6. Execute

Page 46: C++ Fundamentals

A Simple C++ program

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

49

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

Single-line comments.

Preprocessor directive to

include input/output stream

header file <iostream>. Function main appears

exactly once in every C++

program..

Function main returns an

integer value. Left brace { begins function

body.

Corresponding right brace }

ends function body.

Statements end with a semicolon ;.

Stream insertion operator.

Keyword return is one of

several means to exit function; value 0 indicates

program terminated

successfully.

Page 47: C++ Fundamentals

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

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.

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

50

Comments

Page 48: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

51

Page 49: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

52

Page 50: C++ Fundamentals

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.

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

53

Page 51: C++ Fundamentals

‘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

Ignores/skips leading white space characters (space, tab, new line)

Begins collecting digits, stops at the first non-digit character (leaving that character in the buffer)

Character read

Ignores/skips leading white space characters (space, tab, new line)

Reads next character (any valid ASCII character)

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

54

Page 52: C++ Fundamentals

‘cin>>’ Rules

String read

Ignores/skips leading white space characters (space, tab,

new line)

Collects characters and stops at the first white space

character

E.g.:

cin>>a; cin>>b>>c;

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

55

Page 53: C++ Fundamentals

‘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”;

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

56

Page 54: C++ Fundamentals

A Simple C++ program

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

57

1 // Program: Second.cpp

2 // Printing a line with multiple statements.

3 #include <iostream>

4

5 // function main begins program execution

6 int main()

7 {

8 cout << "Welcome ";

9 cout << "to C++!\n";

10

11 return 0; // indicate that program ended successfully

12

13 } // end function main

Welcome to C++!

Multiple stream

insertion statements

produce one line of

output.

Page 55: C++ Fundamentals

A Simple C++ program

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

58

1 // Program: third.cpp

2 // Printing multiple lines with a single statement

3 #include <iostream>

4

5 // function main begins program execution

6 int main()

7 {

8 cout << "Welcome\nto\n\nC++!\n";

9

10 return 0; // indicate that program ended successfully

11

12 } // end function main

Welcome to C++!

Using newline

characters to print on

multiple lines.

Page 56: C++ Fundamentals

A Simple C++ program

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

59

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

9 int integer2; // second number to be input by user

10 int sum; // variable in which sum will be stored

11

12 cout << "Enter first integer\n"; // prompt

13 cin >> integer1; // read an integer

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

Declare integer

variables.

Use stream extraction

operator with standard

input stream to obtain

user input.

Stream manipulator endl outputs a

newline, then “flushes

output buffer.”

Concatenating, chaining

or cascading stream

insertion operations. Calculations can be performed in output statements:

alternative for lines 18 and 20:

cout << "Sum is " << integer1 + integer2 << endl

Enter first integer

45

Enter second integer

72

Sum is 117

OUTPUT

Page 57: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

60

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

WAP to read and display a number

Input a no.

Print the no.

Start

Stop

Page 58: C++ Fundamentals

#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

Program to read and display a number

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

61

Page 59: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

62

• To convert seconds into hours,minutes & seconds

• To convert Celsius to Fahrenheit & vice versa

Write C++ Programs [algorithm, flowchart & program]

Page 60: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

63

Algorithm : conversion of secs into hr, min, secs

Step1: Read secs

Step 2: [do conversions]

hr= sec/3600

min= (sec mod 3600)/60

sec= (sec mod 3600) mod 60

Step 3: print ‘hours=‘ hr, ‘minutes=‘ min, ’seconds=‘ sec

Step 4: [End of algorithm]

Stop

WAP to convert seconds into hours, minutes & seconds

hr= sec/3600 min= (sec mod 3600)/60

sec= (sec mod 3600) mod 60

Input sec

Print hr, min and sec

Start

Stop

Page 61: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

64

#include<iostream.h>

#include<conio.h>

void main( ){

int sec, hr, min;

cout<<“enter seconds”;

cin>>sec;

hr= sec/3600;

min= (sec % 3600)/60;

sec= (sec % 3600) % 60;

cout<<“\n”<<“hour=“<<hr<<“minutes=“<<min;

cout<<“seconds=“<<sec;

}

Program to to convert seconds into

Hours, minutes & seconds

Page 62: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

65

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

WAP to convert Celsius to Fahrenheit & vice versa

Page 63: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

66

Flowchart Read Celsius

Fahrenheit =(9.0 / 5.0) * celsius + 32.0

print Fahrenheit

Read Fahrenheit

celsius =(Fahrenheit – 32) * (5.0 / 9)

Print Celsius

Start

Stop

Page 64: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

67

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

}

Program to convert Celsius to Fahrenheit & vice versa

Page 65: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

68

• 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

Write C++ Programs

Page 66: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

69

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

}

Program to exchange memory variables a, b

Page 67: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

70

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

cout<<" * ";

cout<<"\n ***";

cout<<"\n *****";

}

Program to display a triangle of *’s on the screen

Page 68: C++ Fundamentals

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

71

#include<iostream.h>

#include<conio.h>

void main(){

clrscr();

int num, digit, sum=0;

cout<<“enter 4 digit no.”;

cin>>num;

digit= num%10;

num=num/10;

sum=sum + digit;

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();

}

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

Page 69: C++ Fundamentals

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

7/5

/20

14

7:4

3:3

2 A

M

De

pt o

f C

SE

72

Page 70: C++ Fundamentals

What output is generated by following statements when executed one after another?

• cout<<“welcome\nto\nc++”;

• cout<<“How are you”;

• cout<<endl;

Page 71: C++ Fundamentals

• int a =90;

• cout<<“a”;

What are the errors in following statements?

Void main()

{

Cout<<“Enter a”;

Cin>>a;

}

Page 72: C++ Fundamentals

• void main()

• {

• a int;

• b char;

• a,b int

• }

Page 73: C++ Fundamentals

Downloaded

From www.classnotesmit.blogspot.com

7/5

/20

14

Dep

t o

f C

.S.E

76