Você está na página 1de 48

Computer Programming

(CS-102)
Week 1

Topics
Data and Data types, Variables, Loops, Arrays,
Functions, Switch, Casting, Pointers,
Overloading, Object-Orientation: Structures,
Classes (Encapsulation, Data Hiding,
Inheritance, Polymorphism, Composition)

Course & Reference Books


C++ How To Program (Eight Edition), Dietel
Object-Oriented Programming in C++ (Third
Edition or higher), Robert Lafore

C++ IDEs

Eclipse
Netbeans
Dev C++
Microsoft Visual Studio 2005/2008/2010

Computer Programming Review


What is computer programming?
Computer programming is the art of writing
instructions that makes a computer perform
a certain task.

Computer Programming Languages


What is the natural language of a computer?
A computer naturally understands a machine
code or binary code i.e. a string of 0s and 1s.

Classification of Programming
Languages
Low-level Languages
High-level Languages

Who is a good programmer?


You can tell if you are a good programmer
1) You can understand your own code 12
months later
2) Others can make changes to your code.

A Program
A program is a very detailed list of steps which must be followed to
accomplish a certain task

Example of a daily routine:


1. Wear clothes according to particular weather
2. Buy some tickets
3. Go to a nearby bus stop
4. Wait for the correct bus
5. Get on
6. Pay the driver
7. Sit down where empty seats are available
8. Wait until the bus arrived in the area you wished to go to
9. Alert the driver as your bus stop comes
10. Wait for the bus to stop
11. Finally get off

Flowchart of
the example
Can you identify
number of
loops?
Terminator
Process
Connector
Decision

Programming a Robotic Arm

Programming Techniques
The evolution of programming
techniques is
to make programming languages more
expressive
to develop complex systems more easily

Programming Techniques (Contd..)

Unstructured Programming
Procedural Programming
Modular & Structural Programming
Abstract Data Type
Object-Oriented Programming

Unstructured Programming
Usually, people start learning programming by writing
small and simple programs consisting only of one main
program. Here ``main program'' stands for a sequence of
commands or statements which modify data which is
global throughout the whole program
Drawbacks:
This programming technique can only be used in a very
small program. For example, if the same statement
sequence is needed at different locations within the
program, the sequence must be copied. If an error occurs
And needs to be modified then every copy needs to be
modified

Procedural Programming
With procedural programming, you are able to
combine sequences of calling statements into
one single place.
A procedure call is used to invoke the
procedure. After the sequence is processed,
flow of control proceeds right after the
position where the call was made .

Procedures
With parameters and sub-procedures
(procedures of procedures) , programs can
now be written more structured and error free
For example, if a procedure is correct, every
time it is used it produces correct results
Consequently, in cases of errors you can
narrow your search to those places which are
not proven to be correct

Procedure Program view

Main Program
Data

Procedure1

Procedure2

Procedure3

Modular Programming
Modular programming is subdividing your
program into separate subprograms such as
functions and subroutines.
With modular programming, procedures of a
common functionality are grouped together
into separate modules.
A program therefore no longer consists of only
one single part. It is now divided into several
smaller parts which interact through
procedure calls and which form the whole
program

Modular Programming
Main Program(Also a module)
Data

Module1

+
Data

Procedure1

Data
Data11

Module2
+
Data

Procedure2

Data2

Procedure3

Modular Programming
Each module can have its own data. This
allows each module to manage an internal
state which is modified by calls to procedures
of this module.
Each module has its own special
functionalities that supports the
implementation of the whole program

Structural Programming
How many basic structures for programming?
Three Types of Structures in a structured
program

Statement sequence(s1,s2,,sn)

Branch (if-then-else)

Loop (for,do, and while loops)

Data and Data Types


C++ is a strongly typed language, in other
words every data item in your program has a
type associated with it
Your C++ compiler will make extensive checks
to ensure that, as far as possible, you use the
right data type in any given context
There are two broad classifications of numeric
constants that you can use in C++
1) Integer literals
2) Floating Point literals

Everyday Decimal Numbers


Lets consider an example
324 can be written as 3x10^2+2x10^1+4x10^0
which is 3x10x10+2x10+4
We call it decimal notation because it is built
around powers of 10
Representing numbers in this way is very handy
for people. However, your PC is rather less handy,
Being built mainly of switches that are either on or
off

Binary Numbers
Representing numbers using base 2 is called
the binary system of counting. Digits can only
be 0 or 1, which is ideal when you only have
on/off switches to represent them. In an exact
analogy to our system of counting in base 10,
the binary number 1101 breaks down like
this:
1x2^3+1x2^2+0x2^1+1x2^0 = (13) to base 10

Computer Programming
(CS-102)
Week 1 Lecture 2

Integer Variable Types

Char (1 byte)
Short ( 2 bytes)
Int (4 bytes)
Long (4 or 8 bytes)

Floating Point Values

Mantissa 1.2345
Exponent 3
Value = 1.2345 x 10^3 = 1234.5
1.1E2?

Floating Point Data Types


Float Precision 7 digits Range 1.2 x 10^-38 to 3.4 x
10^38
Double Precision 15 digits Range 2.2x10^-308 to
1.8x10^308
Long double Extended precision
Write a program that will compute area of a circle. The
program should prompt for the radius of the circle
from the user and then display the result
Create a program that converts inches to feet-andinches for example, an input of 77 inches should
produce an output of 6 feet and 5 inches

First Program Review


// My First Program
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}

Introduction to C++
The previous program is the typical program
that programmer apprentices write for the
first time, and its result is the printing on
screen of the "Hello World!" sentence. It is
one of the simplest programs that can be
written in C++, but it already contains the
fundamental components that every C++
program has. We are going to look line by line
at the code we have just written:

Commenting
// my first program in C++This is a comment
line. All lines beginning with two slash signs
(//) are considered comments and do not have
any effect on the behavior of the program.
The programmer can use them to include
short explanations or observations within the
source code itself. In this case, the line is a
brief description of what our program is.

Directives
#include <iostream> Lines beginning with a hash
sign (#) are directives for the preprocessor. They
are not regular code lines with expressions but
indications for the compiler's preprocessor. In this
case the directive #include <iostream> tells the
preprocessor to include the iostream standard
file. This specific file (iostream) includes the
declarations of the basic standard input-output
library in C++, and it is included because its
functionality is going to be used later in the
program.

Namespace std
using namespace std;
All the elements of the standard C++ library are
declared within what is called a namespace, the
namespace with the name std. So in order to
access its functionality we declare with this
expression that we will be using these entities.
This line is very frequent in C++ programs that
use the standard library, and in fact it will be
included in most of the source codes included in
all of programs

Main()

int main ()This line corresponds to the beginning of the definition of the
main function. The main function is the point by where all C++ programs
start their execution, independently of its location within the source code.
It does not matter whether there are other functions with other names
defined before or after it - the instructions contained within this function's
definition will always be the first ones to be executed in any C++ program.
For that same reason, it is essential that all C++ programs have
a main function.
The word main is followed in the code by a pair of parentheses (()). That is
because it is a function declaration: In C++, what differentiates a function
declaration from other types of expressions are these parentheses that
follow its name. Optionally, these parentheses may enclose a list of
parameters within them.
Right after these parentheses we can find the body of the main function
enclosed in braces ({}). What is contained within these braces is what the
function does when it is executed.

Cout
cout << "Hello World!";This line is a C++ statement. A statement is a simple or
compound expression that can actually produce some effect. In fact, this
statement performs the only action that generates a visible effect in our first
program.
cout is the name of the standard output stream in C++, and the meaning of the
entire statement is to insert a sequence of characters (in this case the Hello
World sequence of characters) into the standard output stream (cout, which
usually corresponds to the screen).

cout is declared in the iostream standard file within the std namespace, so that's
why we needed to include that specific file and to declare that we were going to
use this specific namespace earlier in our code.
Notice that the statement ends with a semicolon character (;). This character is
used to mark the end of the statement and in fact it must be included at the end
of all expression statements in all C++ programs (one of the most common syntax
errors is indeed to forget to include some semicolon after a statement).

Return to main function


return 0;
The return statement causes the main function to
finish. return may be followed by a return code
(in our example is followed by the return code
with a value of zero). A return code of 0 for
the main function is generally interpreted as the
program worked as expected without any errors
during its execution. This is the most usual way to
end a C++ console program.

Compilation and Linking


C++ Source Code
Compiler compiles it produce the object code
The linker links the object file to produce the
executable program

Data Types
What is declaration?
General Syntax of data type in C++
<optional specifier><type><name><optional
initialization>

Data Types
Purpose of variables?
Storage of Information
Different types of information that we may
have to store
Integer Data, Floating Point Data, Character(s),
true/false
Collection of all of the above
Different storage in computers

Names of Variables

Keywords cannot be used as integer names


Variable names should
Start with letter(s)
They can contain digits except for the first
letter
They can have underscore (only)
Good naming convention

Character values
1.
2.

#include <iostream>
using namespace std;

3. int main(int argc,char* argv[])


4. {
5.
char a;
6.
a='14';
7.
//a=14; //uncomment and see what happens
8.
cout<<a<<endl;
9.
system("PAUSE");
10. return 0;
11. }

Operating with variables


1.
2.
3.
4.
5.
6.
7.
8.
9.

/ operating with variables


#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;

10.
11.
12.
13.
14.

int result; :
a = 5;
b = 2;
a = a + 1;
result = a - b;

15.
16.

// print out the result:


cout << result;

17.
18.
19.

// terminate the program:


return 0;
}

// process

Scope of variables
All the variables that we intend to use in a
program must have been declared with its type
specifier in an earlier point in the code, like we
did in the previous code at the beginning of the
body of the function main when we declared
that a, b, and result were of type int.
A variable can be either of global or local scope. A
global variable is a variable declared in the main
body of the source code, outside all functions,
while a local variable is one declared within the
body of a function or a block.

Scope of Variable

Global and Local Variables


Global variables can be referred from anywhere in the
code, even inside functions, whenever it is after its
declaration.
The scope of local variables is limited to the block
enclosed in braces ({}) where they are declared. For
example, if they are declared at the beginning of the
body of a function (like in function main) their scope is
between its declaration point and the end of that
function. In the example above, this means that if
another function existed in addition to main, the local
variables declared in main could not be accessed from
the other function and vice versa.

Keyword: const
You can define any kind of variable as const,
and the compiler will check that you do not
attempt to alter the value of such a variable

Classwork
Write a simple program that prompts the user to
provide an three inputs in yards, feets and inches and
express the length in inches
Formula to calculate length in inches:
Inches_per_foot= 12
Feet_per_yard =3
inches+inches_per_foot*(feet+feet_per_yard*yards)

The output should look like this

Você também pode gostar