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

Comprog Study Guide

Computer programming involves writing instructions for computers. There are many types of computers, from small digital watches to large mainframe systems. Programming languages allow humans to communicate instructions to computers. Some key points: - Computers perform tasks according to programmed instructions and can process and store vast amounts of data. - Programming involves developing algorithms to solve problems, which are then implemented through programming languages. - There are many programming languages ranging from low-level assembly to high-level languages like C++ that are easier for humans to read and write. - C was developed in the 1970s and became widely popular for its balance of high-level and low-level features. C++ built upon C by adding object
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Comprog Study Guide

Computer programming involves writing instructions for computers. There are many types of computers, from small digital watches to large mainframe systems. Programming languages allow humans to communicate instructions to computers. Some key points: - Computers perform tasks according to programmed instructions and can process and store vast amounts of data. - Programming involves developing algorithms to solve problems, which are then implemented through programming languages. - There are many programming languages ranging from low-level assembly to high-level languages like C++ that are easier for humans to read and write. - C was developed in the 1970s and became widely popular for its balance of high-level and low-level features. C++ built upon C by adding object
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Computer Programming

In almost every facet of our daily life, we live in close contact with
computers. Whether we realize it or not, we use them as a matter of routine. They
come in many sizes and shapes and do many useful things for us. If you own a
digital watch, you have a computer that tells you what time it is. Your car probably
has several computers that perform many different functions, such as injecting fuel
into its engine, indicating that door is ajar, telling you how many more miles you
can drive on the remaining fuel, and so on. If your telephone has a redial button, it
has a computer in it that remembers the last number you dialed. Your school has
many microcomputers, workstations, and perhaps even mainframes. You probably
own a personal computer at home. The examples of computers and computer
applications around us are nearly endless. So, what is Computer?

COMPUTER
• It is an electronic device that can input and store a set of instructions
designed to perform a specific task, input and store data, process the stored
data according to the instructions, and produce output to be relayed to its
user.

COMPUTERS ARE CLASSIFIED AS EITHER SPECIAL-PURPOSE OR


GENERAL-PURPOSE COMPUTERS.

SPECIAL-PURPOSE COMPUTER
• It is a computer designed for a particular function, executing the same
stored set of instructions whenever requested.

GENERAL-PURPOSE COMPUTER
• It is a computer that can be used for solving many different types of
problems.

1
Computer Programming

BLOCK DIAGRAM OF ALGORITHM AND DATA STRUCTURE

VERBAL PROBLEM ALGORITHM

PROGRAM COMPUTE
M R

DATA OUTPUT
DATA INPUT
STRUCTURE

Area = (1/2)*base*h;
ALGORITHM
• It comes from the word "algorism", means the first Arab numerical.
• It is a finite set of instructions that specify a sequence of operations to be
carried out in order to solve a specific problem.
• It is a recipe for solving the problem.

Two Forms of Algorithm


1. Pseudocode
• It is a textual representation of an algorithm
• It is a semiformal, English-like language with limited vocabulary
that can be used to design and describe algorithms.
2. Flowchart
• It is a two dimensional or graphical representation of an
algorithm.
• It is a graph consisting of geometrical shapes that are connected
by flow lines.

An algorithm must satisfy some requirement:

1. Input
• It must have input. It is conceivable that an algorithm may have no
input.

2. Output
• It must produce at least one output. An algorithm that does not
produce anything is worthless.
2
Computer Programming

3. Unambiguousness
• It must be unambiguous. In most cases, we develop an algorithm so
that it can be translated into a computer program to be executed by
computer. Computers cannot cope with ambiguities. Therefore, every
step in an algorithm must be clear as to what it is supposed to do, and
how many times it is expected to be executed.

4. Generality
• It must have generality.

5. Correctness
• It must be correct and must solve the problem for which it is
designed.

6. Finiteness
• It must execute its steps and terminate in finite time. An algorithm
that never terminates is unacceptable.

7. Efficiency
• It must be efficient. An algorithm that is designed for a specific
computer is not worth much if it takes days to solve a relatively simple
problem or if it requires more memory than what is available on that
computer.

DATA STRUCTURE
• It is an organized collection of values that may be used for data together
with a set of operations that may be done on that data.

Characteristics
1. Type of items
2. Relationship among its items

Categories
1. Scalar or Elementary Types
• These are data whose values are directly supported in the hardware of
the computer.
2. Structure Type
• It is a group of scalar
3. Abstract Type
• The type of data that are defined by the programmers.

3
Computer Programming
PROGRAM
• It is a sequence of instructions for a computer.
• This can be as simple as a DOS batch file or a lotus 1-2-3 Macro, or as
complex as a spreadsheet program written in C or assembly language.

