0% found this document useful (0 votes)
149 views68 pages

Lesson2 - Intro To C

The document provides an introduction to the C++ programming language. It discusses that C++ was developed in 1983 by Bjarne Stroustrup as an extension of the C language to support object-oriented programming. The document then covers various aspects of C++ including comments, libraries, input/output statements, variables, data types, operators, and strings.

Uploaded by

light
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)
149 views68 pages

Lesson2 - Intro To C

The document provides an introduction to the C++ programming language. It discusses that C++ was developed in 1983 by Bjarne Stroustrup as an extension of the C language to support object-oriented programming. The document then covers various aspects of C++ including comments, libraries, input/output statements, variables, data types, operators, and strings.

Uploaded by

light
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/ 68

Programming

Introduction
to C++
Introduction to C++

C is a programming language developed in the 1970's


alongside the UNIX operating system.

C provides a comprehensive set of features for handling a


wide variety of applications, such as systems development
and scientific computation.
A tour of C++:
Developed by Bjarne Stroustrup in 1983 at Bell labs.

Originally named C with Classes.

C++ is an extension of the C language.

C++ supports object-oriented programming.


C++ is a general purpose programming language with a
bias towards systems programming that
is a better C,
supports data abstraction,
supports object-oriented programming
Bjarne Stroustrup
General form of a C++ program
// Program description
#include directives
int main()
{
constant declarations
variable declarations
executable statements
return 0;
}
Hello World!
// Hello World program comment

#include <iostream> Allows access to an


using namespace std; I/O library

Starts definition of special


int main() {
function main()

cout << "Hello World!\n"; output (print) a


string

return 0;
} Program returns a status
code (0 means OK)
Comments
is used to self-document a program.

Comments contain text that is not converted to machine


language

There are two ways to include comments in a program:

