0% found this document useful (0 votes)
13 views74 pages

Chapter 2 - Basic Programming Constructors

The document discusses fundamentals of computer programming in C++, covering topics like compilation process, program structure, basic elements, debugging, formatting, input/output streams, library functions, preprocessor directives, and namespaces. It provides details on statements, blocks, and the main function in C++ programs.

Uploaded by

Ahmed Yassin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
13 views74 pages

Chapter 2 - Basic Programming Constructors

The document discusses fundamentals of computer programming in C++, covering topics like compilation process, program structure, basic elements, debugging, formatting, input/output streams, library functions, preprocessor directives, and namespaces. It provides details on statements, blocks, and the main function in C++ programs.

Uploaded by

Ahmed Yassin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 74

Fundamentals of

Computer
Programming
Chapter Two
Basic Programming
Constructors
Outline
 Compilation Process and running programs:
 Compiling, Debugging and Linking
 Structure (Anatomy) of C++ program
 Preprocessor and library functions
 main() function
 Statement and Block
 Why C++ programming language

2
Chapter 1
Outline
 Basic Elements of program (Syntax and Semantics)
 Input/output standards
 Variables and Data types
 Constants
 Operators and expression
 Debugging and Programming Errors
 Error types
 Debugging errors
 Formatting Program
 Comment, braces, Indentation and White space
 Formatted Input-Output
3
Chapter 1
Anatomy of C++ program

// sample C++ program comment

#include <iostream> preprocessor directive


using namespace std; which namespace to use

int main() beginning of function named main


{ beginning of block for main
cout << "Hello, there!"; output statement

string literal
return 0; send 0 to operating system Output

Hello, there!

} end of block for main


Structure of C++ Program (cont’d)
 Statements
 Independent unit in a program, just like a sentence in the English
language.
 The individual instructions of a program that performs a piece of
programming action
 It is a fragments of the program that are executed in sequence
 Every C++ statement has to end with a semicolon.
 E.g. input/output statement

 Blocks
 Also called compound statement
 A group of statements surrounded by braces { }.
 All the statements inside the block are treated as one unit.
 There is no need to put a semi-colon after the closing brace to end
a complex statement
 E.ge main() function
5
Chapter 1
Structure of C++ Program (cont’d)
 main () function
 It is where program execution starts in C++
 Every C++ must contain main () function
 The main () function can be made to return a value to the
operating system (the caller)
 The return type is specified by Data type where as the return value
is mentioned by with return keyword.
 The main () function must followed by block i.e. { }

Note
 Instead of using numeric value of zero and non-zero, you can
