0% found this document useful (0 votes)
43 views37 pages

Syntax Construction of C++ Program: LO2. Data Types

The document discusses the syntax and construction of C++ programs. It covers basic syntax elements like characters, comments, and identifiers used in C++. It also discusses data types, constants, variables, and how to declare variables in C++ programs. A simple C++ program example is provided that calculates the area of a circle.

Uploaded by

Hirdesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views37 pages

Syntax Construction of C++ Program: LO2. Data Types

The document discusses the syntax and construction of C++ programs. It covers basic syntax elements like characters, comments, and identifiers used in C++. It also discusses data types, constants, variables, and how to declare variables in C++ programs. A simple C++ program example is provided that calculates the area of a circle.

Uploaded by

Hirdesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

LO2.

Data Types, Syntax


construction of C++ program

1
Syntax
1. Characters used:
• Upper- and lower-case letters
• Numbers from 0 to 9
• Various punctuation marks
• White space: space, tab, newline, form feed

2. Comments
• Comments can be used anywhere where a blank or newline are allowed.
• Block comments are delimited by / * and * / . Comments are not
nested.
• A single-line comment (introduced in the standard C99) can begin with
the character / / and end at the end of the line

3. Identifiers
• Identifiers are employed as names of variables, functions, and data
types.
• Upper- and lower-case letters, digits, and the underscore_ character
can be used in identifiers. The first character cannot be a digit.

2 2
LO2. Data Types,
Constants and Variables

3
Data types
Name Description Size* Range*
char Character or small 1 byte signed: -128 to 127
integer unsigned: 0 to 255
short int Short integer 2 bytes signed: -32768 to 32767
(short) unsigned: 0 to 65535
int Integer 4 bytes signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
long int Long integer 4 bytes signed: -2147483648 to
(long) 2147483647
unsigned: 0 to 4294967295
float Floating point number 4 bytes 3.4e +/- 38 (7 digits)

double Double precision 8 bytes 1.7e +/- 308 (15 digits)


floating point number
long double Long double precision 8 bytes 1.7e +/- 308 (15 digits)
floating point number

4
Program mostly a collection of
Hello World Program in C++ functions
“main” function special: the entry point
#include <iostream> “int” qualifier indicates function returns
an integer.
Using namespace std; The value returned by main() indicates
whether our program is successful. By
int main() convention, main() returns 0 to
indicate success. A nonzero return
{ value indicates something went wrong
cout << “Hello, world!”;
return 0;
}
Indicates program ends
Cout is the standard and returns 0
output stream to print
“Hello, World” on monitor

5 5
Variables

• A variable is a name that represents one or more


memory locations used to hold program data
• A variable may be thought of as a container that can
hold data used in a program
• To use a variable, we have to declare a name and type
of memory allocation in this declaration

5
int myVariable;
myVariable = 5; myVari
able

6 6
Variable types

Local variable
Local variables are declared within the body of a function, and can only be
used within that function.

Static variable
Another class of local variable is the static type. It is specified by the keyword
static in the variable declaration.
The most striking difference from a non-static local variable is, a static variable
is not destroyed on exit from the function.

Global variable
A global variable declaration looks normal, but is located outside any of the
program's functions. So it is accessible to all functions.

7
An example
int global = 10; //global variable

int main (int x)


{
static int stat_var; //static local variable
int temp; //(normal) local variable
int name[50]; //(normal) local variable
……
}

8
Variables using fundamental Data Types

Boolean (bool): used to store two pieces of conditional data only – true or false

Character (char, wchar_t, char16_t and char 32_t): used to store a number
with a decimal

Floating point (float, double and long double): used to store a number with a
decimal

Integer (short, int, long and long long): used to store whole number

No data (void): placeholder to represent no data

9
Variables

• Variables are names for storage locations in memory

15 Data Memory (RAM) 0

int warp_factor; 41

char first_letter; ‘A’

5.74532370373175
float length; × 10-14

10 10
Variables

• Variable declarations consist of a unique identifier


(name)…
15 Data Memory (RAM) 0

int warp_factor; 41

char first_letter; ‘A’

5.74532370373175
float length; × 10-14

11 11
Variables

…and a data type


Determines size and how values
are interpreted 15 Data Memory (RAM) 0

int warp_factor; 41

char first_letter; ‘A’

5.74532370373175
float length; × 10-44

12 12
Identifiers

