0% found this document useful (0 votes)
3 views

Week 2 Zsufyan

The document is a course outline for CSC 2311, focusing on the fundamentals of C++ programming, including topics such as program structure, data types, variables, and input/output operations. It covers essential components like the cout and cin objects, preprocessor directives, and the importance of including header files. The document serves as a guide for students learning C++ programming, emphasizing syntax, variable management, and the use of constants.

Uploaded by

Mustapha Kaoje
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Week 2 Zsufyan

The document is a course outline for CSC 2311, focusing on the fundamentals of C++ programming, including topics such as program structure, data types, variables, and input/output operations. It covers essential components like the cout and cin objects, preprocessor directives, and the importance of including header files. The document serves as a guide for students learning C++ programming, emphasizing syntax, variable management, and the use of constants.

Uploaded by

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

CSC 2311

Computer Programming I

Starting Out with C++


Early Objects
8th Edition
by Tony Gaddis, Judy Walters,
and Godfrey Muganda

Updated by: Z.Sufyanu, PhD

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Topics
2.1 The Parts of a C++ Program
2.2 The cout Object
2.3 The #include Directive
2.4 Standard and Prestandard C++
2.5 Variables, Literals, and the Assignment
Statement
2.6 Identifiers
2.7 Integer Data Types
2.8 Floating-Point Data Types
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-2
Topics (continued)
2.9 The char Data Type
2.10 The C++ string Class
2.11 The bool Data Type
2.13 More on Variable Assignments and
Initialization
2.14 Scope
2.15 Arithmetic Operators
2.16 Comments

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-3
2.1 The Parts of a 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

return 0; send 0 back to operating system

} end of block for main

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-4
2.1 The Parts of a C++ Program
Statement Purpose
// 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
return 0; send 0 back to the operating system
} end of block for main

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-5
Special Characters
Character Name Description
// Double Slash Begins a comment
# Pound Sign Begins preprocessor directive

< > Open, Close Brackets Encloses filename used in


#include directive
( ) Open, Close Parentheses Used when naming function

{ } Open, Close Braces Encloses a group of statements


" " Open, Close Quote Marks Encloses string of characters

; Semicolon Ends a programming statement

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-6
Important Details
• C++ is case-sensitive. Uppercase and
lowercase characters are different
characters. ‘Main’ is not the same as
‘main’.
• Every { must have a corresponding }, and
vice-versa.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-7
2.2 The cout Object

• Displays information on computer screen


• Use << to send information to cout
cout << "Hello, there!";
• Can use << to send multiple items to cout
cout << "Hello, " << "there!";
Or
cout << "Hello, ";
cout << "there!";

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-8
Starting a New Line

• To get multiple lines of output on screen


- Use endl
cout << "Hello, there!" << endl;
- Use \n in an output string
cout << "Hello, there!\n";

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-9
The symbol << is called the output operator in C++. (It is also
called the put operator or the stream insertion operator.)
#include <iostream>
using namespace std;
int main ( ) { cout<< “welcome to computer science department!\
n”;
…………….
}
The message ‘welcome to computer science department!’ will
Print to the sentence

The last two characters \n represent the newline character.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-10
The cin Operator
•The cin operator is one way to input from the keyboard.
•When your programs reach the line with a cin, the user can enter values
directly into variables.

• Your program can then process those variables and produce output.
•The format of the cin is
cin >> value [>> values];