TYPES OF PROGRAMS
A. According to Conversion
1. COMPILER
• It is a program which permanently translates the source code into
machine language and gives you a complete stand-alone program.
• Example: COBOL, TURBO C, TURBO PASCAL etc.
2. INTERPRETER
• It is a program which translates the source code one line at a time
each time the program is run.
• Example: GWBASIC/BASIC etc.

B. According to Data Input


1. INTERACTIVE
• It requires the input data from the user.
2. NON-INTERACTIVE
• It requires the input data from the program itself.

PROGRAMMING LANGUAGE
• A Programming Language as the means by which tell the computer
what you want done.
• Languages differ in many ways. Some are more computer-like; others
more English-like; some are for numeric processing; while others are
better for text processing; some are hardware based, while others are
structured or based on objects. But all programming languages have
the roots in the binary numbering system.

TYPES OF PROGRAMMING LANGUAGE


1. LOW-LEVEL LANGUAGE
• It refers to languages that go through every step of what the
computer hardware does. This type of language is very powerful
but difficult to learn and use.
• Example: Assembly Language.
2. HIGH-LEVEL LANGUAGE
• High-level languages are farther for how the computer actually
works. They are designed to fit in with the way the people think
rather than with the way computers operate.

4
Computer Programming
Example:
a. FORTRAN (FORmula TRANslation)
• It is used for engineering and scientific applications or numeric
processing
b. COBOL (COmmon Business Oriented Language)
• It is used for Business data transaction processing and reporting.
c. BASIC (Beginner’s All-purpose Symbolic Instruction Code)
• It is a simple language intended for student use in school-work.
d. LISP (LISt Processing)
• It is used in many educational setting for artificial intelligence
applications.
e. C / C++
• C is used for writing system software
• C++ is an extension of C that support object-oriented
programming.
f. PASCAL
• It is used for teaching students to program in a careful, disciplined
way.
g. MODULA-2
h. VISUAL BASIC

* C is sometimes called a “Low-Level High-Level language” because it is closer to


the way that computers actually work than languages such as BASIC.
* C has some of the advantages of both its low-level in the sense that it works more
like the computer than most high-level language do and its high-level in the sense
that its program structure is easy to follow.
* C is actually a much better introduction to programming than basic. C gives the
new programming insight into the way the actual works than basic does and C
programs are written with a structure that makes them much easier to follow than
basic programs.

BRIEF HISTORY
C LANGUAGE
The C programming language was developed in the early 1970s at AT&T
Bell Laboratories in New Jersey by a researcher named Dennis Ritchie. Although C
was originally developed with systems programming in mind (the UNIX operating
system is written in C), it now finds application to development of numerical and
engineering software as well.
The predecessor to C was the language B designed by Ken Thompson in
1970 for the first UNIX system on a DEC PHP 7 at Bell Laboratories. B was influenced
by the language BCBL developed by Martin Richards in the 1960s.

5
Computer Programming
The C programming language is becoming the standard language for
developing both system and application programs. It is a popular “high level”
language that allows software to be used on many machines without being
rewritten.

C++ LANGUAGE
C++ was invented by Bjarne Stroustrup in 1979, at Bell Laboratories in
Murray Hill, New Jersey. He initially called the new language “C with Classes.”
However, in 1983 the name was changed to C++.

Stroustrup built C++ on the foundation of C, including all of C’s features,


attributes, and benefits. He also adhered to C’s underlying philosophy that the
programmer, not the language, is in charge. At this point, it is critical to understand
that Stroustrup did not create an entirely new programming language. Instead, he
enhanced an already highly successful language.

Most of the features that Stroustrup added to C were designed to support


object-oriented programming. In essence, C++ is the object-oriented version of C.
By building upon the foundation of C, Stroustrup provided a smooth migration path
to OOP. Instead of having to learn an entirely new language, a C programmer
needed to learn only a few new features before reaping the benefits of the object-
oriented methodology.

C# LANGUAGE

C# was designed for developing components in a fully object-oriented


manner as part of the Microsoft .NET initiative. C# debuted in the year 2000 at the
Professional Developers Conference (PDC) where Microsoft founder Bill Gates was
the keynote speaker. At the same time, Visual Studio .NET was announced.
The primary architects of C# were Peter Golde, Eric Gunnerson, Anders Hejlsberg,
Peter Sollichy, and Scott Wiltamuth. Of these, the principal designer of the C#
language was Anders Hejlsberg, a lead architect at Microsoft. Previously, he was a
framework designer with experience with Visual J++ (Microsoft's old version of the
Java language), Delphi, and Turbo Pascal.

