Você está na página 1de 55

Introduction to C++

C vs C++ !!!!? Homework (1)


1.C++ supports (almost) all the features of C. Like C, C++ allows programmers to
manage the memory directly, so as to
develop efficient programs.
1.C++ is OO. C++ enhances the procedural-oriented C language with the object-
oriented extension. The OO extension
facilitates design, reuse and maintenance for complex software.
2.Template C++. C++ introduces generic programming, via the so-called template.
You can apply the same algorithm to
different data types.
3.STL. C++ provides a huge set of reusable standard libraries, in particular, the
Standard Template Library (STL).
C++ Program Basics
Program must be written according to program language rules
Syntax rule o program checked by compiler.
C++ program:
Homework (2)
- Collection of statements. - Metalanguage !!!!?
- Subprogram : some statement grouped to do a purpose within the program.
- Collection of one or more subprograms--called functions
- Function when invoked, carry out some task.
- A C++ program written within a function called main function ,where other may written outside this function.

Source code editor


Program creation

Loader

Running Program
.cpp / .h

compiler

Include : files, library , replace symbols Processing (CPU)

linker

.exe file OUTPUT


BASIC STRUCTURE OF A C++ PROGRAM
#include<iostream.h>
void main()
{
clrscr();

write your code program here

getch();
}

AAKASH KAUSHIK 9891983083,9289817971


Structure of a C++ program
output
# include <iostream>
GS200 welcom
void main ()
{
clrscr();
cout<<GS200 welcome!;
getch();
}
Header file are the predefined files in the
C++ library,iostream.h stands for Input
# include <iostream> Output Stream,It contains functions
#include <conio.h> related to input and output.
void main () conio.h: stands for Console Input Output .
It contains functions related to Console
{
screen .
clrscr(); input and output, The output screen of
cout<<GS200 welcome!; C++ is called Console Screen.
getch(); Main function: Actual execution of a
} program starts from main method.

Clear the whole window screen


Wait the user to press any key to Display a string GS200
close the output window welcome on screen
C++ CHARACTER SET
Characters A-Z, a-z.
Digits 0-9.
Special Symbols {} [] () ; : < > ? & # ~ | \ / etc.
White spaces, new line characters .
Besides all these C++ has 256 ASCII characters.

ASCII- American Standard Code for Information Interchange

AAKASH KAUSHIK 9891983083,9289817971


C++ data type x= 5
ali mohaned sasi = 5 + x

Multiple data type . (why ) ?????

- C++ provides various collection o datatypes , characters , integers ,


float ,.
- C++ also , have ability to define new data type.
-
Basic data type

Integer Float Void bool


C++ data type x= 5
ali mohaned sasi = 5 + x
Integer variable hold non-fractional numbers
Integer (ex: 4 ,654,1 ,0, -5 , -100 , ).
1-unsigned char x ;
Characters may include letters, digits and punctuation
2- unsigned short m;
character, i.e. a and @ etc ?????
3- unsigned int z;
A blank space is a character and is written ' ', with
4- unsigned long avg;
a space left between the single quotes
5- unsigned long long KL;
all integer variable by default are signed .
Float
Each integer variable has a valid range. 1- char 1 Byte
valid range determined by the # of bits , and signed/
0 to 255 or +127 to -128
Basic data type