- //
- /* */
Comment Example:
// Dave's Homework #1
// This program is awesome!
#include <iostream.h>
/* This program computes the
coefficient of expansion of the
universe to 27 decimal places.
*/
int main() {
cout << 1.0000000000000000000001;
}
#include<iostream.h>
Lines beginning with a pound sign(#) are directives for the
preprocessor

The file (iostream) includes the declarations of the basic


standard input-output library in C++.
Some common library functions
include:
iostream.h

iomanip.h

stdlib.h

time.h
The input/output
statements
cout<<Hello World;
- Is a C++ statement.

- A statement is a simple or compound expression that can


actually produce some effect.

- To insert a sequence of characters into the standard output


stream.
cout
Represents the standard output stream in C++.

<<
- Called the insertion operator.

- Used in conjunction with the cout statement.


cin
Represents the standard input stream in C++.

>>
- Called the extraction operator.

- Used with cin.


Three primary activities of program:
1. Input - information a program collects from the outside
world.
Example:
cin>>hours;
cin>>rate;
2. Process
Example:
pay= hours * rate;
3. Output information that a program sends to the outside
world.
Example:
cout<<How many hours did you work?;
Token
-is the smallest individual unit of a program written in any
language.

C++s tokens are divided into:


> special symbols
> word symbols
> identifiers.
Special Symbols
+ - * /

. ; ,

<= != == >=
Word Symbols
(Reserved Words/Keywords)
Keywords
Cannot be redefined within any program; that is, they cannot
be used for anything other than their intended use.
Identifiers
- are names of things that appear in programs, such as
variables, constants, and functions.

- A C++ identifier consists of letters, digits, and the


underscore character ( _ ) and must begin with a letter or
underscore.

- Some identifiers are predefined; others are defined by


the user.

Note C++ is case sensitiveuppercase and lowercase letters are considered


different.
Variables and Constants
Variable - represent storage locations in the computers
memory.

Constants - data items whose values do not change while


the program is running.
Variable declaration:
C++ variables are declared like this:
type var_name;

Example:
int value;

Variable initialization:
value = 5;

cout<<The value is <<value<<endl;


Variable Names: Valid or Invalid?
dayOfWeek
3dGraph
_employeenum_
June1997
Mixture#3
x
J-20
theSalesFigureForFiscalyear98
r&d
grade_report
num 1
Literals (Constants)

Literals are fixed values used by a program.

Some examples of literals:

22 3.14159
false 'c'
Arithmetic Operators
+ addition

- subtraction or negation

* multiplication

/ division

% mod (modulus or remainder)


Arithmetic Expression
- is constructed by using arithmetic operators and
numbers.

- The numbers appearing in the expression are called


operands.
Unary operator:
An operator that has only one operand.

Binary operator:
An operator that has two operands.
Example: Arithmetic Expression
Expressions

C++ expressions are used to express computation.


Mathematical Expressions

Mathematical expressions have numeric values when


evaluated.

Some examples:
1+2
(fahr - 32)*(5/9)
1*(2*(3*(4*5)))
C++ Math Operator Rules
Operator Associativity Precedence
() left to right high
* / % left to right middle
+ - left to right low

what is the value of this?:


2 / 3 / 4 + 5
How about this: (7*3/4-2)*5
Precedence of Arithmetic Operators
Example of expressions:

1. 5 + 2 *4
2. 10 / 2 3
3. 8 + 12 * 2 4
4. 4 + 17 % 2 1
5. 63*2+7-1
Grouping with Parentheses

average = (a + b + c + d) / 4;

Example :
1. (5 + 2) * 4
2. 10 / (5 - 3)
3. 8 + 12 * (6 - 2)
4. (4 + 17) % 2 1
5. (6 - 3) * (2 + 7) / 3
Converting Algebraic Expressions to
Programming Statements
Algebraic Expressions Operation C++ Equivalent

6B 6 times B 6*B

(3)(12) 3 times 12 3 * 12

4xy 4 times x times y 4*x*y

Z = 3BC + 4

A = 3X + 2
4A - 1
No Exponents Please!

Raising a number to a power requires the use of library


function.

pow raise a number to a power.

Example:
Area = pow (4,2);
Math Operator Quiz
What are the values printed?

const int five = 5;


int i = 7;
float x = 7.0;
cout << five + i/2 << endl;
cout << five + x/2 << endl;
Relational and Equality Operators
Relational Operators:
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal

Equality Operators:
== Equal to
!= Not Equal to
Common Escape Sequences

\n - newline
\t - horizontal tab
\a - alarm
\b - backspace
\r - return
\\ - backslash
\ - single quote
\ - double quote
Seatwork1:

On paper, write a program that will display your name


on the first line, your street address on the second line,
your city, province, and zip code on the third line and
your telephone number on the fourth line of your
screen. Place a comment with todays date at the top of
the program.
Quiz1:
Instruction: Write assignment statements that
perform the following operations with the variables
a, b, and c.

1. Adds 2 to a and stores the result in b.


2. Multiplies b times 4 and stores the result in a.
3. Divides a by 3.14 and stores the result in b.
4. Subtracts 8 from b and stores the result in a.
5. Stores the value 27 in a.
6. Stores the character K in c.
7. & 8. How many operands do the following types of
operators require?
_____ Unary
_____ Binary

9. How may the float variables temp and weight be declared


in one statement?

10. How may the int variables months, day, and years be
declared in one statement, with months initialized to 2 and
years initialized to 3?
Data types
A set of values together with a set of operations.

- Integer
- only hold whole numbers
- Character
- primarily for storing characters
- Floating Point
- used to declare variables that can hold real numbers.
- Bool
- set to either true or false
Categories of Floating-Point data types:
1. float
2. double
3. long double

Examples of Real Numbers Printed in C++ Floating-Point Notation:


How would each of the following numbers be represented in E
notation?

a. 3.287 x 106
b. 978.65 x 1012

-3
c. 7.65491 x 10

-4
d. -58710.23 x 10
The char Data type
When character is stored in memory, it is actually the
numeric code that is stored.
#include<iostream>
using namespace std;
int main()
{
char letter;
letter = 65;
cout<<letter<<endl;
letter = 66;
cout<<letter<<endl;
return 0;
}
The C++ string Class
Two ways of storing and working with strings

store them as C strings in character array variables

Store them in string class objects

Note
some pre-standard compilers do not support them
What is the string class?
An abstract data type
A programmer defined that accompanies the C++ language.

Using the string class:

Include string header file


Declare a string object
Assign a string value
Some important points regarding character
and strings
Printable characters are internally represented by numeric
codes
Characters occupy a single byte of memory
Strings are consecutive sequences of characters and can
occupy several bytes of memory
Strings always have a null terminator at the end
Character constants are always enclosed with a single quote
String constants are always enclosed in double quotation
Escape sequences are always stored internally as a single
character
Demo Example 1
#include <iostream>
using namespace std;
int main()
{
int number_of_pods, peas_per_pod, total_peas;

cout << "Press return after entering a number.\n";


cout << "Enter the number of pods:\n";
cin >> number_of_pods;
cout << "Enter the number of peas in a pod:\n";
cin >> peas_per_pod;

total_peas = number_of_pods * peas_per_pod;


Demo Example 1
cout << "If you have ";
cout << number_of_pods;
cout << " pea pots\n";
cout << "and ";
cout << peas_per_pod;
cout << " pea in each pod, then \n";
cout << "you have ";
cout << total_peas;
cout << " peas in all the pods.\n";

return 0;
}
Programming Style
C++ is a free-format language, which means that:
Extra blanks (spaces) or tabs before or after
identifiers/operators are ignored.
Blank lines are ignored by the compiler just like comments.
Code can be indented in any way.
There can be more than one statement on a single line.
A single statement can continue over several lines.
Programming Style (cont. )
In order to improve the readability of your program, use the following
conventions:
Start the program with a header that tells what the program does.
Use meaningful variable names.
Document each variable declaration with a comment telling what the
variable is used for.
Place each executable statement on a single line.
A segment of code is a sequence of executable statements that belong
together.
Use blank lines to separate different segments of code.
Document each segment of code with a comment telling what the
segment does.
What makes a bad program?

Writing Code without detailed analysis


and design
Repeating trial and error without
understanding the problem
Writing tricky and dirty programs
PROGRAMMER'S DRINKING
SONG!!
100 little bugs in the code,
100 bugs in the code,

fix one bug, compile it again,


101 little bugs in the code.

101 little bugs in the code


Repeat until BUGS = 0

The Internet Joke Book


Seatwork2 :
The following codes of program had been mixed up. Arrange
the program and determine the output.
cout<<Success\n;
cout<<Success\n \n;
int main()
cout<<Success;
}
//Its a mad, mad program.
#include<iostream.h>
cout<<\nSuccess;
{
return 0;
Quiz2:
What will the program prints on the screen?
1. #include<iostream.h>
int main()
{
int x=0,y=2;
x = y * 4;
cout<<x<<endl<<y<<endl;
return 0;
}
2. #include<iostream.h>
int main()
{
cout<<Be careful\n;
cout<<This might/n be a trick;
cout<<question\n;
return 0;
}
Review questions:
1. Is the following assignment statement valid or invalid?
72 = amount;
2. How would you consolidate the following declarations into
one statement?
int x = 7;
int y = 16;
int z = 28;
3. Is the following an example of integer division or floating
point division? What value will be stored in portion?
portion = 70 / 3;
4. What is wrong with the given program? How would you
correct it?

#include<iostream.h>
int main()
{
critter = 62.7;
float critter;
cout<<critter<<endl;
return 0;
}
5. Every complete statement ends with a _______________.
6. Preprocessor directives begin with a _________.
7. The following data

72 A Hello World 2.8712

are all examples of ___________.


8. The negation operator is ________________.
9. A variable must be declared before it can be used.
10. Variables names may begin with a number.
11. Which of the following are not valid cout statements?
a. cout<<Hello World;
b. cout<<Have a nice day\n;
c. cout<value;
d. cout<<programming is great fun;
12. Assume w = 5, x = 4, y = 8, and z = 2. What value will be
stored in result in each of the following statements?
a. result = x + y;
b. result = z * 2;
c. result = y / x;
d. result = Y Z;
e. result = w % 2;
13. What header file must be included in programming using
cin?
14. Cin requires the user to press the [Enter] key when finished
entering the data.
15. A left brace in C++ program is always followed by a right
brace later in the program.
Programming
Challenges
Exercise 1: Cashier Screen
Exercise2: Variable Declaration
Write a program that has the following character variables:
First, Middle, and Last. Store your initials in these variables
and then display them on the screen.
Exercise3: Adding 2 numbers
Peter: Hey Frank, I just learned how to add two numbers
together.
Frank: Cool!
Peter : Give me the first number.
Frank: 2.
Peter : Ok, and give me the second number.
Frank: 5.
Peter : Ok, here's the answer : 2 + 5 = 7
Frank: Wow! You are amazing!

after Frank says 2, Peter has to keep this number in his mind.
after Frank says 5, Peter also needs to keep this number in his mind.

First number: 2 Second number: 5 Sum: 7


Exercise4: Sales Prediction

The East Coast sales division of a company


generates 62 percent of total sales. Based on the
percentage, write a program that will predict
how much the East Coast division will generate if
the company has 4.6 million in sales this year.

You might also like