Sei sulla pagina 1di 38

CSC-113

COMPUTER PROGRAMMING

LECTURER :AMNA IFTIKHAR


EMAIL ADDRESS:
amnaiftikhar.bukc@bahria.edu.pk
omer.amna@gmail.com
Course link:
https://sites.google.com/view/amnaiftikhar
C++ Fundamentals
LECTURE OUTLINE

 Fundamentals of C++
 Structure of C++ Program C++
 Data types
 Variables
 Escape Sequences
 I/O Statements (cin/cout)
STRUCTURE OF A C++ PROGRAM

Opening brace

Closing brace

Opening brace

Closing brace
5
PREPROCESSOR DIRECTIVES
 A libraries that contain /* A program to print the string
functions and symbols that are Welcome to C++ to the screen
necessary to run a C++ */

program. #include <iostream>

 Every library has a name and is int main()


referred as a header file. {
/* print out the message */
 All preprocessor commands cout<<"Welcome to C++"<<endl;
begin with #. return 0;
}
 In Standard C++, header files
have the file extension .h
 There is no semicolon at the
end of these commands. #include <headerFileName>

 The general syntax to include a


#include <iostream.h>
header file
PREPROCESSOR DIRECTIVES

 Another option to use to perform /* A program to print the string


I/O in a program: Welcome to C++ to the screen
*/
#include <iostream>
equivalent
#include <iostream>
#include <iostream.h> using namespace std;

int main()
 To use the string data type in a
{
program, your must include the
/* print out the message */
following preprocessor directive:
cout<<"Welcome to C++"<<endl;
#include <string> return 0;
 The descriptions of some very }
useful mathematics functions such
as power, absolute, sine, etc., are
contained in the header file
cmath.
#include <cmath>
NAMESPACE

 A container for a set of identifiers (also known as symbols, names)


 The built in C++ library routines are kept in the standard namespace
 The statement:
using namespace std;
 pulls everything defined in the std namespace into the global namespace, as if it had not
been defined inside a namespace at all. This makes it more convenient to access things
that are defined in the std namespace, without having to use the scope resolution
operator to qualify them. So, instead of having to say:
std::cout << myValue << std::endl;
 you can just say:
cout << myValue << endl;

8
THE PROGRAM PART: THE HEADING

The heading part has the following form


 Every C++ program has a function
main.
typeOfFunction main(argument list)
 The basic parts of the function main
are:
1. The heading
2. Body of the function int main()
{
/* print out the message */
cout<<"Welcome to C++"<<endl;
return 0;
}
 The statement

int main(void) int main()


means that the function main equivalent It is not necessary to put word
returns a value of the type int the void in parentheses, but
and it has no arguments. the parentheses are still
needed.
THE PROGRAM PART: BODY OF THE FUNCTION
 The body of the function is enclosed
