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

CSC 126 NOTES

The document provides an overview of basic programming concepts in C++, including variable declaration, data types, arithmetic and relational operators, and error handling. It emphasizes good programming practices such as reliability, efficiency, interactivity, and readability. Additionally, it covers the structure of a C++ program, including the use of comments and preprocessor directives.

Uploaded by

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

CSC 126 NOTES

The document provides an overview of basic programming concepts in C++, including variable declaration, data types, arithmetic and relational operators, and error handling. It emphasizes good programming practices such as reliability, efficiency, interactivity, and readability. Additionally, it covers the structure of a C++ program, including the use of comments and preprocessor directives.

Uploaded by

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

ALGO RI THM DESI GN & CO MPUTER PRO BLEM SO LVI NG

CSC126
BA S I C D ECLARATION PRO GRAMMI NG ERRO RS

EXPRES SI O N GO O D PRO GRA MMI NG


STRUCTURE

S TA TEMENT

C++ PRO GRAM STRUCTURE


Basic Declaration
Basic Declaration
• Variable is an identifiers that refers to memory location, which can hold values.
• Variable can only store one value at one time. Thus, the content of variable may
change during the program execution.

Variable
• Before it is used, it must be declared with its data type.

i is example of variable
name
Basic Declaration
⚬ Syntax:
data_type variableName;

⚬ Type of declaration:

Variable
■ Single declaration
■ Multiple declaration

Multiple declaration Single declaration


Basic Declaration

Variable
Basic program components
• Identifier:
⚬ Are used to define names to represent variables, constant and name of
function.