• Names given to program variables


• Valid characters in identifiers:

Identifier
First Character Remaining Characters
‘_’ (underscore) ‘_’ (underscore)
‘A’ to ‘Z’ ‘A’ to ‘Z’
‘a’ to ‘z’ ‘a’ to ‘z’
‘0’ to ‘9’
• Case sensitive!
• Only first 31 characters significant
13 13
Variables
How to Declare a Variable?
Syntax

type identifier1, identifier2,…,identifiern;

• A variable must be declared before it can be used


• The compiler needs to know how much space to allocate
and how the values should be handled
Examples

int x, y, z;
float warpFactor;
char text_buffer;
unsigned index;

14 14
Variables
How to Declare a Variable?

Variables may be declared in a few ways:


Syntax

One declaration on a line


type identifier;

One declaration on a line with an initial value


type identifier = InitialValue;

Multiple declarations of the same type on a line


type identifier1, identifier2, identifier3;

Multiple declarations of the same type on a line with initial values


type identifier1 = Value1, identifier2 = Value2;
15 15
Variables
How to Declare a Variable

Examples

int x;
int y = 12;
int a, b, c;
long int myVar = 12345678;
long z;
char first = 'a', second, third = 'c';
float big_number = 6.02e+23;

16 16
Classes

• A class is a collection of related variables and


associated functions intended to work with variables.
• A new data type is declared by a “Class”, similar to
declaration of a structure.

17 17
A Simple C++ Program
Preprocessor Header File
Directives
This library supports
input/output of data from/to files
#include <iostream> for built-in data types.
Using namespace std;

int main(void)
{
float rad, area_circle, PI; Variable Declarations

//Calculate area of circle Comment


Cout << “Enter radius of Circle:”;
Function Cin >> rad;
PI = 3.1416;
Overload area = PI * rad * rad;
Operator Cout<< “Area of circle with radius”
<< rad << “is: ” <<
area_circle;
18 } 18
Input/Output
C++ standard library is the “iostream” library.
Input operations are supported by the class
“istream” and output operations by “ostream”.

In the library iostream, the following streams


are defined:
 cin – the object of the class istream that corresponds to the standard
input (keyboard);
 cout – the object of the class ostream that performs the standard
output (display);
 cerr – the object of the class ostream that implements the standard
output of errors.

19
Input/Output
The general syntax is
cout << (“format”, variables);

To work with C++ files, header file iostream:


#include <iostream>

An example
int stud_id = 5200;
char name[20] = “Mike”; // array discussed in
LO4
cin >> (“%s ‘s ID is %d \n”, name, stud_id);

20
Input and output in C++
Format Identifiers
%d decimal integers
%x hex integer
%c character
%f float number
%lf double number
%s string
%p pointer
%e decimal exponent

How to specify display space for a variable?


cin >> (“The student id is %5d \n”, stud_id);
The value of stud_id will occupy 5 characters space in the print-out.

21
Why “\n”
It introduces a new line on the terminal screen.
escape sequence

\a alert (bell) character \\ backslash


\b backspace \? question mark
\f formfeed \’ single quote
\n newline \” double quote
\r carriage return \000 octal number
\t horizontal tab \xhh hexadecimal number
\v vertical tab

22
(Standard Libraries

Work with time:


ctime of the C++ standard library should be included
Function time (null) gets the current time
Function ctime returns time as a string: weekday, month, day,
time (hour, minutes, seconds) and year

Common Fucntions:
The C++ standard library (stdlib. h in C++)

23
(Standard Libraries

Declaration:
Variables can be declared anywhere within a block before use.
It defines type and name of a variable. Below are some
standard declarations.

extern int i;
char *strchr( const char *Str, const char Target );

Example:
int a, result;
result = scanf("%d", &a);

24
scanf() in C++
#include <iostream>
#include <cstdio>
main() {
Is a function in C which allows the int pin;
programmer to accept input from a cout << ("Please type in your PIN\
keyboard. This function is also used n");
in C++. The following program scanf("%d",&pin);
illustrates the use of this function. cin >> ("Your access code is %d\
n",pin);
Return 0;
}

What happens in this program? An integer called pin is defined. A prompt to enter in a number is then
printed with the first cout statement. The scanf routine, which accepts the response, has a control string
and an address list.
In the control string, the format specifier %d shows what data type is expected.
The &pin argument specifies the memory location of the variable the input will be placed in. After the
scanf routine completes, the variable pin will be initialized with the input integer. This is confirmed with the
second cin statement. The & character has a very special meaning in C++. It is the address operator.

25
Reading and Writing Strings
Example: The following example shows the usage of scanf() function to read strings.
Note: in scanf, we do not use & with array names

#include <iostream> String header file


#include <string>

int main() Declaring string


{
char str1[20], str2[30];

cin >> "Enter name: "; reading string


cout << "%s", str1 ;

cin >> "Enter your website name: ");


cout <<("%s", str2); Enter name: admin
Writing string
Enter your website name:
cout << "Entered Name: %s\n", str1); www.tutorialspoint.com
cout << "Entered Website:%s", str2); Entered Name: admin
return 0;
26
}
Arithmetic Operations
Operator Operation Example Result