•The iostream.h header file contains the information C++ needs to use cin,
so include it when using cin.
•In C++, input is almost as simple as output. The input operator >> (also
called the get operator or the extraction operator) works like the output
operator <<

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-11
Example:
#include <iostream>
using namespace std;
int main()
{ //test the input of integer, float and characters
int m, n;
cout<<”enter the two integers:”;
cin>>m>>n;
cout<<”m=”<<m<<” “<<”n=”<<n<<endl;
……………
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-12
• First, the expression is evaluated and then the resulting value is assigned to the
variable. The equals sign “=” is the assignment operator in C++.

Example: in this example, the integer 32 is assigned to the variable x, and the value
of the expression x+23 is assigned to the variable y.
#include <iostream>
…………………….
int main()
{ //prints “x=32 and y=55”:
int x,y;
x = 32;
cout<<”x =”<<x;
y =x+23
cout<<”y =”<<y<<endl;
…………..
}

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-13
Escape Sequences – More Control Over
Output

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-14
2.3 The #include Directive
 the C++ compiler routes your programs through a
preprocessor before it compiles them.
 You must supply special non-C++ commands, called
preprocessor directives, to control the preprocessor.
 The preprocessor can be called a “pre-compiler”
because it preprocesses and prepares or modifies
your source code before the code reaches the compiler.
• Regular C++ commands do not affect the
preprocessor.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-15
2.3 The #include Directive…
• Inserts the contents of another file into the program.
It begins with a pound sign (#)
• Preprocessor directives are commands that you supply to
the preprocessor.
• Is a preprocessor directive
– Not part of the C++ language
– Not seen by compiler
– Never put a semicolon at the end
• Example:
No ; goes here
#include <iostream>

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-16
• program below contains three preprocessor directives.
• // C++ program that demonstrates preprocessor directives.
• #include <iostream>
• #define AGE 28
• #define MESSAGE “Hello, world”
• main()
• {
• int i = 10, age; // i is assigned a value at declaration
• // age is still UNDEFINED
• age = 5; // Defines the variable, age, as five.
• i = i * AGE; // AGE is not the same as the variable, age.
• cout << i << “ “ << age << “ “ << AGE << “\n”;
• cout << MESSAGE; // Prints “Hello world”.
• return 0;
• }
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley
• The #include preprocessor directive merges a disk file into your
source program.
• You usually can use angled brackets, <>, around the included
filename
• The angled brackets tell the preprocessor to look for the include
file in a default include directory, set up by your compiler.
• Your C++ compiler comes with its own header files
• The most common header file is named iostream
• This file gives your C++ compiler needed information about the
built-in cout and cin operators, as well as other useful built-in
routines that perform input and output.
• The name “iostream” stands for input/output stream header.

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-18
• At this point, you don’t have to understand the iostream file.

• You only have to place this file before main() in every


program you write.

• It is rare that a C++ program does not need the iostream.h


file.
• Even when the file is not needed, including it does no harm.

• Your programs can work without iostream as long as they


do not use an input or output operator defined there.
• Nevertheless, your programs are more accurate and hidden
errors come to the surface much faster if you include this
file.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley
Including header files of some
functions

•If you write a program that contains strcpy()


function, include its matching header file at the
same time you include <iostream>.
•These appear on separate lines, such as:
#include <iostream>
#include <string.h>

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley
2.4 Standard and Prestandard C++

Prestandard (Older-style) C++ programs


• Use .h at end of header files
#include <iostream.h>
• Do not use using namespace convention
• May not use return 0; at the end of function
main
• May not compile with a standard C++ compiler

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-21
2.5 Variables, Literals, and the
Assignment Statement
• Variable
– Has a name and a type of data it can hold

variable name
data type
char letter;
– Is used to reference a location in memory where a
value can be stored
– Must be defined before it can be used
– The value that is stored can be changed, i.e., it can
“vary”
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-22
Variables

– If a new value is stored in the variable, it


replaces the previous value
– The previous value is overwritten and can no
longer be retrieved
int age;
age = 17; // age is 17
cout << age; // Displays 17
age = 18; // Now age is 18
cout << age; // Displays 18

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-23
Assignment Statement

• Uses the = operator


• Has a single variable on the left side and a
value on the right side
• Copies the value on the right into the
variable on the left
item = 12;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-24
Constants
Literal
– Data item whose value does not change
during program execution
– Is also called a constant

'A' // character constant


"Hello" // string literal
12 // integer constant
3.14 // floating-point constant

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-25
2.6 Identifiers

• Programmer-chosen names to represent parts of the


program, such as variables
• Name should indicate the use of the identifier
• Cannot use C++ key words as identifiers
• Must begin with alphabetic character or _, followed
by alphabetic, numeric, or _ . Alphabetic characters
may be upper- or lowercase

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-26
Multi-word Variable Names

• Descriptive variable names may include multiple words


• Two conventions to use in naming variables:
– Capitalize all but first letter of first word. Run words together:
quantityOnOrder
totalSales
– Use the underscore _ character as a space:
quantity_on_order
total_sales
• Use one convention consistently throughout program
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-27
Valid and Invalid Identifiers

IDENTIFIER VALID? REASON IF INVALID


totalSales Yes

total_Sales Yes

total.Sales No Cannot contain period

4thQtrSales No Cannot begin with digit

totalSale$ No Cannot contain $

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-28
2.7 Integer Data Types

• Designed to hold whole (non-decimal)


numbers
• Can be signed or unsigned
12 -6 +3
• Available in different sizes (i.e., number of
bytes): short, int, and long
• Size of short  size of int  size of long

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-29
Signed vs. Unsigned Integers

• C++ allocates one bit for the sign of the


number. The rest of the bits are for data.
• If your program will never need negative
numbers, you can declare variables to be
unsigned. All bits in unsigned numbers
are used for data.
• A variable is signed unless the unsigned
keyword is used.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-30
Defining Variables

• Variables of the same type can be defined


- In separate statements
int length;
int width;
- In the same statement
int length,
width;
• Variables of different types must be defined
in separate statements
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-31
2.8 Floating-Point Data Types

• Designed to hold real numbers


12.45 -3.8
• Stored in a form similar to scientific notation
• Numbers are all signed
• Available in different sizes (number of
bytes): float, double, and long double
• Size of float  size of double
 size of long double
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-32
Floating-point Constants
• Can be represented in
- Fixed point (decimal) notation:
31.4159 0.0000625
- E notation:
3.14159E1 6.25e-5
• Are double by default
• Can be forced to be float 3.14159F or
long double 0.0000625L
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-33
Assigning Floating-point Values to
Integer Variables

If a floating-point value is assigned to an


integer variable
– The fractional part will be truncated (i.e.,
“chopped off” and discarded)
– The value is not rounded
int rainfall = 3.88;
cout << rainfall; // Displays 3

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-34
Example:
#include<iostream>
…………………
int main()
{ //tests the floating – point operators +, -, *, and /:
double x = 55.0;
double y = 20.0;
cout<< “x=”<<x<< “and y =”<<y<<endl;
cout<< “x+y=”<<(x+y)<<endl;
cout<< “x-y=”<<(x-y)<<endl;
cout<< “x*y=”<<(x*y)<<endl;
cout<< “x/y=”<<(x/y)<<endl;
…………………
}
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley
2.9 The char Data Type

• Used to hold single characters or very small


integer values
• Usually occupies 1 byte of memory
• A numeric code representing the character
is stored in memory
SOURCE CODE MEMORY

67

char letter = 'C'; letter


Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-36
• #include <iostream>
• using namespace std;

• /* run this program using the console pauser or add your own getch, system("pause") or input loop */

• int main()
• {
• char c = 'A';
• cout<<"c="<<c<<",int(c)="<<int(c)<<endl;
• c='t';
• cout<<"c="<<c<<",int(c)="<<int(c)<<endl;
• c='!';
• cout<<"c="<<",int(c)="<<int(c)<<endl;
• return 0;
• }
• Output
• c=A,int(c)=65
• c=t,int(c)=116
• c=,int(c)=33

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 1-37
Character Literal

• A character literal is a single character

• When referenced in a program, it is


enclosed in single quotation marks:

cout << 'Y' << endl;

• The quotation marks are not part of the


literal, and are not displayed
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-38
String Literals

• Can be stored as a series of characters in


consecutive memory locations
"Hello"
• Stored with the null terminator, \0,
automatically placed at the end
H e l l o \0

• Is comprised of characters between the " "


Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-39
A character or a string literal?
• A character literal is a single character,
enclosed in single quotes:
'C'
• A string literal is a sequence of characters
enclosed in double quotes:
"Hello, there!"
• A single character in double quotes is a
string literal, not a character literal:
"C"
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-40
2.10 The C++ string Class

• Must #include <string> to create and


use string objects
• Can define string variables in programs
string name;
• Can assign values to string variables with the
assignment operator
name = "George";
• Can display them with cout
cout << "My name is " << name;
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-41
2.11 The bool Data Type
• The Boolean type represents one of the two
values: false or true. The values are stored as the
integer 0 and 1 respectively.

• The Boolean type in standard C++ is named bool.


• bool allDone = true;
bool finished = false; allDone finished

1 0

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-42
Example
#include<iostream>
…………..
int main(){
bool signal= false;
cout<< “signal=” <<signal<<endl;
signal= true;
cout<< “signal=” <<signal<<endl;
…………..
}
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley
2.13 More on Variable Assignments and
Initialization

Assigning a value to a variable


– Assigns a value to a previously created variable
– A single variable name must appear on left side
of the = symbol
int size;
size = 5; // legal
5 = size; // not legal

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-44
Variable Assignment vs. Initialization

Initializing a variable
– Gives an initial value to a variable at the time
it is created
– Can initialize some or all of the variables
being defined
int length = 12;
int width = 7, height = 5, area;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-45
2.14 Scope

• The scope of a variable is that part of the


program where the variable may be used
• A variable cannot be used before it is defined
int num1 = 5;
cout >> num1; // legal
cout >> num2; // illegal
int num2 = 12;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-46
2.15 Arithmetic Operators

• Used for performing numeric calculations


• C++ has unary, binary, and ternary
operators
– unary (1 operand) -5
– binary (2 operands) 13 - 7
– ternary (3 operands) exp1 ? exp2 : exp3

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-47
Binary Arithmetic Operators

SYMBOL OPERATION EXAMPLE 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

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-48
/ Operator

• C++ division operator (/)performs integer


division if both operands are integers
cout << 13 / 5; // displays 2
cout << 2 / 4; // displays 0
• If either operand is floating-point, the result
is floating-point
cout << 13 / 5.0; // displays 2.6
cout << 2.0 / 4; // displays 0.5
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-49
% Operator

• C++ modulus operator (%) computes the


remainder resulting from integer division
cout << 9 % 2; // displays 1
• % requires integers for both operands
cout << 9 % 2.0; // error

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-50
2.16 Comments

• Are used to document parts of a program


• Are written 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
• Are ignored by the compiler

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-51
Single-Line Comments

• Begin with // and continue to the end of line


int length = 12; // length in inches
int width = 15; // width in inches
int area; // calculated area

// Calculate rectangle area


area = length * width;

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley 2-52
Multi-Line Comments

• Begin with /* and end with */


• Can span multiple lines
/*----------------------------
Here's a multi-line comment
----------------------------*/
• Can also be used as single-line
comments
int area; /* Calculated area */
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-
Wesley 2-53
Lab Exercises
1. Write a program that store the detail of your
bank account. Declare Name of the bank,
Account Name, Account Type, Account
Number and Current Balance as your
variables, assign values and display them on
the screen.

2. Modify the program in 1.) Above to


receive keyboard input. (Ref. Hrn
garko,Week 3,)

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-


Wesley

You might also like