unsigned
2- short 2 Byte
1- char x ;
0 to 65,535 or -32,768 to 32,767
2- short m; // preferred
short int y; // valid
3- int 2 Byte
Void
3- int z; 4- long 4 byte
0 to 4,294,967,295 or
4- long avg; // preferred -2,147,483,648 to 2,147,483,647
long int sum; // valid 5- Long long 8 byte
5- long long KL; // preferred
long long int c;// valid
bool
0 to 18,446,744,073,709,551,615 or -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
C++ data type
Integer
Floating variable hold fractional numbers
(real number), and very large number
(floating variable has three types.
Floating
1- float x ; Range: -3.4E+38 to 3.4E+38 (four bytes)
2- double m; Range: -1.7E+308 to 1.7E+308 (eight bytes)
Basic data type

3- long double z; Range: same as double and more ( 8 ,12


byte)
Void

bool
C++ data type
Integer

Are used as return type for functions that do not


Floating
return any value.
Basic data type

used when program or calculation does not


require any value but the syntax needs it.
Void

bool
C++ data type
Integer

Two values: true and false


Floating Manipulate logical (Boolean) expressions
true and false are called logical values
Basic data type

Void

bool
string Type
Sequence of zero or more characters
Enclosed in double quotation marks
Null: a string with no characters
Each character has relative position in string
Position of first character is 0
Length of a string is number of characters in it
Welcome GS200 " is a string ,and its length is14

15
Comments

Comments are for the reader, not the compiler


Two types:
Single line
// This is a C++ program. It prints the sentence:
// Welcome to C++ Programming.

Multiple line
/*
You can include comments that can
occupy several lines.
*/

16
Arithmetic Operators and Operator Precedence
C++ arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulus operator
All operations inside of () are evaluated first
*, /, and % are at the same level of precedence and are evaluated next
+ and have the same level of precedence and are evaluated last
When operators are on the same level
Performed from left to right (associativity)
3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) 6) + ((2 * 5) / 4 )) + 6 17
Expressions
If all operands are integers , then its called an integral expression
Produces an integral result Ex: 2 + 3 * 5

If all operands are floating-point , then its called a floating-point


expression
Produces a floating-point result Ex: 12.8 * 17.5 - 34.50

Mixed expression contains integers and floating-point


- 2 + 3.5
- 6 / 4 + 3.9
- 5.4 * 2 13.6 + 18 / 2

18
IDENTIFIERS Variables
ARE THE NAMES GIVEN BY THE PROGRAMMER TO DIFFERENT variables
It can contain characters(A-Z, a-z),Digits(0-9), & only one special symbol called
underscore(_).
First letter must be a character (A-Z, a-z) or underscore(_).
No commas or blank spaces allowed.
Upper case and Lower case characters are different.

Variable decleration
Variables are used to store values that can be changed during the program
execution.

x=5 ; // x is the identifier , and 5 is the initial value assigned to x


average =0 ; ..
AAKASH KAUSHIK 9891983083,9289817971
Reserved Words
Reserved word cant used as identifier
such as ::
int
float
double
char
const
void
Return
cin
cout
Constant
CONSTANTS WHOSE VALUES DONT CHANGE DURING THE PROGRAM
EXECUTION.
Constants and variables must be declared before they can be used.
A constant declaration specifies the type, the name and the value of
the constant.
const <type> <identifier> = <expression>;
Examples:
const int number = 7.8;
const long double zxy= 4534565.5533;
Variable declarations
Variables are used to store values that can be changed
during the program execution.
< type > < identifier >;
< type > < identifier > = < expression >;
Examples:
int sum;
int total = 3445;
char answer = 'y';
double temperature = -3.14;
Basic Input / Output
Standard output (cout)
cout<< exp1;
cout<< exp1<<exp2<<exp3;

- cout << "Output sentence"; // prints Output sentence on screen


- cout << 120; // prints number 120 on screen
- cout << x; // prints the value of x on screen

- cout<< output sentence<< 120<<x;


Basic Input / Output

Standard input (cin)


cin>>exp1;
cin>>exp1>>exp2 >>exp3;

- int a ;
float b ,c ;
cin>>a >>b;
cin>>c ;
Example -6
// Addition program for two integers c=a+b
# include <IOstream.h>
# include <conio.h>
Void main()
{
int a,b,c; /* Declaration */
cout<<("Enter the value of A: ");/* Prompt */
cin>>a; /* Read a */
cout<<("Enter the value of B: ");/* Prompt */
cin>>b; /* Read b */
c=a+b; /* c=a+b */
cout<<("The value of C is",c);
//Print the result
getch();

}
Example -7 :: what is the output o the following program ?
# include < iostream.h >
Void main()
{
int p,q,r,x;
p=2;
q=6;
r=p + q / p;
x=( p + q ) / p;
cout<<"r = "<<r<<"\n x = <x<<"\n";// \n means move to new line
}
MANAGING CONSOLE I/O
OPERATIONS
Escape character
FORMATTED I/O OPERATIONS
C++ supports a number of features which can be used for formatting
the output. These features include :-

ios class functions


Manipulators
User-defined Manipulators

Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008


ios format functions
Function Task
Width() To specify the required field size for displaying the
output value
Precision() To specify the digits to be displayed after decimal point
of a float value
Fill() To specify a character that is used to fill the unused
portion of a field
Setf() To specify format flags that can control the form of
output display
Unsetf() To clear the flags specified

Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008