between { and } and has two types of int main()
statements. {
 Declaration Statements /* assignment statements */
int a, b, c; int a = 10;
int b = 2;
double x, y; int c;
Variables (or identifies) can be int sum;
declared anywhere in the program,
but they must be declared before
they can be used. /* print out the message */
cout<<"Welcome to C++"<<endl;
 Executable Statements
// input statement
a = 10; cin>>c;
//assignment statement sum=a+b+c;
/* output statement */
cin>>c;
cout<<sum<<endl;
//input statement
cout<<a+b+c<<endl; return 0;
//output statement }
COMMENTS

 Multiple line comments are


enclosed between /* and */ /* A program to print the string
Welcome to C++ to the screen
 Single line comments begin
*/
with //
#include <iostream>
 Statements that have no using namespace std;
effect on the execution of
int main()
the program
{
 The Compiler neglects these // print out the message
comments when translating cout<<"Welcome to C++"<<endl;
the program to machine return 0;
code
}
 Comments can be place
before each of the functions
Output:
and inside the function
Welcome to C++ Programming
THE HELLO WORLD PROGRAM
Indicates the beginning of the
functions body  < iostream> is included
in this program because it
#include <iostream> provides information to the
using namespace std; compiler about cout
int main (void) function
{
cout<<“hello world\n”; Block
 cout is a function from a
return 0; standard library that prints
} on the screen

End of function’s body 0 is returned to the OS when


main is terminated

 The string “hello world\n” is sent to the cout function and the
function will display the message on the screen
 The \n that appears in the cout function call will cause the message
to be printed on the screen then moves the printing to the next line
SYNTAX

 A programming language is a set of rules, symbols, and special words used


to construct a program.

 There are rules for both syntax (grammar) and semantics (meaning).
 Syntax: The formal rules governing how one writes valid
instructions in a language

 Semantics: The set of rules that gives the meaning of


instructions written in a programming language.

 The syntax rules tell us which statements (instructions) are legal, that is,
accepted by the programming language and which are not.
TOKEN
 The smallest individual unit of a program written in any language is called a token.

 A token is the basic vocabulary of the language.

 Tokens in C++
 keywords
 identifiers
 constants
 string constants
 operators
 punctuators

 Language syntax specifies the valid combinations of tokens in the language into legal
strings.
TOKEN TYPES

 Identifiers
main, payRate, score_1, conversion

 Operators
+ - * / ( )

 Keywords
int, float, double, char, void, return

 Punctuators
. ; ? , {

 Others
<= != == >=

 Comments are not tokens (remember they are removed from the program)
IDENTIFIERS

 Identifiers allow us to name variables, constant names, functions and


objects in the program
 Each piece of data in the computer is stored at a unique memory address
 Identifier names allow us to symbolically deal with the memory locations so
that we don’t have to deal directly with these addresses
 A C++ identifier are formed using the following symbols
 Capital letters A to Z
 Small letters a to z
 Digits 0 to 9
 Underscore _ “shift key with minus key in the keyboard”
IDENTIFIERS A Syntax diagram of the identifier
 Rules to form and Identifier
 First character must be an alphabet
Letter
or an underscore
 Can consist of alphabets, digits and Letter digit
underscore
underscore underscore
 C++ is case sensitive language

Some of the predefined identifiers are cout and cin.


Unlike reserved words, pre-defined identifiers may be redefined, but it would
not be wise to do so.

Valid Identifiers Invalid Identifiers

A _a a123
ABcDf99_ sum average 1a_a a+2 a$1
Mark1 Mark_2 xy_1_4
A”bc -abc aa.bb
Sum_of_values avg_plus_sum
A abc a9!c
these are not the same
Why they are invalid ?.
Aa aa aA AA aa
KEYWORDS (reserve words)

 Keywords are words (like identifiers) that have a special meaning


to the compiler and cannot be used in your programs for other
purposes.

auto do goto signed unsigned


break double if sizeof void
case else int static volatile
char enum long struct while
continue extern register switch
default float return typedef
for short union const
DATA TYPE

 A set of values together with a set of operations is called a


data type.

C++’s Data Types


 C++ data types fall into three categories
 Simple Data Type.
Simple Structured Pointers
 Structured Data Type.
 Pointers.
Integral Floating-Point Enumeration
Simple Data Type

 C++ simple data can be classified into three categories


1. Integral, which is a data type that deals with integers, or numbers
without a decimal part.
2. Floating-point, which is a data type that deals with decimal numbers.

3. Enumeration type, which is a user-defined data type.

Simple Data Type

Integral Floating-Point Enumeration


THE INT DATA TYPE
 The type defines the size of the field in which
data can be stored
-6728, -67, 0, +78, 36782, ...
 C++ language supports three different types
of integer data type.

short int Int 2 long int


2 bytes or 4 bytes 4 bytes

The bool Data Type


 The data type bool has two values, true and
false. The central purpose of this data type
is to manipulate logical (Boolean) expressions.

 In C++, bool, true, and false are reserved


words.
FLOATING – POINT DATA TYPES

float: The data type float is used in C++ to represent any real number
between -3.4E+38 and 3.4E+38.The memory allocated for the float data
type is 4 bytes.

double: The data type double is used in C++ to represent any real number
between -1.7E+308 and 1.7E+308.The memory allocated for the double
data type is 8 bytes.

 On most newer compilers, the data types double and long double are
the same.
 The maximum number of significant digits—that is, the number of decimal
places—in float values is 6 or 7 and double is 15.

Floating-Point Data Type

float double long double


THE CHAR DATA TYPE
 To the computer, a character is any value that can be represented in the
computer’s alphabets
 Most computers use American Standard Code for Information Interchange
(ASCII) as computer alphabets
 A character requires one byte for the representations (28=256 characters,
extended ASCII table shown next slide)
 Characters are stored in memory as numbers (ASCII number)

Valid character literals (ASCII values) Invalid character literals


‘A’=65,‘B’=66,‘C’=67, … “a” a
‘a’=97,‘b’=98,‘c’=99, … ‘ab’ ‘a11111’
‘0’=48,‘1’=49,‘2’=50, … Why ?
THE STRING TYPE
 The data type string is a programmer-defined type and is not part of the C++
language. The C++ standard library supplies it.
 A string is a sequence of zero or more characters.
 Strings in C++ are enclosed in double quote marks.
 A string with no characters is called a null or empty string.
Null or empty string

Valid string constants Invalid string constants


“” ‘ mary’ Use single quotes for
“mary” “ hgshd hfd h” jsdjasdhajdk” character constants
and Double quotes
“Hello world\n” for strings
“How are you John?” How to fix the problem?
“I have #1 pc costs 15$”
“……………….”
“\n\t\r\r\r\t\thi *&^%$%$###”
CONSTANTS AND VARIABLES

 Storing data in the computer’s memory is a two step process.


 Instruct the computer to allocate memory.
 Include statements in the program to put data into the
allocated memory.

 Allocating Memory with Constants and Variables


 Named Constant: A memory location whose content is not
allowed to change during program execution.
 Variable: A memory location whose content may change during
program execution.
NAMED CONSTANT
 The syntax to declare a named constant is

const dataType identifier = value;

const double conversion = 2.54;


 This mean that conversion has a value of 2.54 and cannot be changed throughout
the program execution.
 In C++, const is a reserved word.

int main ()
{
const int noOfStudents = 20;
const char blank = ' ';
const double payRate = 15.75;
return 0;
}
VARIABLES

 Variables don’t have fixed values


throughout the program dataType identifier;
 In C++ language there are a set of
operations to change and manipulate
the value stored in these variables int conversion = 2.54;
 Every variable used in the program
must be declared before its use
= Literal
 Variable names are valid identifiers and
cannot be the same as any of the
reserved words (keywords) type identifier ;
 When variables are created there is a
need to assign them initial values ,
 In order to do that an assignment
operator is used (=)
int sum =
0;
INPUT AND OUTPUT FUNCTIONS IN C++ LANGUAGE
 C++ uses two functions for formatted input/output
 cin reads data from the keyboard and stores it to a buffer
 cout prints out data to the monitor

 Keyboard is known as the standard input device (stdin).


 The monitor is known also as the standard output device (stdout)

cin>>…

cout<<…
INPUT (READ) STATEMENT: CIN Output : cout
 The syntax of cout together with <<
 Syntax of cin together with is
>>:
cout<< variable;
cin>>variable;
 In C++, << is called the insertion
 In C++, >> is called the operator.
extraction operator.  expression is evaluated and its
Suppose miles is a variable value is printed at the current
of the type double. cursor position on the screen.
 manipulator manipulates the
The statement output. The simplest manipulator is
cin>>miles; endl (the last character is the letter
el), which causes the cursor to
move to the beginning of the next
causes the computer to get a line.
value of the type double and
 Strings and expressions involving
place it in the memory cell only one variable or a single value
miles. are evaluated to itself.
OUTPUT : COUT
Statement Output
1. cout<<29/4; 7
2. cout<<"Hello there. "; Hello there.
3. cout<<12; 12
4. cout<<"4+7"; 4+7
5. cout<<4+7; 11
6. cout<<"A"; A
7. cout<<"4 + 7 = "<<4 + 7; 4 + 7 = 11
8. cout<<2+3*5; 17
9. cout<<"Hello \nthere. "; Hello
there.
 \n is called new line escape sequence.
 \ (back slash) is called the escape character.
USE OF BLANKS, SEMICOLONS, BRACKETS AND COMMAS

 In C++, one or more blanks are used to separate numbers when data is input.
 Blanks are also used to separate reserved words and identifiers from each other
and other symbols.
int a,b,c;
int a, b, c;
The blanks between the identifiers in the second statement
are meaningless.

inta,b,c;
no blank between the t and a changes the reserved word
int and the identifier a into a new identifier inta.

 Commas are used to separate items in a list.


 All C++ statements terminate with a semicolon  statement terminator
 Brackets{ and } are not C++ statements.
NAMING IDENTIFIERS

const double a = 2.54; //conversion constant


double x; //variable to hold centimeters
double y; //variable to hold inches

x = y * a;
Consider the following
const double conversion = 2.54;
double centimeters;
double inches;

centimeters = inches * conversion;

 Run-together-word
inchperfoot inchPerFoot inch_per_foot.
PROMPT LINES

cout<<"Please enter a number between 1 and 10 and"


<<" press ENTER"<<endl;
cin>>num;

When these two statements execute in the order given, first the cout statement causes
the following line of text to appear on the screen:

Please enter a number between 1 and 10 and press ENTER

After seeing this line, users know that they must enter a number and press the return key.
ESCAPE SEQUENCE

Escape
Description
sequence
\' single quote
\" double quote
 Escape sequences are used to
\? question mark
represent certain special
\\ backslash
characters within string \a audible bell
literals and character literals. \b backspace
\n line feed - new line
\r carriage return
\t horizontal tab
Examples
35
MORE ABOUT COUT

 precision (int) sets the number of significant digits of float type


numbers

float y = 23.1415;
cout.precision(1);
cout << y << '\n'; // Outputs 2e+01
cout.precision(2);
cout << y << '\n'; // Outputs 23
cout.precision(3);
cout << y << '\n'; // Outputs 23.1
SUMMARY

 The body of the function is enclosed between { and } and has two types of
statements.
 Statements enclosed in // have no effect on the execution of the program.
 Identifiers allow us to name variables, constant names, functions and objects in the
program.
 C++ data types fall into three categories: Simple Data Type. ,Structured Data Type.,
Pointers
 Named Constant: A memory location whose content is not allowed to change
during program execution.
 Variable: A memory location whose content may change during program execution.
 cin reads data from the keyboard and stores it to a buffer
 cout prints out data to the monitor
 In C++, >> is called the extraction operator
 In C++, << is called the insertion operator 37

Potrebbero piacerti anche