There are several reasons for its popularity such as:


1. C is flexible with few restrictions on the programmer.
2. C compilers produce fast and short machine code.
3. C is the primary language used in UNIX (trademark of AT&T Bell
Laboratories) operating system.

6
Computer Programming
KEY FEATURES OF C LANGUAGE
1. Operating system portability
C is a language that was designed in such a way that it would be
easy to implement a translator for it on various operating systems.
The result is a language that is available on virtually every
operating system in existence. Therefore, a version of an existing
program written in standard C can easily be transported to another
operating system.

2. Highly efficient object code


The C language was designed to facilitate direct translation into
machine language. As a result, the simple structures found in the
language closely resemble machine instructions, making it simple
to produce compact and fast programs.

3. Support of structured programming


The language supports structured programming by providing
control structures for sequencing, decision-making and repetition.
This makes it possible to create structured easily-to- read programs
in C.

APPLICATIONS OF C LANGUAGE
1. Database Applications
2. User interfaces
3. Networking Applications
4. Graphics
5. Operating system
6. Business Applications
7. Engineering and real-time applications.

7
Computer Programming

One advantage of C is that it lets you write programs that resemble


everyday English. Even you do not yet know how to write your own programs, you
can probably read and understand the program.

I. GENERAL FORM OF A C/C++ PROGRAM

A. Program Identification
/* AUTHOR
DATE
PROGRAM DESCRIPTION
*/
B. Compiler Directives:
#include
#define

C. Global Variable Declaration // optional

D. User-Defined Function (UDF) Declaration // optional

E. Main Program

F. User-Defined Function (UDF) Definition // optional

8
Computer Programming
Simplified format of a C/C++ Program

/* INTRODUCTORY COMMENTS
FILE NAME, PROGRAMMER
WHEN WRITTEN OR MODIFIED
PROGRAM DESCRIPTION */
Preproccessor directives

void main()
{
constant declarations
variable declarations
executable statements
{
}
}