Identifier
⚬ Consists of letters, digits, and the underscore (no others symbols are
permitted to form a identifier.
⚬ Must begin with the letter or underscore
⚬ The following are some example of illegal identifier in C++:
Illegal Identifier Description
There can be no space between employee and
employee Salary
Salary
The exclamation mark cannot be used in an
Hello!
identifier
one+two The symbol + cannot be used in an identifier
2nd An identifier cannot begin with a digit
Basic program components

• Rules in naming identifier:

Identifier
⚬ The 1ˢᵗ character must be an alphabet letter or an underscore ‘_’.
⚬ Can only consists of letters, digits and underscore ‘_’.
⚬ Cannot use C++ reserved words/keywords
⚬ There must be no blank space character
⚬ Identifiers are case sensitive
Basic program components

• Reserved words/ keywords

Variable
int char long

float double default

case for void

break const else

if private do

else goto switch

while public class

return continue break


Basic program components

• Data types define


the type of data a variable can
hold, for example an
integer variable can hold

Data type
integer data, a character type
variable can hold
character data.
Basic program components – character data type
Character Data type

• String of characters is a group of characters that are put together to create


text

Data type
• 2 types : -
⚬ String literals
■ “hard coded” into your program and is enclosed in quotation marks.
⚬ string eg: string text = “hello”;
⚬ Need to include #include<string>

⚬ Character arrays
■ used to store strings that change during the program execution.
⚬ char[] eg: char text[6] = “hello”;
⚬ it will hold only 5 characters and terminated by a null character
‘\0’ which has the value zero
Basic Declaration
• A variable whose value does not change throughout program execution.
⚬ Allow you to give name to a value that is used several times in a program.
⚬ Usually, constant name is capital to distinguish from other variables.
⚬ 2 ways of declaring constant:
■ Using constant keywords: const float PI=3.142;

constant
■ Using preprocessor directives: #define PI 3.142
constant
Basic Declaration

Variable initialization
⚬ Once a variable is declared, it contains none useful value (garbage).
⚬ To make it useful, the variable must be given a value.
⚬ The value serves as the initial value to the variable.
⚬ A variable can be initialized to any value as long as the value’s data type
matches the variable’s data type. C++ has several assignment operators.
The most commonly used assignment operator is ‘=’.
⚬ Assignment operations using = has the general form:
identifier = expression;
⚬ Where identifier generally represent variable, and expression represent a
constant, a variable or a more complex expression.
Basic program components

Variable initialization
Basic program components

Variable initialization
Expression
Expression

Arithmetic Operator
• To perform arithmetic operations (manipulate integral and
floating-point data types).
• The arithmetic operators :-

Operator Operation
+ Addition
Floating-point data
- Subtraction type

* Multiplication Integral data type

/ Division
% Modulus (Remainder) Integral data type

-- Decrement by 1
Integral data type
++ Increment by 1
Expression

Arithmetic Operator
• Arithmetic precedence
Basic program components
Mathematical Operator

Example of Arithmetic operator and arithmetic expression


Expression

Arithmetic Operator
• Precedence rules:
⚬ specify which operator is evaluated first when two operators with different
precedence are adjacent in an expression.
⚬ Evaluate operator with highest priority (precedence).
• Associativity rules:
⚬ specify which operator is evaluated first when two operators with the same
precedence are adjacent in an expression.
⚬ Evaluate from left to right.
Parentheses, () may be used to alter the order of evaluation. They are force
an operation, or set of operation to have a higher precedence level.
Basic program components
Mathematical Operator

• Arithmetic expression
⚬ Formally, arithmetic expression is constructed by using arithmetic
operators and numbers.
⚬ The numbers appearing in the expression are called operands.
⚬ Operators that have only one operand are called unary operators.
⚬ Operators that have two operands are called binary operators.
• Example:
-5 7-5
Unary operator (negative number) Binary operator
Basic program components
Mathematical Operator

• Important notes:
⚬ For the modulus (remainder) operator, all of its operands must be integer
only.
⚬ Be careful of the operands’ data types when using division operator. For
example:

Expressions Output

7/4 1

7.0 / 4 1.75

-1 / 4 0

-1 / 4.0 -0.25
Expression

• To compare the values of two operands.

Relational Operator
• The evaluation result is either true (1) or false (0).
• The relational operators :-

Operator Operation
< Less than
<= Less than and equal to
> Greater than
>= Greater than and equal to
== Equal to
!= Not equal to
Expression

• When there is more than one relational expression at a time, logical

Logical Operator
operator are used to perform the evaluation
• The evaluation result is either true (1) or false (0)
• The logical operators :-

Operator Operation
&& AND
|| OR
! NOT
Expression
• When more than one arithmetic operator is used in an expression, C++ uses the

Operator Precedence
operator precedence rules to evaluate the expression.

Operator Category

Parentheses Highest

Multiply, Division, Modulus

Add, Subtract

Relational Operators

Equality Operators

Logical AND

Logical OR Lowest

The multiplication, division, and modulus operators are evaluated before addition and subtraction operators. Operators having the same
level of precedence are evaluated from left to right. Grouping is allowed for clarity.
Mathematical Function

• To use a Math predefined function in a program, you need to know


the name of the header file containing the specification of the
function and include that header file in the program. In addition,
you need to know the name of the function, the number of
parameters the function takes, and the type of each parameter. You
must also be aware of what the function is going to do.
• For example, to use the function pow, you must include the header
file cmath. The function pow has two parameters, which are
decimal numbers. The function calculates the first parameter to
the power of the second parameter.
Mathematical Function
Mathematical Function
Statement
Basic program components
• Standard output stream is called cout which refers to the computer screen.
• Symbol << that follows after cout is called insertion operator means “sends to”.

Output statement
• cout << is used to send output to the screen.
• Preprocessor directive #include <iostream.h> must be used in order to handle
output statement ‘cout <<’.
Formatting Output
• It is important that the numerical results are presented attractively and
formatted correctly. In C++, there are a number of stream manipulators that can
be used commonly for that purpose, as illustrated in the following table.

• To used stream manipulators, the iomanip.h header file must be included as


part of the program. This is accomplished by the preprocessor command
#include <iomanip.h>.
Formatting Output
Escape sequence
• The combination of backslash (\)
and specific characters are

Extra notes…..
called escape sequences.
Escape sequences change the
meaning of the character that
follows it.
• Those escape sequences must
be within quotation marks ( “ ” ).
• Table 2 illustrates some escape
sequences.
Basic program components

• Standard input stream is called cin, which will pause the program to allow the

Input statement
user to enter the data.
• Symbol >> that follows after cin is called extraction operator means “gets from”
cin >> identifier >> identifier;
• Example:
cin >> num1;
//gets the value from the keyboard then stores it in memory location name num1.
Basic program components
• cin.getline() is used to read the entire line of input from user as a
string including blank space and newline character.

Input statement
• To use string predefined functions, string.h header file must be
included in the program.
• The syntax take the form
cin.getline(variable, length);
• For example,
cin.getline (text, 80);
• indicates that text is a variable used to store a string of characters,
and 80 is the maximum length the variable text can store.
Basic program components

Input statement
string studName;
getline(cin,studName);
Basic program components

Input statement
C++ Program Structure
Basic program components

• A simple C++ program has the following form:

Note:
Option on how to write main function

void main()
{

}
Basic program components

• These are introductory comments. The comments are not executed


by the compiler and they are used only to allow the readability of

Comments
the program.
• Types of comment:
block comment
⚬ Line comment - //
⚬ Block comment - /* ……. */

Line comment
Basic program components

Preprocessor Directive
• Examples:
⚬ #include <iostream.h>
■ To declares the basic C++ streams (I/O)
routines.
⚬ #include <math.h>
■ Declares prototypes for the math
functions and math error handlers.
⚬ #include <conio.h>
■ Declares various functions used in
calling the operating system console I/O
routines.
Basic program components

Function main()
• The word main, which must be typed in Note:
Option on how to write main
lowercase letters, is the name of function
function.
void main()
• A function is simply a block of code that {
performs a task. …
}
• void main() is referred to as function
header, because it marks the beginning
of a function.
• Every C++ program has a function
called main
Errors
Program errors
• Run‐time error
⚬ Run‐time errors occur during the execution of a program and are detected
by the compiler.
Type of errors

• Syntax error
⚬ A syntax error is an error in the structure or spelling of a statement. This
error can be detected by the compiler during compilation of the program.
• Logic error
⚬ Logic errors refer to the unexpected or unintentional errors resulted from
some flaw in the program’s logic. Logic error is very difficult to detect since
compiler cannot detect this error. The only way to detect it is by testing the
program thoroughly and comparing its output against manually calculated
results.
Run-time error Program errors

Attempting to divide by zero in the above statement causes a


run‐time error such as “Floating point division by error” or
divide‐error exception”.
Syntax error Program errors

i. Invalid use of backslash (/) in line 6


ii. Missing semicolon (;) in line 6
iii. Keyword cout is misspelled in line 7
iv. Invalid use of insertion symbol (>>) in line 7
v. Missing a closing quote (“) in line 7
Logic error Program errors

The logic errors are:


i. Assigning invalid values to variable of type integer in line 1
ii. Attempting to divide by zero in line 3
iii. Missing numerical output in line 4
iv. Taking the square root of a negative number in line 5
Good Programming
Practices
Good programming practices
1. Reliability of an output

• A good program must be able to produce correct


output. For that, a different set of input data is used
to ensure the reliability of the output.
Good programming practices
2. Program’s efficiency

• A good program must be designed to be efficient and reliable in the


sense that it produces no errors during execution process. Also,
the program must achieve its purpose so that the final result can
be trusted. Thus, it is important that the program is outlined first
using the pseudocode or flowchart tool.
Good programming practices
2. Program’s efficiency

• A good program must be designed to be efficient and reliable in the


sense that it produces no errors during execution process. Also,
the program must achieve its purpose so that the final result can
be trusted. Thus, it is important that the program is outlined first
using the pseudocode or flowchart tool.
Good programming practices
3. Interactivity

• The interaction process between the user and the program must be
well defined. The interactivity is important so that the user knows
the processing status. Program that are user‐friendly allow the
users to responds to instruction correctly and this will help the
users to key in input thus minimizing the errors resulted from
invalid data.
3. Interactivity Good programming practices
Good programming practices
• Readability is concerned with how other person views one’s program. For
4. Program readability

programmers, the use of indention and comments are common to improve


the program’s readability.
a. Indentation
• Indentation helps in making the structure of the program clearer and easier to read. A
statement within a statement should be indented to show the user which statements
are subordinated of the other.
Good programming practices
4. Program readability

b. Comments
• Some explanatory notes or comments (sometimes referred to as
internal documentation) should be place in the program coding to
improve its readability. In other words, comments are there for the
convenience of anyone reading the program.
• Comments can be placed anywhere within in a program and they will
NOT be executed by the compiler. Commenting out a section of code is
very useful in a debugging process.
Good programming practices
• Line comment - A line comment begins with two slashes (//) and
continues to the end of line.
4. Program readability
Good programming practices
• Block comment - Block comment begins with the symbol /* and end with symbol */. Block
comments are conveniently used for statements that span across two or more lines.
4. Program readability

You might also like