also use EXIT_SUCESS or EXIT_FAILURE, which is defined in the
cstdlib header (i.e., you need to "#include <cstdlib>".
6
Chapter 1
I/O Streams
 Data stream refers to the flow of data between program and it’s
environment particularly input/output devices.
 Data stream typically exist in the form of characters or numbers

 An input stream is data for the program to use typically originates


at the keyboard
 An output stream is the program’s output. Destination is typically
the monitor.
7
Chapter 1
I/O Streams (cont’d)
 C++ standard OUTPUT Stream (cout)
 cout (console output) is the object to display information on the
computer's screen in C++.

 Syntax: cout<<data;
 The insertion operator "<<" inserts data into cout
 cout is an output stream sending data to the monitor
 data refers to data to be printed which can be literal,
variable, expression or constant.
 More than one data separated by insertion operator can be
sent to screen with single cout output stream.
8
Chapter 1
I/O Streams (cont’d)
 C++ standard INPUT Stream (cin)
 cin (console input) is the object to read data typed at the
keyboard in C++.

 Syntax: cin>>variable;
 cin is an input stream bringing data from the keyboard
 The extraction operator (>>) removes data to be used
 variable refers to memory location where the data will be stored.
 More than one variable separated by extraction operator can
be used to capture data from keyboard with single cin input
stream.
9
Chapter 1
I/O Streams (cont’d)
 Sample program to demonstrate the standard Input/output stream

10
Chapter 1
C/C++ Library Functions and preprocessor
 Library functions also called “built-in” functions
 This are functions that are implemented in C/C++ and ready to be directly
incorporated in our program as per our requirements
 Library functions in C/C++ are declared and defined in special files called
“Header Files” which we can reference in our C/C++ programs using the
“include” directive.
 Some of C/C++ library header files are tabularized as below
Headers Description Functions
This header contains the prototype
iostream for standard input and output cin, cout, cerror, get(), getline() etc.
functions used in C++
sqrt(), pow(base,exponent), exp(x),
This is the header containing
cmath/math fabs(x), log(x), log 10(x), sin(x), cos(x),
various math library functions.
tan(x), asin(x), acos(x), atan(x) etc.
This header contains stream
setw (int n), setfill(char c),
iomanip manipulator functions that allow setprecision(int n) etc.
us to format the stream of data.

11
Chapter 1
C/C++ Library Functions (cont’d)
Headers Description Functions
contains various functions related to conversion abs(x), atof(const char* str), atoi(const
cstdlib between text and numbers, random numbers, char* str), atol(const char* str),
and other utility functions. atoll(const char* str) etc.
Contains function prototypes related to date and
ctime time manipulations in C++. localtime(), clock(), difftime() etc.
Contain function prototypes that test the type of toupper(ch), tolower(ch), isalpha(ch),
characters (digit, alphabet, etc.). It also has
cctype prototypes that are used to convert between isalnum(ch), isupper(ch), isdigit(ch),
uppercase and lowercase islower()
This header file includes function prototypes for
cstring C/C++-style string-processing functions. strcpy (), strcat(), strcmp() etc.
Function as prototypes for functions that open(), close(), put(), read(), write()
fstream perform input/output from/to files on disk are
included in fstream header. etc.
CHAR_MIN, CHAR_MAX, INT_MIN,
This header file has the integral size limits of the
climits system.
INT_MAX, UINT_MAX, LONG_MIN
LONG_MAX
FLT_DIG, DBL_DIG, LDBL_DIG,
This header file contains the size limits for
cfloat floating-point numbers on the system.
FLT_MANT_DIG, DBL_MANT_DIG,
LDBL_MANT_DIG

12
Chapter 1
C/C++ Library Functions (cont’d)
Namespace: using namespace std;
 Namespace designed to overcome a difficulty of like the below
 Sometimes a developer might be writing some code that has a
function called xyz() and there is another library available which is
also having same function xyz().
 The compiler has no way of knowing which version of xyz() function
you are referring to within your code.

 Generally namespace designed to differentiate similar functions,


variables etc. with the same name available in different libraries.

 There are several ways in which a namespace used in our program


 Option 1: using namespace std;
 Option 2: using std::cout; using std::cin;
where “std” is identifier of the namespace
13
Chapter 1
Preprocessor Directives
 A preprocessor is a program that invoked by the compiler before the
program is converted to machine language
 In C++ preprocessor obeys command called preprocessor directives,
which indicate that certain manipulations are to be performed on
the program before translation begins.

14
Chapter 1
Preprocessor Directives (cont’d)
 A file preprocessor
#include <filename> versus #include “/path/filename.h”
 #include <filename>
• Looks in the IDE C++ devloper tools standard include directories that
were created at install time for the file.

 #include “/path/filename.h”
• Looks for the filename.h file in the /path/ directory path.
• Used when you are creating your own files (we will learn later how to
do) OR when you have downloaded some 3rd party non-standard C++
header files.

15
Chapter 1
Comments
• Used to document parts of the program
• Are ignored by the compiler
• Type of comments -- Single comment and Multi line comment

• Single comment - Begin with // through to the end of line:


e.g.1) int length = 12; // length in inches

e.g. 2) // calculate rectangle area