* Multiplication x*y Product of x and y


/ Division x/y Quotient of x and y
% Modulo x%y Remainder of x divided by
+ Addition x+y y
Sum of x and y
- Subtraction x-y Difference of x and y
+ (unary) Positive +x Value of x
- (unary) Negative -x Negative value of x

NOTE - An int divided by an int returns an int:


10/3 = 3
Use modulo to get the remainder:
10%3 = 1

27 27
Arithmetic Assignment Operators

28
Relational Operations
Operator Operation Example Result (FALSE = 0, TRUE ≠ 0)

< Less than x<y True if x less than y, else false


Less than or True if x less than or equal
<= x <= y
equal to to y, else false
> Greater than x > y True if x greater than y, else
false
Greater than True if x greater than or
>= x >= y
or equal to equal to y, else false
== Equal to x == y True if x equal to y, else
!= Not equal to x != y false
True if x not equal to y,
else false

29 29
Increment and Decrement Operators

awkward easy easiest

x = x+1; x += 1 x++

x = x-1; x -= 1 x--

30
Example Arithmetic operators
int i = 10;
int j = 15;
int add = i + j; //25
int diff = j – i; //5
int product = i * j; // 150
int quotient = j / i; // 1
int residual = j % i; // 5
i++; //Increase by 1
i--; //Decrease by 1

31
Example Comparing them The Answer
int i = 10; j / i = 1;
int j = 15; j % i = 5;
float k = 15.0; k / i = 1.5;
k % i It is illegal.
j/i=?
j%i=? Note: For %, the operands
k/i=? can only be integers.
k%i=?

32
Logical Operations

What is “true” and “false” in C++


In C++, there is no specific data type to represent
“true” and “false”. C++ uses value “0” to represent
“false”, and uses non-zero value to stand for “true”.

Logical Operators
A && B => A and B
A || B => A or B
A == B => Is A equal to B?
A != B => Is A not equal to B?

33
Logical Operations

A > B => Is A greater than B?


A >= B => Is A greater than or equal to B?
A < B => Is A less than B?
A <= B => Is A less than or equal to B?

Don’t be confused
&& and || have different meanings from & and |.
& and | are bitwise operators.

34
OPERATOR PRECEDENCE
Precedence and Associativity of C++ Operators
Symbol Type of Operation Associativity
[ ] ( ) . –> postfix ++ and postfix –– Expression Left to right
prefix ++ and prefix –– sizeof &   *   + – ~
Unary Right to left
!
typecasts Unary Right to left
* / % Multiplicative Left to right
+ – Additive Left to right
<< >> Bitwise shift Left to right
< > <= >= Relational Left to right
== != Equality Left to right
& Bitwise-AND Left to right
^ Bitwise-exclusive-OR Left to right
| Bitwise-inclusive-OR Left to right
&& Logical-AND Left to right
|| Logical-OR Left to right
? : Conditional-expression Right to left
= *= /= %= 
Simple and compound
+= –= <<= >>= &= Right to left
assignment
^= |=
35 , Sequential evaluation Left to right35
Some practices
Compute the value of the following logical expressions?

int i = 10; int j = 15; int k = 15; int m = 0;


if( i < j && j < k) =>
if( i != j || k < j) =>
if( j<= k || i > k) =>
if( j == k && m) =>
if(i) =>
if(m || j && i ) =>

36
Answers
int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) => false
if( i != j || k < j) => true
if( j<= k || i > k) => true
if( j == k && m) => false
if(i) => true
if(m || j && i ) => true

37

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy