Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

C Programming h

The document provides an overview of C++ programming, explaining the process of running a program, the role of high-level languages, and the function of compilers. It details the program design process, the software life cycle, and the origins of C++, along with fundamental components of a C++ program and variable management. Additionally, it covers the use of libraries, preprocessor directives, and C++ output mechanisms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Programming h

The document provides an overview of C++ programming, explaining the process of running a program, the role of high-level languages, and the function of compilers. It details the program design process, the software life cycle, and the origins of C++, along with fundamental components of a C++ program and variable management. Additionally, it covers the use of libraries, preprocessor directives, and C++ output mechanisms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

C++ Programming

Simple view of Running a Program:

A program is a set of
instructions for a computer to
follow. The input to a
computer can be thought of
as consisting of two parts, a
program and some data. The
computer follows the
instruction in the program,
and in that way, performs
some process.

The data is what we conceptualize as the input to the


program, and both the program and the data are input
to the computer. Whenever we give a computer both a
program to follow and some data for the program, we
said to be running the program on the data, and the
computer is said to execute the program on the data.
High-Level Languages

High-level languages are relatively sophisticated


sets of statements utilizing words and syntax
from human language. They are more similar
to normal human languages than assembly or
machine languages and are therefore easier
to use for writing complicated programs.
However, high-level languages must be
translated into machine language by another
program called a compiler before a
computer can understand them.
Compilers

A program that translates a high-level language


program into a machine language program
that the computer can directly understand
and execute. A compiler is somewhat a
peculiar sort of program, that is an input or
data in some other program, and its output is
yet another program. The input program is
usually called the source program or
source code, and the translated version
produced by the compiler is called the object
program or object code.
Program Design

Program design is a creative process. There is


no complete set of rules, no algorithm to tell
how to write programs. Still, there is the
outline of a plan to follow. The entire
program-design process can be divided into
two phases, the problem-solving phase and
the implementation phase. The result of the
problem-solving phase is an algorithm
and producing the final program from the
algorithm is called the implementation
phase.
Program Design Process:
Testing takes place in
both phases. Before
the program is written,
the algorithm is tested
and if the algorithm is
found to be deficient,
then algorithm is
redesigned. The
desktop testing is
performed by mentally
going through the
algorithm and
executing the steps
yourself.
Software Life Cycle:

• Analysis and specification of the task


(problem definition)
• Design of the software (algorithm
design)
• Implementation (coding)
• Testing
• Maintenance and evolution of the
system
Origins of C++ Language:
• C++ was derived from the C language.
• Developed by Bjarne Stroustrup of
AT&T Bell Laboratories in early 1980s.
• C++ has facilities to do object-oriented
programming.
The C++ Program
• The main work area in any C++
programming environment is the editor.
An editor is a simplified version of a
word processor in which you type your
program statements, or source code.
When you save what you have written
on a disk, you typically save C++
source code files with a filename that
has a .cpp extension.
• After you enter the source code for a
program, you must compile the
program. When you compile, the code
you have written is transformed into
machine language. The output from the
compilation is object code.
• A runnable, or executable, program
needs the object code as well as code
from any outside sources to which it
refers. The process of integrating these
outside references is called linking. An
executable file contains the same
filename as the source code and the
object code, but carries the
extension .exe to distinguish it as a
program.
• In C++, an action is referred to as an
expression.

• An expression terminated by a
semicolon is referred to as a statement.

• A statement is the smallest independent


unit in a C++ program.
First Program:
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}

The result is the printing on screen of the


“Hello World!” sentence.
Fundamental Components Of Every C++ Program:
// my first This is a comment line. All lines beginning
program in C++ with two slash signs (//) are considered
comments and do not have any effect on
the behavior of the program.
#include Lines beginning with a hash sign (#) are
<iostream> 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++.
#include conio.h is a header file that contains utility functions to
<conio.h> perform input and output operations to the console
from the C++ program.

using All the elements of the standard C++ library are


namespace std; declared within what is called a namespace, the
namespace with the name std. (std is an abbreviation
of “standard”)

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.
The instructions contained within this function's
definition will always be the first ones to be executed
in any C++ program.
The word main is followed in the code by a pair of
parentheses (()). That is because it is a function
declaration.
{ } The braces { and } mark the beginning and end
of the main part of a program. They need not be
on a line by themselves, but that is the way to
make them easy to find.

cout << "Hello This line is a C++ statement.


World!!!"; cout represents 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 (which usually is the
screen).

semicolon This character is used to mark the end of the


statement and in fact it must be included at the
character (;) end of all expression statements in all C++
programs
return 0; The return statement causes the
main function to finish. return may
be followed by a return code (The
example is followed by the return
code 0). A return code of 0 for the
main function is generally
interpreted as the program worked
as expected without any errors
during its execution.
getch() getch function is very useful if you
want to read a character input from
the keyboard.
Creating the main() function
C++ programs consist of modules called
functions. Every statement within every
C++ program is contained in a function.
Every function consists of two parts: a
function header and a function body.
The initial line of code in a C++ function
make up the function header, which always
has three parts:
• return type of the function
• name of the function
• types and names of any variable enclosed in
parentheses, and which the function receives.
• A C++ program may contain many
functions, but every C++ program
contains at least one function, and that
function is called main(). If the main
function does not pass values to other
programs or receives values from
outside the program, then main()
receives and returns a void type. Many
C++ programs begin with the header
void main().
Tips: You do not need to understand the
terms void or return type to
successfully run C++ programs. The
purpose of these components will
become apparent when you learn to
write you own functions. For now,
you can begin each program with
the header void main().
The body of every function in a C++ program is
contained in curly braces, also known as curly
brackets. The simplest program you can write has
the form shown below. It contains the header void
main() and an empty body.

Void main()
{
}
The program shown doesn’t actually do anything
because it contains no C++ statements. To create a
program that does something, you must place one or
more C++ statements between the opening and
closing braces.
Tips: Placing the main() header and the pair of
braces on three separate lines is a matter
of style. The program void main() { }
works as well as one written on three lines.
As a matter of style, however, most C++
programmers give void main() a line of its
own. They then give each brace a line of
its own, and indent each bracket a few
spaces.

Every C++ program must contain exactly


the same number of opening braces as
closing braces.
Working with Variables:

• In C++, you must name and give a type to


variables before you can use them.
• Names of C++ variables can include letters,
numbers and underscores but must begin
with a letter or underscore. No space or other
special characters is allowed.
• C++ is case-sensitive.
• Every programming language contains a few
vocabulary words, or keywords, that you
need in order to use the language. A C++
keyword cannot be used as variable name.
Common C++ Keywords are the following:
and continue if public try
and_eq default inline register typedef
asm delete int reinterpret_cast typeid

auto do long return typename


bitand double mutable short uchar_t
bitor dynamiccast namespace signed union
bool else new sizeof unsigned
break enum not state_cast using
case explicit not_eq static virtual
catch extern operator struct void
char false or switch volatile
class float or_eq template wchar_t
compl for overload this while
const friend private throw xor
constcast goto protected true xor_eq
• Variable names should be limited to 31
characters, or at least be unique within the
first 31 characters.
• Each named variable must have a type. C++
supports three types: integer, floating
point and character.
• Integer is a whole number, either positive or
negative. Integers do not include decimal
points, and they cannot be written with
commas, dollar signs, or any symbols other
than a leading + or - .
• An integer value may be store in an integer
variable declared with the keyword int.
• Real or floating-point numbers are
numbers that include decimal positions.
They may be stored in variables with
types float, double, and long double.
Usually a double occupies more
memory space than a float (allowing a
double to provide grater precision). A
long double typically uses more
memory space than a double. A double
never takes less storage space than a
float, and a long double invariably
requires no less space than a double.
• Characters may be stored in variables
declared with the keyword char. A character
may hold any single symbol in the ASCII
character set. Often it contains a letter of the
alphabet, but it could include a space, digit,
punctuation mark, arithmetic symbol, or other
special symbol. In C++, a character value is
always expressed in single quotes, such as ‘A’
or ‘&’.
• TIPS: A single character, such as ‘D’, is
contained in single quotes. A string value
such as “Donna” uses double quotes.
• To declare a variable, you list its type
and its name. A variable declaration is a
C++ statement, so it must end with a
semicolon.
• C++ allows any one-word identifier to
be used as a variable, but your
programs will be clearer and your work
will be considered more professional if
you use descriptive names like
myTestScore instead of cryptic variable
names such as x.
• Variables may be declared anywhere in a
C++ program, but are often declared just
after the opening curly braces in a function.
• The following code shows a C++ program
that will use variables of several types:

void main()
{
int myAge;
int yourAge;
char myMiddleInitial;
double myMoney, yourMoney;
}
• Notice the integer variables myAge and
yourAge are each declared in a
separate statement. On the other hand,
the two doubles, myMoney and
yourMoney, are declare in the same
statement. When you declare two
variables within the same statement,
you separate the variable names with a
comma and place the semicolon at the
end of the list of all the variables of that
type.
• Stating the value of a variable is called
assignment, and is achieved with the
assignment operator =. You can
assign a value to a variable in the same
statement that declares the variable, or
assign the value later in another
statement. Assigning a value to a
variable upon creation is often referred
to as initializing the variable.
Declaring, initializing, and assigning values to
variables:
int midtermScore;
int finalScore = 100,
midtermScore = 76;
int quiz1Score = 10,
quiz2Score = 5;

Note: the variable midtermScore is declared in


one statement, and assigned a value in a
separate statement. The variable finalScore is
declared and assigned a value at the same
time.
• TIPS: C++ allows you to assign values to
several variables in one statement. For
example, total = sum = amount=0; assigns a
value of 0 to all three variables listed in the
statement.
• TIPS: Assignment always takes place from
right to left; that is, a value on the right side
of the assignment operator is stored in the
memory location on the left side of the
assignment operator. A declaration is
complete only when you have listed as many
variables as you want for that type; use a
semicolon only when the entire statement is
complete.
• TIPS: Noticed that semicolons never
follow function headers such as void
main(). Function headers are not C++
statements. You can think of C++
statements as full actions, so you do
not place a semicolon at the end of a
function header, nor at the end of any
line with a statement that continues on
the next line.
Using Libraries and Preprocessor Directives:

• Header files are files that contain


predefined values and routines. Their
filenames usually end in .h. In order for your
C++ program to use these predefined
routines, you must include a preprocessor
directive, a statement that tells the compiler
what to do before compiling the program. In
C++, all preprocessor directives begin with a
pound sign (#), which is also called an
octothorp.
• The #include preprocessor directive tells
the compiler to include a file as part of the
finished product. For example, to use the
sqrt() function, you need to use
#include<math.h>
• TIPS: the angle brackets in
#include<math.h> indicate that the math.h
file is found in the standard folder that holds
include files.
C++ Output:

• C++ provides several objects for producing


output. The simplest object is called cout,
pronounced “see out”. The name comes form
Console OUTput, and cout shows whatever is
passed to it. The statement cout<<”Hi there”;
places the phrase “Hi there” on the monitor.
The insertion symbol (<<) says “insert
whatever is to my right into the object cout”.
• The object cout is contained in the header
file iostream.h. The term iostream is short
for Input Output STREAM. The preprocessor
directive #include<iostream.h> must appear
at the top of any program that uses cout.
A complete program that prints “Hi there”
is:

#include<iostream.h>
void main()
{
cout<<”Hi there”;
}
• To indicate a newline character, you can use
the escape sequence \n. The backslash
removes the usual meaning of the letter n,
(which is simply to produce the letter n, as in
the statement cout<<’n’) and causes the
output to move to a new line. The statement
cout<<”Hi\nthere”; shows “Hi” and “there” in
two separate lines.

• TIPS: other commonly used escape


sequences are \t for Tab, \” for a double
quote, and \’ for a single quote.
• Another way to advance output to a new line
is to use the end line manipulator endl.
C++ INPUT

• Many programs rely on input from a user.


These are called interactive programs
because the user interacts with the program
statements. The program must provide a way
the user can enter responses to program
prompts. You create prompts by using the
cout object; you retrieve user responses by
using the cin object. The cin (pronounce see
in) object fetches values from the keyboard.
It is used with the extraction operator >>.
Like cout, cin is contained in the iostream.h
header file.
The #include Directive
• The #include directive tells the
preprocessor to treat the contents of a
specified file as if those contents had
appeared in the source program at the
point where the directive appears.
• conio.h is a header file that declares
several useful library functions for
performing "console input and output"
from a program. Its a header file..used
for clrscr(), getch() functions.
#include <conio.h>
#include <iostream>

using namespace std;

int main ()
{
double price;
cout << "Please enter the price";
cin >>price;
cout << "The price you entered is " <<price<<endl;
getch();
}
C++ Classes and Objects:

• When you use data types like int, char,


and double within a program, you are
using the C++ built-in, primitive or
scalar data types. A major feature of
OOLs is the ability to create your own
new, complex data types. These new
types are called classes.
C++ Classes and Objects:

• Classes can become quite complex. A class


can contain many simpler data types within it,
as well as any number of functions. For
example, you might create an Employee
class with components such as firstName,
lastName, hourlySalary, and so on. The
relationship between these components, or
fields, of the Employee class is often called a
has-a relationship because every Employee
“has a” firstName, lastName, hourlySalary,
and so on.
class Employee
{
int idNumber;
double hourlySalary;
}

This indicates that an Employee has two components:


an integer idNumber and a double hourlySalary.
• By default all class fields are
private. That means they are not
available for use outside the class.
When creating a class, you can declare
some fields to be private and some to
be public.
• It indicates that if you want your fields
to be public, or readily accessible
outside their class.
SAMPLE Program:
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
cout << "I'm a C++ program";
return 0;
}
Example of a statements in C++

int book_count = 0;
book_count = books_on_shelf + books_on_order;
cout <<“the value of book_count:” <<book_count;

Note:
The first statement is a declaration statement.
book_count is called an identifier, a variable or an object.
It defines an area of computer memory associated
with the name book_count that holds integer
values.
0 is a literal constant.
book_count is initialized to a first value of zero.
The second statement is an assignment statement.
It places in the area of computer memory
associated with book_count the result of adding
together books_on_shelf and books_on_order.

The third statement is an output statement.


cout is the output destination.
<< is the output operator.

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 program.
• The program begins with the following lines:
#include <iostream>
using namespace std;
int main()
{
• The program ends with the following lines:
return 0;
}

• Note: the lines in between these beginning


and ending lines are the heart of the program.
Exercise:
1. What is the first step you should take
when creating a program?
2. From the given program examples,
formulate a layout of a simple C++
program of your personal information
(fullname, course, year, college,
school, home address, email address,
and contact number)
Sample Output:

Jade A. Buenavides
BSCPE-5
College of Engineering
Sultan Kudarat State University
Isulan Campus
jadebuenavides@sksu.edu.ph
0917-000-0001
Activity: Discuss the following:

a. Data Structure
b. Object Oriented Programming
c. Abstract Data Type
d. Inheritance
--end--

You might also like