area = length * width;
• Multi line comment - Begin with /* and end with */ and
 Can span multiple lines
e.g. /* this is a multi-line
comment
*/
 Can begin and end on the same line
e.g. int area; /* calculated area */
Comments (cont’d)
• Purpose: Intended for persons reading the source code of the program
 Indicate the purpose of the program
 Describe the use of variables
 Explain complex sections of code

• Comment Guidelines --where


 Towards the top of your program
 Before every function you create
 Before loops and test conditions
 Next to declared variables.
Translation and Execution process (1/4)
 The only language that the computer understands is the machine
language.
 Therefore any program that is written in either assembly or high
level language must be translated to machine code so that the
computer could process it.
 This process is called Program translation/ and performed by
special software called translator

18
Chapter 1
Translation and Execution process (2/4)

Compiler Interpreter

Compiler scans the whole program in one go Translates program one statement at a time.

As it scans the code in one go, the errors (if Considering it scans code one line at a time,
any) are shown at the end together. errors are shown line by line.

Converts the source code into object code. does not convert source code into object code

More memory requirement due to creation


Requires less memory. However, it is slower
object. However, comparatively it faster

C, C++, C# etc. Python, Ruby, Perl, SNOBOL, MATLAB, etc.

19
Chapter 1
Translation and Execution process (3/4)

20
Chapter 1
Translation and Execution process (4/4)

21
Chapter 1
Variables and Data types
 Variables
 A primary goal of computer program is data processing
 Variable is a named reserved place (storage location) in memory,
which stores a piece of data of a particular data type.
 As a result it can be used in various computations in a program
 All variables have three important components
 Data Types
 Identifier
 Value

22
Chapter 1
Variables and Data types (cont’d)
 Data Types
 Describes the property of the data and the size of the reserved
memory.
 Established when the variable is defined
 Data types supported by C++ can be classified as follow

23
Chapter 1
Variables and Data types (cont’d)

 Signed - either negative or positive


 Unsigned - refers to positive integer only
24
Chapter 1
Variables and Data types (cont’d)
 Data types size and range of value

25
Chapter 1
Variables and Data types (cont’d)
 Data types size and range of value

26
Chapter 1
Variables and Data types (cont’d)
 The program below prints the size of C++ primitive data types

27
Chapter 1
Variables and Data types (cont’d)
 Signed Vs. Unsigned

 +ve – 0 bit
 -ve ---> 1 bit

 By default
 integer Data types are Signed where as char data types are Unsigned
 float, double, long double is also Signed, and cannot restricted to be Unsigned
28
Chapter 1
Variables and Data types (cont’d)

29
Chapter 1
Variables and Data types (cont’d)

Data type Value Range


This program demonstrate
the value range that int,
unsinged, short int, and
unsigned short store.

30
Chapter 1
Variables Naming Conventions
 An identifiers refers to the name of variable that needed to
uniquely identify each variable, so as to store a value to the
variable and retrieve the value stored

 Rules of Making Identifier (Conventions)


 Identifier name can be the combination of alphabets (a – z and
A - Z), digit (0 -9) or underscore (_).
E.g. sum50, avgUpto100 etc.
 First character must be either alphabet or underscore
E.g. _sum, class_strength, height ----- valid
123sum, 25th_var --------- invalid
 No space and No other special symbols(!,@,%,$,*,(,),-,+,= etc)
except underscore
E.g. _calulate, _5, a_
31
Chapter 1
Variables Naming Conventions (Cont’d)
 Variable name should not be a keyword or reserve word
Invalid names: interrupt, float, asm, enum etc.
 Variable name must be unique and case sensitive

Good practice of Identifier


 It is important to choose a name that is self-descriptive and
closely reflects the meaning of the variable.
 Avoid using single alphabet and meaningless names like below
a, b, c, d, i1, j99
 Some of allowed single alphabets include x, y, i, j, k
 Use came rule if the identifier constructed from more than words
thefontSize, roomNumber, xMax, yMin,
xTopLeft, thisIsAVeryLongName
32
Chapter 1
C++ Key Words
 Certain words are reserved by C++ for specific purposes and have a
unique meaning within a program.
 These are called reserved words or keywords.
 cannot be used for any other purposes.
 All reserved words are in lower-case letters.

33
Chapter 1
Variables declaration and Initialization
 Variable Declaration
 Variable must first be declared (defined) before they can be
used.
 Variables can be created in a process known as declaration
which instructs the computer to reserve a memory location
with the name and size

 Declaration syntax:
DataType Identifier;

 Declaration Examples:
• float moon_distance;
• double average, m_score, total_score;
• int age, num_students;
• Assigning a value: age=14;
34
Chapter 1
Variables declaration and Initialization
(cont’d)
 Variable Initialization
 When a variable is assigned a value at the time of declaration

 Declaration and initialization can be combined


using two methods
Method 1: DataType Identifier = Intial value;
Method 2: DataType Identifier (Intial value);

 Example:
int length = 12;
double width = 26.3, area = 0.0;
int length (12), width (5);

 We can initialize some or all variables:


int length = 12, width, area (0.0);
35
Chapter 1
User Defined Data types
 “typedef” Keyword is used to define a data type by the
programmer
 Evaluate the below two sample codes

36
Chapter 1
Scope of Variables
 Variables in a program can be declared just about anywhere.
 However, the accessibility, visibility and length of life of a variable depend
on where the variable is declared.
 Scope of a variable is the boundary or block in a program where a
variable can be accessed

Global Variable
 referred/accessed
anywhere in the
code

Local Variable
 Accessed only in side
a block within which
they are declared
37
Chapter 1
Scope of Variables (cont’d)
 Sample program to demonstrate scope of variable

38
Chapter 1
Constants and literals (1/8)
 Constant
 Like a variable a data storage locations in the computer memory
that has a fixed value and that do not change their content during
the execution of a program.
 Must be initialized when they are created by the program,
 The programmer can’t assign a new value to a constant later.
 Usually defined for values that will be used more than once in a
program but not changed
E.g., PI = 3.14, Sun_Seed = 3*10^8

 It is customary to use all capital letters, joined with underscore in


constant identifiers to distinguish them from other kinds of
identifiers.
E.g., MIN_VALUE, MAX_SIZE.
39
Chapter 1
Constants and literals (2/8)
(a) Defining constant using const keyword
 Syntax: const DataType Identifier = value;
 Example: const float PI = 3.14;

(b) Defining constant the #define preprocessor


 Syntax: #define Identifier value
 Example: #define PI 3.14

40
Chapter 1
Constants and literals (3/8)
 Literals
 are data used for representing fixed values.
 They can be used directly in the code.
 For example: 1, 2.5, 'c' etc.

41
Chapter 1
Constants and literals (4/8)
 Sample program

42
Chapter 1
Constants and literals (5/8)
 C++ Escape characters

43
Chapter 1
Constants and literals (6/8)
 Special characters

Character Name Meaning


# Pound sign Beginning of preprocessor
directive
< > Open/close brackets Enclose filename in #include
( ) Open/close Used when naming a function
parentheses
{ } Open/close brace Encloses a group of statements

" " Double open/close Encloses string of characters


quotation marks
‘ ‘ Single open/close Encloses character
quotation marks

44
Chapter 1
Constants and literals (7/8)
 Enumerated Constant
 Use to declare multiple integer constants using single line with
different features.
 Cannot take any other data type than integer
 enum types can be used to set up collections of named integer
constants.
 Enables programmers to define variables and restrict the value of
that variable to a set of possible values which are integer.
 Use the keyword enum is short for ``enumerated''.
 Syntax: enum identifier {enumerated list};

45
Chapter 1
Constants and literals (8/8)
 enum sample program

46
Chapter 1
Operators and expression (1/ 17)
 Operators
 A symbol that tells the computer to perform certain mathematical
(or) logical manipulations (makes the machine to take an action).

 Used in programs to manipulate data and variables.

 Different Operators act on one or more operands

 Based on the number of the operands the operators act on, operators are
grouped as

Unary – only single operand used


Binary – require two operands
Ternary – require three operands
47
Chapter 1
Operators and expression (2/17)

48
Chapter 1
Operators and expression (3/17)
 Expression
 A combination of operators and operands (variables or literal values),
that can be evaluated to yield a single value of a certain type.
 It can also be viewed as any statement that evaluates to a value (returns
a value)
 Examples:
• x=3.2; returns the value 3.2
• x = a + b;

49
Chapter 1
Operators and expression (4/17)
 Arithmetic Operators
SYMBOL OPERATION EXAMPLE VALUE OF ans
+ addition ans = 7 + 3; 10
- subtraction ans = 7 - 3; 4
* multiplication ans = 7 * 3; 21
/ division ans = 7 / 3; 2
% modulus ans = 7 % 3; 1

 Points to be considered
 Arithmetic expression
 Mixed type operations - two operands belong to different types
 Type casting – implicitly type casting
 Overflow/Under Flow – what happen if the computation result
exceed the storage capacity of the result variable 50
Chapter 1
Operators and expression (5/17)
 Overflow/Underflow and wrapping around
 Arithmetic overflow/underflow happens when an arithmetic operation
results in a value that is outside the range of values representable by the
given data type
 Wrapping around unsigned integers - when the program runs out of positive
number, the program moves into the largest negative number and then
counts back to zero
 Wrapping around signed integers - when the program runs out of positive
number, the program moves into the largest negative number and then
counts back to smallest negative value

Because of overflow the


value of num2 & num
either wrapping around or
the program generate
garbage value

51
Chapter 1
Operators and expression (6/17)
 Exercise

(1) Given below constants


Base pay rate = 180.25 ETB
regular work hours <= 40 hrs.
Over time payment rate = 120 ETB

Write a program that read hours worked and calculate hourly


wages, overtime and total wages.

(2) Write a program which inputs a temperature reading expressed in


Fahrenheit and outputs its equivalent in Celsius, using the formula

52
Chapter 1
Operators and expression (7/17)
 Assignment Operators
 Copy/put the value/content (of RHS) ----> to a variable (of LHS)
 Evaluates an expression (of RHS) and assign the resultant value to a
variable (of LHS)
Single assignment operators

Compound assignment
operators

Multiple assignment
a = b = c = 36
53
Chapter 1
Operators and expression (8/17)
 Relation (Comparison) Operators
 Evaluated to true/false
 Used to compare two operands that must evaluated to numeric
 Characters and Boolean are valid operands as they are represented
by numeric. Character can be evaluated by their ASCII value

54
Chapter 1
Operators and expression (9/17)
 Logical Operators
 Evaluated to true/false
 Used to compare two logical statements
 any non-zero value can be used to represent the logical true, whereas
only zero represents the logical false

Exercise:
• Given the year, month (1-12), and day (1-31), write a Boolean expression which
returns true for dates before October 15, 1582 (G.C. cut over date)
55
Chapter 1
Operators and expression (10/17)
 Bitwise Operators
 It refers to the testing, setting or shifting of actual bits in a
byte or word.
 There are bitwise operators

56
Chapter 1
Operators and expression (11/17)
 Increment/Decrement Operators (++/--)
 Used to automatically increment and decrement the value of a
variable by 1
 Provide a convenient way of, respectively, adding and subtracting 1
from a numeric variable

Prefix increment/decrement (++Operand or --Operand)


 Adds/subtracts 1 to the operand & result is assigned to the variable
on the left before any other operation performed

Postfix increment/decrement (Operand++ or Operand--)


 First assigns the value to the variable on the left or use the current
value of operand in operation & then increments/decrements the
operand
57
Chapter 1
Operators and expression (12/17)
 Example 1
#include <iostream>
using namespace std;

main() {
int a = 21, c ;

c = a++; //postfix increment


cout<<"Value of c after assigned a++ is :"<<c<<endl;
cout<<“Value of a is after a++:" << a << endl ;

c = ++a; //prefix increment


cout << Value of c after assigned ++a is :"<<c<<endl;
cout<<“Value of a is after ++a:" << a << endl ;
return 0;
}
58
Chapter 1
Operators and expression (13/17)
 Example 2
#include <iostream>
using namespace std;

main() {
int a = 21, c ;
a++; //postfix increment
c = a;
cout<<"Value of c after assigned a++ is :"<<c<<endl;
cout<<“Value of a is after a++:" << a << endl ;

++a; //prefix increment


c = a;
cout << Value of c after assigned ++a is :"<<c<<endl;
cout<<“Value of a is after ++a:" << a << endl ;
return 0;
} 59
Chapter 1
Operators and expression (14/17)
 Miscellaneous Operators
 Conditional operator (ternary operator)

Output:
i = 10 j = 5
10>=5? 10: 5

The larger
number is 10 60
Chapter 1
Operators and expression (15/17)
 Miscellaneous Operators
 Type casting operator (using bracket)

 Type casting operator (using static-cast) – provides error message

61
Chapter 1
Operators and expression (16/17)
/* Test Type Casting (TestTypeCast.cpp) double d1 = 5.5, d2 = 6.6;
*/ cout << (int)d1 / i2 << endl; // 0
#include <iostream> cout << (int)(d1 / i2) << endl; // 0
#include <iomanip>
using namespace std; // Test implict type casting
d1 = i1; // int implicitly casts to double
int main() { cout << d1 << endl; // 4.0
// Print floating-point number in fixed
format with 1 decimal place // double truncates to int! (Warning?)
cout << fixed << setprecision(1); i2 = d2;
cout << i2 << endl; // 6
// Test explicit type casting }
int i1 = 4, i2 = 8;
cout << i1 / i2 << endl; // 0
cout << (double)i1 / i2 << endl; // 0.5
cout << i1 / (double)i2 << endl; // 0.5
cout << (double)(i1 / i2) << endl; // 0.0

62
Chapter 1
Operator precedence (17/17)
 Refers to the order an expression that contain more than one
operators will be evaluated

63
Chapter 1
Debugging program Errors (1/2)
 Errors
 The problems or the faults that occur in the program, which
makes the behavior of the program abnormal
 Also known as the bugs or faults
 Detected either during the time of compilation or execution

 Debugging
 The process of removing program bugs and correcting it
 Types of errors
 The are three major errors in programming namely
1. Syntax errors – also include semantics error
2. Logical errors
3. Run-time errors
64
Chapter 1
Debugging program Errors (2/2)
 Syntax errors
 When there is the violation of the grammatical (Syntax) rule.
 Detected at the compilation time.
 e.g. missing of semicolon, Identifier not declared
 Logical Errors:
 Produced due to wrong logic of program. Tough to identify and even
tougher to remove.
 Variables are used before initialized/assigned value
 Misunderstanding of priority and associativity of operators
 Runtime Errors:
 Generated during execution phase due to mathematical or some
operation generated at the run time.
 Division by zero,
 Square root of negative number,
 File not found, Trying to write a read only file 65
Chapter 1
Formatted Input/output (1/2)
 Formatted console input/output functions are used for performing input/output
operations at console and the resulting data is formatted and transformed.
Functions Description
Using this function, we can specify the width of a value to be displayed
width(int width)
in the output at the console.
Using this function, we can fill the unused white spaces in a value(to be
fill(char ch)
printed at the console), with a character of our choice.
Using this function, we can set the flags, which allow us to display a
setf(arg1, arg2)
value in a particular format.
The function returns the next character from input stream, without
peek()
removing it from the stream.
The function skips over a number of characters, when taking an input
ignore(int num)
from the user at console.
This function appends a character(which was last read by get()
putback(char ch)
function) back to the input stream.
Using this function, we can specify the number of
precision(int num_of_digts) digits(num_of_digits) to the right of decimal, to be printed in the
output.

66
Chapter 1
Formatted Input/output (2/2)

67
Chapter 1
Formatting codes (1/1)
 Proper commenting
 Avoid improper/unnecessary and over comments
 Comment your codes liberally
 Braces
 Place the beginning brace at the end of the line, and align the ending
brace with the start of the statement
 Indentation and whitespace
 Indent the body of a block by an extra 3 (or 4 spaces), according to its
level and provide enough space/newline between statements, operators,
operands/variables and other programming elements
 Naming (Identifiers)
 Use self-contained identifier (variable naming)
 e.g., row, col, size, xMax, numStudents.
 Avoid using single-alphabet and meaningless names, such as a, b, c, d
except common one like i, j, x, y
68
Chapter 1
Summary of C++ Statements (1/1)
 Prep-processor statements
 Declarative Statements
 Variable declaration
 Variable Initialization
 Constant definition
 Executable statements
 Input/output statements
 Assignment statements
 Expression
 Selection statements
 Loop statements
 Special Statements (break, continue, return, exit)

69
Chapter 1
Exercise
1. Identify which of the following are valid and invalid identifiers?
Justify your answer.
a) Identifier f) 2by2
b) seven_11 g) Default
c) _unique_ h) average_weight_of_large_pizza
d) gross-income i) variable
e) gross$income j) object.oriented

2. Define variables to represent the following entities:


a) Age of a person.
b) Income of an employee.
c) Number of words in a dictionary.
d) Mark of student
e) Gender of person
70
Chapter 1
Exercise (cont’d )
3. Write a program which inputs a positive integer n and outputs 2
raised to the power of n (Hint: use pow() function from math.h).
4. Write a program which inputs three numbers and outputs the
message Sorted if the numbers are in ascending order, and outputs
Not sorted otherwise. (Hint: use conditional operator)
5. Add extra brackets to the following expressions to explicitly show
the order in which the operators are evaluated then evaluate it.
a) (n <= p + q && n >= p - q || n == 0)
b) (++n * q-- / ++p - q)
c) (n | p & q ^ p << 2 + q)
d) (p < q ? n < p ? q * n - 2 : q / n + 1 : q - n)
6. What will be the value of each of the following variables after its
initialization. Which type of casting is applicable1?
a) double d = 2 * int(3.14);
b) long k = 3.14 - 3;
71
Chapter 1
Exercise (cont’d )
7. What will be the output of the following C++ code?
#include<iostream> #include<iostream>
(a) using namespace std; using
(b) namespace std;
int main(){ int main(){
int x = 5, y = 5; int x = 5, y = 5, z;
cout << ++x << y -- <<endl; x = ++x; y = --y;
return 0; z = x++ + y--;
} cout << z << endl;
return 0;
#include<iostream> }
using namespace std;
int main(){
int num1 = 5, num2 = 3, num2 = 2;
(c) num1 -= num2++; num2 *= --num3;
bool num4 = num1 – num2;
cout << num1 << num2 << num3<< num3 <<endl;
return 0;
} 72
Chapter 1
Reading Resources/Materials
 Chapter 1, 2 & 3: Problem Solving With C++ [10th
edition, University of California, San Diego, 2018;
Walter Savitch;

 Chapter 2 & 3: An Introduction to Programming with


C++ (8th Edition), 2016 Cengage Learning; Diane Zak

 Chapter 2: C++ how to program, 10th edition, Global


Edition (2017); P. Deitel , H. Deitel
73
Thank You
For Your Attention!!

74

You might also like