MANIPULATORS

MANIPULATORS Equivalent ios function


setw() width()

setprecision() precision()

setfill() fill()

setiosflags() setf()

resetiosflags() unset()
Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008
Setting Width : width()

Example-8
cout.width(5);
cout<<543<<12<<\n;
//cout<<setw(5)<<543<<12<<\n; 5 4 3 1 2

cout.width(5);`
cout<<543;
cout.width(5);
cout<<12<<\n; 5 4 3 1 2

Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008


Example-9:
#include<iostream.h> for(int i=0; i<4;i++) // for loop
#include<iomanip.h> {
main() cout.width(5);
cout << items[i];
{
cout.width(8); These 8 statement will
int item[4] = {10,8,12,15}; cout << cost[i]; executed 4 times
int cost[4] = {75,100,60,99}; int value = items[i] * cost[i];
cout.width(5); cout.width(15); field width 5 field width 8 field width 15
cout << ITEMS; cout << value <<\n;
cout.width(8); sum =sum + value;
} ITEMS COST VALUE
cout << COST; 10 15 150
cout << \n Grand Total = ;
cout.width(15); cout.width(2); 8 100 800
cout << value<<\n; cout << sum <<\n; 12 60 720
int sum = 0; }
15 99 1485

Grand Total = 3155


Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008
Setting Precision : precision()
cout.precision(3); 1.141
cout<<sqrt(2)<<\n; // sqrt(2) == 2
cout<<3.14159<<\n;
3.142
cout<<2.50032<<\n; 2.5
#include<iostream.h> cout.width(i+1);
Value of pi :
#include<iomanip.h> cout.precision(i); 3.1
void main() cout<<pi<<\n; 3.14
3.143
{ float pi=22.0/7.0; //cout<<setw(i+1)<< 3.1429
// setprecision(i)<<pi<<\n; 3.14286
int I; 3.142857
}
cout<<Value of pi :\n ; }
3.1428571
3.14285707
for(i=1;i<=10;i++) 3.142857075
3.1428570747
{
Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008
Filling fill()

Example-12:

cout.fill(*);
cout.width(10); * * * * * * 5 2 5 0
cout<<5250<<\n;

Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008


Example-13 :
#include<iostream.h> cout<<\n Paddling
#include<iomanip.h> Changed\n\n;
void main() cout.fill(#);
cout.width(15); <<<<1<<<<<<<<<1
{
cout<<12.345678<<\n;<<<<2<<<<<<<0.5
cout.fill(<); <<<<3<<<<<<<0.3
cout.precision(3); return 0; >>>>4>>>>>>0.25
for(int n=1;n<=6;n++) } >>>>5>>>>>>>0.2
{ cout.width(5); >>>>6>>>>>0.167
cout<<n; Paddling Changed
cout.width(10);
cout<<1.0/float(n)<<\n; #########12.346
if(n==3)
cout.fill(>);
} Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008
Formatting Flags, setf()
arg1 - formatting flags defined in the class ios
FORMAT REQUIRED FLAG (ARG1)
Left-justified output ios::left

Right-justified output ios::right

Scientific Notation ios::scientific

Fixed Point notation ios::fixed

Decimal Base ios::dec


Example-14 :
#include<conio.h>
#include<iostream.h>
main()
{
float x=1234.674,y=0.98123334 ;
cout<<x<<endl<<y<<endl;
// Cout<<setiosflags(ios::fixed)<< x; 1234.67
cout.setf(ios::fixed, ios::floatfield); 0.981233
cout<<x<<endl; 1234.668234

1.234672e-01
cout.setf(ios::scientific, ios::floatfield);
x=.123467 ;
cout<<x;

getch();

}
Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008
Example-15:
#include<iostream.h>
#include<iomaniop.h>
void main()
{
int num;
cout<<enter an integer value;
cin>>num;

cout<<The hexadecimal, octal and decimal representation<<num<< is : ;

cout.setf(ios::hex, ios::basefield)
cout<<num<<, ;
Enter an integer value : 92
cout.setf(ios::oct, ios::basefield)
The hexadecimal, octal and decimal representation of 92 is: 5c, 134 , and 92
cout<<num<<, ; respectively.

cout.setf(ios::dec, ios::basefield)
cout<< and <<num<< respectively.;
}
Namita Pandey 2011BTechece020 . Shiva Johari 2011BTechcse015 . Pritam Kalwaniya 2011BTechcse008
Intput character function cin.get(char)

An alternative to the >> operator is the get() function, a member of the istream class

The get() function reads and stores the next character in the input stream, skipping
nothing in other words, it reads white space

Example:
char c;
cout << Enter a character: ;
cin.get(c); // reads the character entered
cout << You entered: << c << endl;
Output character function cout.put(char)
Member function of the ostream class
Used to output single chars

Examples
cout.put( 'A' );
Char ch=z;
Cout.put(ch);
cout.put( 65 ); //Using the ASCII value
Character Strings

A sequence of characters is often referred to as a character string.


A string is stored in an array of type char ending with the null character '\0 '.

A string containing a single character takes up 2 bytes of storage.


Character Strings
Character vs. String
A string constant is a sequence of characters enclosed in
double quotes.
For example, the character string:
char s1[2]="a"; //Takes two bytes of storage.
s1: a \0

On the other hand, the character, in single quotes:


char s2= `a`; //Takes only one byte of storage.
s2: a

Character vs. String


Example:
char *message1 =hello world;
cout<<message1<< endl;

char message2[12] = "Hello world";


cout << message2 << endl;

message2: H e l l o w o r l d \0

char message3[12];
cin >> message3; // type "Hello" as input

message3: H e l l o \0 ? ? ? ? ? ?
Strings
String can be input using the extraction operator >>, but one or more white spaces indicates
the end of an input string.
Example :
char A_string[80], E_string[80];
cout << "Enter some words in a string:\n";
cin >> A_string >> E_string;
cout << A_string << E_string<< \nEND OF OUTPUT\n";
Output:
Enter some words in a string:
This is a test.
Thisis
END OF OUTPUT
getline
The function getline can be used to read an entire line of input into a string variable.
The getline function has three parameters:
The first specifies the area into which the string is to be read.
The second specifies the maximum number of characters, including the string delimiter.
The third specifies an optional terminating character. If not included, getline stops at \n.
Example :
char A_string[80]; // array of characters
cout << "Enter some words in a string:\n";//80 is the size of A_string
cin.getline(A_string, 80);
cout << A_string << \nEND OF OUTPUT\n";
Output:
Enter some words in a string:
This is a test.
This is a test.
END OF OUTPUT
getline
Example :
char A_string[5], E_string[80];
cout << "Enter some words in a string:\n";
cin >> A_string;
cin.getline (E_string, 9) ;
cout << A_string << "#" << E_string<< \nEND OF OUTPUT\n";

Output:
Enter some words in a string:
This is a test.
This# is a te
END OF OUTPUT
Example: Output example:
#include <string>
#include <iostream> Enter a line of text: This is a test line of text
int main(void) You entered: This is a test line of text
{ Enter a line of text, <space> as the delimiter:
This is another line of text
string str; //must include string
You entered: This
string str1;
string str2;
cout<<"Enter a line of text: ";
getline(cin, str); // cin.getline(str ,xx) -> if str defined as an array of size xx char
str[xx];
cout<<"You entered: "<<str<<endl;
cout<<"Enter a line of text, <space> as the delimiter: "<<endl;
getline(cin, str1, ' ');
cout<<"You entered: "<<str1<<endl;
return 0;
ignore()Member Function\

There is also a way to remove and discard characters from an input stream:
cin.ignore(N, ch);
means to skip (read and discard) up to N characters in the input stream, or until the character ch
has been read and discarded, whichever comes first. So:
cin.ignore(80, '\n');
says to skip the next 80 input characters or to skip characters until a newline character is read, whichever comes first.
The ignore function can be used to skip a specific number of characters or halt whenever a given character occurs:
cin.ignore(100, '\t');
means to skip the next 100 input characters, or until a tab character is read, or whichever comes first.
Example:
Example:
#include<iostream.h>
void main ()
{
char first ;
char last;
cout<<"Enter your first and last :";
firsth = cin.get();
cin.ignore(30,'\n');
last = cin.get();
cout<<"The initials letters are:
"<<first<<endl<<last<<endl;
cin.ignore(30,'\n');
cin.get();
}

Output example:

Você também pode gostar