Note:
• It makes complex programs much easier to interpret if, as above, closing
braces } are aligned with the corresponding opening brace {.
• Also additional spaces, new lines etc. can also be used to make programs
more readable. The important thing is to adopt one of the standard
conventions and stick to it consistently.
Example:

/*Sarah Moreno and Manny Lacson


Aug 17, 2021
Sample Program */
#include<stdio.h> // preprocessor directives
#include<conio.h>
void main(void) // main function heading
{
// local variables declaration
int a=2,b=3,c;
float x=3.0,y=5.6,z;
// executable statements
clrscr();
c=a+b;
printf(“ The sum of a and b is %d \n ”, c);
z=x*y; printf(“ The product of x and y is %f ”, z);
getch();
}
9
Computer Programming
The Mechanics of Creating a C/C++ Program

Editor: accepts the typing


of the source code (or header
file).

Source file: the file that


contains the program you
prepared in the editor after
you save it. (.cpp)

Header file: header files


such as iostream.h

Preprocessor: performs
preliminary operations on
files before they are passed
to the compiler.

Compiler: translates the


source code to machine
language.

Object code: the file


containing the translated
source code. (.obj)

Linker: links the object file


with additional code, such as
the library codes.

Executable code: the file


containing the final
product. (.exe)

LIBRARY
It is a collection of useful functions and symbols that may be accessed by a
program.

10
Computer Programming
COMMENTS
A program comment is like a parenthetical remark in a sentence – it is
intended to make the program easier to understand by describing its
purpose.
Comments are also used to describe the use of identifiers and the
purposes of each program step.
Comments are an important part of the documentation of a program
because they help others read and understand the program.
The compiler ignores comments; they are not translated into machine
language.

SYNTAX:
// COMMENT
/* COMMENT */

EXAMPLE
// This is a comment
/* and so
is this */

INTERPRETATION:
// can be used only when comment fits on a single line or when the
remainder of a line is a comment.
/* */ can stand alone or can be embedded in the of the statement. A
comment that begins with /* may extend over any number of lines until it
closes with */.

PREPROCESSOR
The preprocessor is a program that runs prior to compilation and
potentially modifies a source code file.
It may add code in response to the #include directive, conditionally
include code in response to #if, #ifdef, #ifndef directives or define
constants using the #define directive.

PREPROCESSOR DIRECTIVES
The preprocessor directives are commands that give instructions to the
C preprocessor, whose job is to modify the text of a C program before it is
compiled.
A preprocessor directive begins with a number symbol (#) as its first
nonblank character.

11
Computer Programming
The two most common directives are #include and #define.
#include DIRECTIVE
The #include directive instructs the preprocessor to read and include a file
into a source code file.
The file name is typically enclosed with < and > if the file is a system
provided file, or in quotes if the file is user provided.
Syntax:
#include <standard header file>
or
#include “user-defined header file”
Examples:
#include <stdio.h>
#include <math.h>
#include <iostream.h>

#include “myserial.h”
#include “myhfiles.h”
Interpretation:
#include directives tell the preprocessor where to find the meanings of
standard identifiers used in the program. These meaning are collected in
files called standard header files.
The header file stdio.h contains information about standard input and
output function such as scanf and printf.
Descriptions of common mathematical functions are found in the header file
math.h
The header file iostream.h is required in order to be able to use the stream
input/output facilities provided by cin, cout and endl.

#define Directive
It is used for Creating Constant Macros.
CONSTANT MACRO
A name that is replaced by a particular constant value before the program
is sent to the compiler.
Syntax:
#define NAME value
or
#define FUNCTION_NAME (expression)
Examples:
#define MILES_PER_KM 0.62137
#define PI 3.1416
#define MAX_LENGTH 100
#define p printf
12
Computer Programming
#define MAX(A,B) ((A)>(B)?(A):(B))
#define CUBE(A) (A)*(A)*(A)
#define ADD(A) ((A)+(A))
#define SUM(A,B) ((A)+(B))
Max(1,3) = 3
#define sw1 (PAIN&0x80)
Interpretation:
The C/C++ preprocessor is notified that it is to replace each use of the
identifier NAME by value.
C/C++ program statements cannot change the value associated with
NAME.

FUNCTION MAIN
The heading main() marks the beginning of the main function where
program execution begins.
Every C/C++ program has a main function.
The remaining lines of the program form the body of the function which
enclosed in braces {,}.
A function body has two parts: declarations and executable statements.

DECLARATION
A declaration is used to specify the name and type of an object to the
compiler.

EXECUTABLE STATEMENTS
Program lines that are converted to machine language instructions and
executed by the computer.

main Function Definition

SYNTAX:
[return_data_type] main([data_type])
{
function body
}

EXAMPLE:
int main(void)
{
printf(“ University of the East\n”);
return(1);
}
13
Computer Programming

void main(void)
{
printf(“ University of the East\n”);
}

void main()
{
printf(“ University of the East\n”);
}

DATA TYPES

It is a set of values and operations that can be performed on those values.


The type of a variable or constant indicates what kind of value it will
store.
A standard data type in C is a data type that is predefined.

DATA TYPE

BASIC AGGREGATE POINTER

void 0 array

char 1 struct

int 2 union

float 4

double 8

14
Computer Programming

BASIC DATA TYPES


2^8 = 256 (0 to 255) unsigned char ; signed char = char
Data Type Size in bytes Data Range Description
void No types used for
function Declarations and
‘ignoring’ a value returned
from a function.
char 1 byte=8bits -128 to 127 character data(signed)
signed char 1 byte = 2
nibbles
unsigned char 1 byte 0 to 255 character data
int 2 bytes = -32,768 to 32,767 integer value
16bits
short int 2 bytes -32,768 to 32,767 exactly the same as int
unsigned int 2 bytes 0 to 65,535 integer value
long int 4 bytes -2,147,483,648 to integer value with an
2,147,483,647 extended range
unsigned long 4 bytes 0 to 4,294,967,295 Unsigned long integer
int value
float 4 bytes 3.4×10-38 to floating point number
3.4×10+38
double 8 bytes 1.7×10-308 to double precision floating
1.7×10+308 point number
long double 10 bytes 3.4 * (10**-4932) double value with an
to 1.1 * extended range
(10**+4932)

QUALIFIERS
Qualifiers can be applied to the fundamental types.
The four Qualifiers are:
1. signed +-
2. unsigned+
3. short - same
4. long +2

15
Computer Programming
THE BASIC LANGUAGE ELEMENTS ARE:
1. Reserved words/ Keywords
2. Identifiers
3. Constants
4. Separators
5. Operators

RESERVED WORD/KEYWORD
Reserved word or keyword is a word that has special meaning in C/C++.
It cannot be redefined or used in other contexts. For instance, it cannot
be used as variable name.
These words always appear in lowercase
The keywords in the C++ language are:
asm auto bool break

case catch char class

const const_cast continue default

delete do double dynamic_cast

else enum except explicit

export extern false finally

float for friend goto

if inline int long

mutable namespace new operator

private protected public register

reinterpret_cast return short signed

sizeof static static_cast struct

switch template this throw

true try typedef typeid

typename union unsigned using

virtual void volatile wchar_t

while

16
Computer Programming
IDENTIFIERS
The names you give to constants, data types, variables, and functions.
Two rules must be kept in mind when naming identifiers:
The case of alphabetic characters is significant.
Up to 31 characters can be used and will be considered significant.
STANDARD IDENTIFIER
A word having special meaning but one that a programmer may redefine
(but redefinition is not recommended)
The standard identifiers printf and scanf are names of operations defined
in the standard input/output library (stdio.h).

USER-DEFINED IDENTIFIERS (UDI)


We choice our own identifiers (called user-defined identifiers) to name
memory cells that will hold data and program results and to name
operations that we define.
The syntax rules and some valid and invalid identifiers follow.
An identifier must consist only of letters, digits, and underscores.
An identifier cannot begin with a digit.
A reserved word cannot be used as identifier.
An identifier defined in a C standard library should not be redefined.

Valid identifiers
Voltage_1 Ampere2 Karen Length5 RESISTANCE
OUTPUT_PER_INPUT R I Mario
Michael_Jordan23 LJ

Invalid identifiers:
2voltage /* begins with a digit */
double /* reserved word */
THREE*ONE /* character * not allowed */
Shakey’s /* character ‘ not allowed */

Tip:
Some programmers use an underscore in variable names to separate parts
of the name, such as voltage_output.
Others prefer a "capital style" notation, such as voltageOutput to
separate parts of the name.
NEVER use UPPERCASE for every letter in a variable name, because
uppercase names are reserved for constant.
The best naming convention is to choose a variable name that will tell the
reader of the program what the variable represents.
17
Computer Programming
CONSTANTS
Constants are values that cannot be changed.

There are several types of constant


1. integer-constants
2. floating-point constants
3. character-constants
4. string constants
5. enumeration-constants

1. Integer Constant
An integer constant is consisting of a sequence of digits, beginning
with unary minus for negatives or an optional unary plus for
positives.
Integer constants may be written in the following forms:
 Decimal form without a prefix.
▪ Ex. 15
 Hexadecimal form with 0x or 0X prefix
▪ Ex. 0xF
 Octal form with 0 prefix
▪ Ex. 017
An integer constant may be suffixed by the letter
 unsigned integer constants can have the suffix u or U
▪ Ex. 123U
 long integer constants can have the suffix l or L
▪ Ex. 123L
 unsigned long integer constants can have the suffix ul or UL
▪ Ex. 123UL

2. Floating-point Constants
Floating-point constants are stored, on most computers, in a different
form from that of integers.
A floating-point value represents a real number.
The constant is of the type double unless a suffix is used to alter the
range and precision.
The suffixes are:
 The letter “F” or “f”, which makes it a float.
▪ Ex. 1.234F
 The letter “L” or “l” to make a long double.
▪ Ex. 1.234L

18
Computer Programming
There are two written representations:
1. f Notation
It is consisting of integer part, decimal point, fractional part,
optionally with one part omitted.

For example:
0.86 2.0 -0.005

2. e Notation
The letter e or E is used to separate the mantissa from the
exponent of the power of 10.

For example:
1.38E-23 or 1.38 x 10-23
1.5E1, 1.5e1, 15E0, .15e2, 150E-1 are all the same value.

Note:
Read E as “ times 10 to the power of…”
The exponent is of the integer type.

3. Character Constants
Character constants can be printable (like 0 to 9 and a to z) or non-
printable characters (such as new line, carriage return, or tab).
Printable character constants may be enclosed in single quotation marks
(such as ‘s’).
The value of a character constant with only one character is the numeric
value of the character in the machine’s character set at the execution
time.

Note:
The code used to represent characters is a subset of the American Standard
Code for Information Interchange (ASCII)-the most common 7-bit character
code. IECEP – 0x49,0x45, 0x43,0x45, 0x50
A=0x40 +1 = 0x41, E = 0x40+5 =0x45, M = 0x40+0x0D = 0x4D, 64+13
=77
A= 65, 64+1 = 65
a = A+space = 65+32 = 97
0=48
C uses an escape convention consisting of a character constant that
begins with a backslash and single lower case letter code for the
common control codes, and the further convention of either an octal or
hexadecimal number for any arbitrary code.
19
Computer Programming
The single letter codes or escape sequences are:

Newline \n Backslash \\
Horizontal tab \t Question mark \?
Vertical tab \v Single quote \’
Backspace \b Double quote \”
Carriage return \r Octal number \000
Form-feed \f Hex number \xff
Audible alert/bell \a
\‘a\’ – ‘a’
ASCII TABLE AND DESCRIPTION

20
Computer Programming

EXTENDED ASCII

ñÑ╢╔═╦═╗ñÑñÑαßΓ

IBM PC Keyboard Scan Codes


For many of the special key combinations such as ALT-A, F1, PgUp, and so forth,
the IBM PC uses a special two-character escape sequence. Depending on the
programming language being used and the level at which the keyboard is being
accessed, the escape character is either ESC (27, 0x1B), or NUL (0). Here are some
common sequences:

Char. Decimal Pair Hex Pair Char. Decimal Pair Hex Pair
ALT-A (00,30) (0x00,0x1e) ALT-B (00,48) (0x00,0x30)
ALT-C (00,46) (0x00,0x2e) ALT-D (00,32) (0x00,0x20)
ALT-E (00,18) (0x00,0x12) ALT-F (00,33) (0x00,0x21)

21
Computer Programming

4. Strings constants
A string constant is a one-dimensional array, or vector, of character
codes and has written form of a sequence of characters enclosed in a
pair of double quotation marks.
This requires the character code escape of \” for double quote itself,
should one be needed in a string.
Additionally, the escape sequences from the character constant codes
are supported.
It is possible to have an empty string, which is simply two double-
quote characters.

For example:
The string “ Nancy Jowel “ = Nancy Jowel
‘N’ ‘a’ ‘n’ ‘n’ ‘y’ ‘ ’ ‘J’ ‘o’ ‘w’ ‘e’ ‘l’ ‘\0’

This shows how the string “Nancy Jowel” is stored in the memory.
The value of the string constant is an address of where the characters
making up the string are stored. The compiler automatically places a
NUL character ‘\0’ at the end of the string in order for it to be possible
to find the end of the string.
Each memory byte contains the binary code for the character. The
value of the string is the address of the first byte.
The shortest string (the empty string) is “ “, which has just the NUL
character (‘\0’).

5. Enumeration constants
Enumerations are unique types with values ranging over a set of named
constants called enumerators.
The identifiers in an enumerator list are declared as constants of type
int, and may appear wherever constants are required.
The reserved word enum is used to assign sequential integer constant
values to a list of identifier.

The syntax is shown by:


enum TAG_NAME{list of constant name};

Example 1:
enum Boolean { FALSE , TRUE };

22
Computer Programming
In this case the constant names will be automatically assigned values
starting at 0, so that FALSE is 0 and TRUE is 1.
Example 2:
enum LETTER { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P };
The name A is assigned a constant value of 0, B of 1, C of 2, and so on.

An initial value may be forced as in


Example 3:
enum Order{ first=5, second, third, fourth };
Which will cause first to have a value of 5, and then each subsequent name
will be one greater. Second is 6, third is 7, and fourth is 8.

It is possible to follow a constant name with an “=” and then a literal


constant, for example:
Example 4:
enum tolerance {white=10, silver=5, gold=1};

One of the advantages of this method over that of using #define is that
variables of this may be able to issue warnings when inappropriate types
are assigned; the other advantage is that the values are automatically
assigned.
SEPARATORS
Separators are used to separate adjacent characters and to enhance
readability such as blanks, tabs and newlines.

OPERATORS
One of the characteristics of C is that it has a small set of keyword and a
rich set of operators.
Often, the operators have more than one use.
The specific function of an operator depends on the context in which it is
used.
Some examples are:
The plus ‘+’ character:
a+b ++a a+=b
In this example, the + character is used as an addition operation in
the first instance, as the pre-increment operator in the second, and
as an assignment operator in the third.

The percent ‘%’ character:


printf ( “%d”, a); a%7
The % character is used as a format control character in the first
statement. It is used as the modulus operator in the second.
23
Computer Programming
DECLARATION OF VARIABLES AND CONSTANTS
VARIABLE
It is a value that can be changed
It is a named memory location which temporarily stores data that can
change while the program is running.

VARIABLE DECLARATIONS
Variable declarations are statements that communicate to the compiler the
names of variables in the program and the kind of information stored in
each variable.
All variables must be declared before they can be used.
Declaring Variables
1. Choose the "type" you need.
2. Decide upon a name for the variable.
3. Use the following format (syntax) for a declaration statement:

datatype variable_identifier;

4. You may declare more than one variable of the same type by separating the
variable names with commas.
int Age;
float Weight, Height;

5. You can initialize a variable (place a value into the variable location) in a
declaration statement.

double mass = 3.45;


Note:
Variables that are not initialized are NOT empty.
If you do not initialize your variables, they will contain junk ("garbage")
values left over from the program that last used the memory they
occupy, until such time as the program places a value at that memory
location.
A good programming practice to develop is to declare variables at the
top of a function. Declaring variables in this manner makes for easier
readability of the program.

24
Computer Programming
Example:
1. For integer
int Age, Quantity;
int Age = 12, Quantity =100;
long int Quantity;
2. For floating-point and double
float Height, Weight, Grade;
float Height = 5.9;
double Price = 1000000.00;
3. For character
char MyInitial, MiddleInitial;
char MyInitial = ‘M’, MiddleInitial = ‘C’;
4. For string
char Name[20]; // Maximum of 20 characters
char Name[] = “Nancy Jowel McDonie”;
5. For array of integer and array of float
int Row[10], Column[12];
float buffer[6];
int Row[5] = { 1, 4, 5, 6,10 };
// where Row[0] = 1;Row[1] = 4;Row[2]=5;
Row[3] = 6;Row[4] = 10;

SCOPE OF VARIABLES
1. Global variable
A global or external variable is a memory space that is allocated by the
compiler and can be accessed by all the functions in a program
(unlimited scope).
It can be modified by any function and will remain its value to be used
by other functions.
It is declared outside of any function, before the program begins, above
the main() function.
2. Local variable
Local variables are memory spaces allocated by the function when the
function is entered, typically on the program stack.
These variables are not accessible from other functions, meaning that
their scope is limited to the functions in which they are declared.
The local variable declaration can be used in multiple functions without
conflict, because the compiler sees each of these variables as being part
of that function only.
It is declared inside the function after its opening curly bracket.
Note: If a local variable name has the same name with a global variable, the local
overwrites the global, but when function terminates, the global name is retained.
25
Computer Programming
CONSTANT
It cannot be changed within a program.

CONSTANT DECLARATION
Using const you can define an identifier whose values never change.
You MUST assign an initial value into a constant when it is declared.
If you do not place this initial value, C/C++ will not allow you to assign a
value at a later time.
Syntax:

const [data_type] constant_identifier_list;

Example:
const int AGE_LIMIT = 21; //this value cannot be changed
const float PI = 3.14159;
THE SEVEN BASIC ELEMENTS OF PROGRAMMING

1. Input
Input means reading values from the keyboard, from a disk, or
from an I/O port.
2. Output
Output means writing information to the standard output
(stdout), to a disk, or to an I/O port.
3. Data types
Data types are constants, variables, and structures that contain
numbers (integer and real), text (characters and strings), or
addresses (of variables and structures).
4. Operations
Operations assign one value to another, combine values (add,
divide, etc.), and compares values (equal, not equal, etc).
5. Conditional execution
Conditional execution means that your program executes a set
of instructions only if a specified condition is true (and skips
them if it is false).
6. Loops(iteration)
Loops execute a set of instructions some fixed number of times
or while some condition is true.
7. Subroutines
Subroutines are separately named sets of instructions that can
be executed anywhere in the program just by a reference to the
name.

26
Computer Programming
STANDARD INPUT/ OUTPUT FUNCTIONS

FUNCTION CALL
In C, it is used to call or activate a function.

Syntax of function:

[return_ data_type] Function_name([function arguments]);

FUNCTION ARGUMENT
Enclosed in parentheses following the function name; provides
information needed by the function.

INPUT OPERATION
It is an instruction that copies data from an input device into memory.

READING VALUES FROM THE KEYBOARD


scanf Funtion
Scans and formats input from stdin.

SYNTAX:
scanf(format_string, input_list);

EXAMPLE:
scanf(“%c”,&MiddleInitial);
scanf(“%f”,&Distance);

INTERPRETATION:
The scanf function copies into memory data typed at the
keyboard by the program user during program execution. The
format string is a quoted string of place holders, one
placeholder for each variable in the input_list. Each int,
double, or char variable in the input_list is preceded by an
ampersand(&).

OUTPUT OPERATION
It is an instruction that displays information stored in a memory.
INFORMATION TO THE STANDARD OUTPUT
printf Function
sends formatted output to stdout
27
Computer Programming

SYNTAX:
printf(format_string, print_list);
printf(format_string);
EXAMPLES:
printf(“I am %d years old, and my gpa is
%f\n”,age,gpa);
printf(“University of the East”);

INTERPRETATION:
The printf function displays the value of its formal string alter
substituting in left-to-right order the values of the expressions in the print
list for their placeholders in the format string and after replacing escape
sequence such as \n by their meanings.

Format string
A string of characters enclosed in quotes(“), which specifies the
form of the output line.
Print list
The variables or expressions whose values are displayed.
Placeholders
Symbols beginning with% in a format string that indicate where
to display each output value.
Placeholder Variable type Function use
%d , %i int, signed int or decimal form printf/scanf
%hd short int, or signed short int printf/scanf
%ld long int or signed long int printf/scanf
%u unsigned int or unsigned short int printf/scanf
%lu unsigned long int printf/scanf
%f float or double printf/scanf
%e, %E float( using e or E notation) printf/scanf
%g,%G assigned decimal digit in either e/E printf
form or f form whichever is shorter.
%lf, float or double scanf
%Lf, %Le long double printf/scanf
%c char printf/scantf
%s String printf/scanf
%o Octal printf/scanf
%x,%X Hexadecimal printf/scanf

28
Computer Programming

FORMATTING NUMBERS IN PROGRAM OUTPUT


Format
%Nd
This number (N) specifies how many columns are to be used for the
display of digits, the field width.
For example:
printf(“ Result: %3d meters = %4d ft. %2d in. \n”, meters, feet, inches);
Example:
Value Placeholder Printed Output
234 %4d #234
234 %5d ##234
234 %6d ###234
- 234 %4d -234
- 234 %5d #-234
- 234 %6d ##-234
234 %2d 234
234 %1d 234
- 234 %2d -234
The character # represents a blank character.

Formatting Values of type float or double


The form of the necessary format string placeholder is:
%N.Mf
where N is a number representing the total field width, and
M is the desired number of decimal places.

Value Placeholder Printed Output


3.14159 %5.2f #3.14
3.14159 %4.2f 3.14
3.14159 %3.2f 3.14
3.14159 %5.1f ##3.1
3.14159 %5.3f 3.142
3.14159 %8.5f #3.14159
3.14159 %.4f 3.1416
0.1234 %4.2f 0.12
-0.006 %4.2f -0.01
-0.006 %.4f -0.0060
-0.006 %8.5f -0.00600
-0.006 %8.3f ##-0.006

29
Computer Programming
C++ EXCEPTION HANDLING

An exception is a problem that arises during the execution of a program. A


C++ exception is a response to an exceptional circumstance that arises while
a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.

throw: A program throws an exception when a problem shows up. This is


done using a throw keyword.

catch: A program catches an exception with an exception handler at the


place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.

try: A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a


combination of the try and catch keywords. A try/catch block is placed around the
code that might generate an exception. Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch looks like the following:

try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}

You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.

30
Computer Programming
Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements.
The operand of the throw statements determines a type for the exception and can
be any expression and the type of the result of the expression determines the type
of exception thrown.

Following is an example of throwing an exception when dividing by zero condition


occurs:

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions:

The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.

try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify
that a catch block should handle any type of exception that is thrown in a try block,
you must put an ellipsis, ..., between the parentheses enclosing the exception
declaration as follows:
try
{
// protected code
}catch(…)
{
// code to handle ANY exception
}

31
Computer Programming
The following is an example, which throws a division by zero exception and we catch
it in catch block.

#include <iostream>
using namespace std;
double division(int a, int b)
{
if(b == 0)
{
throw "Division by zero condition!";
}
return (a/b);
}

int main()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}

Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run above
code, this would produce the following result:

Division by zero condition!

32
Computer Programming
C++ Standard Exceptions:
C++ provides a list of standard exceptions defined in <exception> which we can
use in our programs. These are arranged in a parent-child class hierarchy shown
below:

33
Computer Programming
Here is the small description of each exception mentioned in the above hierarchy −
Sr.No Exception & Description

1 std::exception
An exception and parent class of all the standard C++ exceptions.

2 std::bad_alloc
This can be thrown by new.

3 std::bad_cast
This can be thrown by dynamic_cast.

4 std::bad_exception
This is useful device to handle unexpected exceptions in a C++ program.

5 std::bad_typeid
This can be thrown by typeid.

6 std::logic_error
An exception that theoretically can be detected by reading the code.

7 std::domain_error
This is an exception thrown when a mathematically invalid domain is
used.

8 std::invalid_argument
This is thrown due to invalid arguments.

9 std::length_error
This is thrown when a too big std::string is created.

10 std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().

11 std::runtime_error
An exception that theoretically cannot be detected by reading the code.

12 std::overflow_error
This is thrown if a mathematical overflow occurs.

34
Computer Programming
13 std::range_error
This is occurred when you try to store a value which is out of range.

14 std::underflow_error
This is thrown if a mathematical underflow occurs.
Define New Exceptions
You can define your own exceptions by inheriting and overriding exception class
functionality. Following is the example, which shows how you can use std::exception
class to implement your own exception in standard way −
#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception {


const char * what () const throw () {
return "C++ Exception";
}
};

int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
This would produce the following result –

MyException caught
C++ Exception

Here, what() is a public method provided by exception class and it has been
overridden by all the child exception classes. This returns the cause of an exception.

35
Computer Programming

36

You might also like