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

C-Tutorials-Session-1

The document provides a comprehensive guide on installing a C++ compiler and IDE, basic syntax, and program structure, including examples of a simple C++ program. It covers essential concepts such as classes, objects, methods, variable types, data types, variable scope, and operators in C++. Additionally, it explains how to compile and execute C++ programs, along with input methods and comments.

Uploaded by

svenkudo013
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-Tutorials-Session-1

The document provides a comprehensive guide on installing a C++ compiler and IDE, basic syntax, and program structure, including examples of a simple C++ program. It covers essential concepts such as classes, objects, methods, variable types, data types, variable scope, and operators in C++. Additionally, it explains how to compile and execute C++ programs, along with input methods and comments.

Uploaded by

svenkudo013
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Installation of Compiler and IDE

- What we need is a compiler, GNU G++/ GCC and an Integrated Development Environment (IDE)
Bloodshed Dev C++.

Basic Syntax
- When we consider a C++ program, it can be defined as a collection of objects that communicate via
invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant
variables mean.

 Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors
- wagging, barking, and eating. An object is an instance of a class.
 Class - A class can be defined as a template/blueprint that describes the behaviors/states that object of its type
support.
 Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the
logics are written, data is manipulated and all the actions are executed.
 Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values
assigned to these instant variables.

C++ Program Structure


Let us look at a simple code that would print the words Hello World.

#include <iostream>
using namespace std;
// main() is where program execution begins.
int main()
{
cout << "Hello World" ;
return 0;
}

Let us look at the various parts of the above program:


1. The C++ language defines several headers, which contain information that is either necessary or useful
to your program. For this program, the header <iostream> is needed.
2. The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively
recent addition to C++.
3. The next line ‘// main() is where program execution begins.’ is a single-line comment available in
C++. Single-line comments begin with // and stop at the end of the line.
4. The line int main() is the main function where program execution begins. It uses the “{}” as the body
of the main function.
5. The next line cout << "Hello World”; causes the message "Hello World" to be displayed on the screen.
6. The next line return 0; terminates main() function and causes it to return the value 0 to the calling
process.

Compile & Execute C++ Program


Let's look at how to save the file, compile and run the program. Please follow the steps given below:

1. Open Bloodshed Dev C++ and add the code as above.


2. Save the file as filename.cpp using Ctrl+S or simply Ctrl+F9 to compile and save.
3. Run the program using Ctrl+F10.
4. Press F9 to compile & run the program.
Semicolons & Blocks in C++
- In C++, the semicolon “;”is a statement terminator. That is, each individual statement must be ended with
a semicolon. It indicates the end of one logical entity.
For example, following are three different statements:

x = y;
y = y+1;
add(x, y);

A block is a set of logically connected statements that are surrounded by opening and closing braces. For example:
{
cout << "Hello World" ; // prints Hello World
return 0;
}

C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a
statement in a line. For example:
x = y; is the same as
y = y+1; x = y; y = y+1; add(x, y);
add(x, y);

C++ Identifiers
- A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined
item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).
- C++ identifier is also known as “variable name”.
- C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive
programming language. Thus, Manpower and manpower are two different identifiers in C++.

Here are some examples of acceptable identifiers:


Name1 firstName last_name Age salary asdasda

C++ Keywords
- The following list shows the reserved words in C++. These reserved words may not be used as constant
or variable or any other identifier names.

asm const else friend new short this unsigned


auto const_cast enum goto operator signed throw using
bool continue explicit if private sizeof true virtual
break default export inline protected static try void
case delete extern int public static_cast typedef volatile
catch do false long register struct typeid wchar_t
char double float mutable reinterpret_cast switch typename while
class dynamic_cast For namespace return template union
Whitespace in C++
- A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler
totally ignores it.
- Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify where one
element in a statement, such as int, ends and the next element begins.
Example:
int age=16 ;

In the above statement there must be at least one whitespace character (usually a space) between int and age for
the compiler to be able to distinguish them.

Comments in C++
- Program comments are explanatory statements that you can include in the C++ code. These
comments help anyone reading the source code. All programming languages allow for some
form of comments.
- C++ supports single-line and multi-line comments. All characters available inside any
comments are ignored by C++ compiler.
- C++ comments start with /* and end with */.
For example:
/* This is a comment */

/* C++ comments can also


Span multiple lines
like this
*/

A comment can also start with //, extending to the end of the line.
For Example:
#include <iostream>
Using namespace std;

Int main()
{
cout << “Hello World!”; // prints Hello World!

Return 0;
}

When the above code is compiled, it will ignore // prints Hello World and final executable will produce the
following result.:

Hello World!
Data Types
- While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
- You may like to store information of various data types like character, wide character, integer,
floating point, double floating point, boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory

Primitive Built-in Types

C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types:

Type Keyword
Boolean bool
Character char
Integer int
Floating Point float
Double Floating Point double
String string
Void void

Several of the basic types can be modified using one or more of these type modifiers:
 signed
 unsigned
 short
 long

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
Unsigned char 1byte 0 to 255
Signed char 1byte -127 to 127
Int 4bytes -2147483648 to 2147483647
Unsigned int 4bytes 0 to 4294967295
Signed int 4bytes -2147483648 to 2147483647
Short int 2bytes -32768 to 32767
Unsigned short int Range 0 to 65,535
Signed short int Range -32768 to 32767
Long int 4bytes -2,147,483,647 to 2,147,483,647
Signed long int 4bytes -2,147,483,647 to 2,147,483,647
Unsigned long int 4bytes 0 to 4,294,967,295
Float 4bytes +/- 3.4e +/- 38 (~7 digits)
Double 8bytes +/- 1.7e +/- 308 (~15 digits)
Long double 8bytes +/- 1.7e +/- 308 (~15 digits)

The sized of variables might be different from those shown in the above table, depending on the compiler and the
computer you are using.

Following is the example, which will produce correct size of various data types on your computer.
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;

return 0;
}

This example uses endl, which inserts a new-line character after every line and << operator
is being used to pass multiple values out to the screen. We are also using sizeof() function
to get size of various data types.

When the above code is compiled and executed, it produces the following result which can
vary from machine to machine:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8

Variable Types
- A variable provides us with named storage that our programs can manipulate. Each variable
in C++ has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable.
- The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C++ is case-sensitive:

There are following basic types of variable in C++ as explained in last chapter:
Type Description
bool Stores either value true or false.
char Typically, a single octet (one byte). (used for characters)
int The most natural sized of integer for the machine.
float A single-precision floating point value. (used for decimal numbers)
double A double-precision floating point value. (used for decimal numbers)
string Contains a collection of characters surrounded by double quotations.
void Represents the absence of type.
Variable Definition in C++
- A variable definition tells the compiler where and how much storage to create for the variable.
- A variable definition specifies a data type, and contains a list of one or more variables of that
type as follows:

Type variable_name;

Here, type must be a valid C++ data type including, char, int, float, double, bool or any user-defined object, etc.,
and variable_name may consist of one or more identifier names separated by commas. Some valid declarations
are shown here:
int i, j, k;
char c, ch;
float f, salary;
string s;

The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create
variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer consist of an equal sign
followed by a constant expression as follows:
Type variable_name = value;
Some examples are:

int i = 3, j = 4, k = 5; string s = “Christian Langit”


char c = ‘A’, ch = ‘B’
float f = 10.5, salary = 10000.50
double d = 10000000000.50

- A variable declaration provides assurance to the compiler that there is one variable existing
with the given type and name so that compiler proceed for further compilation without
needing complete detail about the variable. A variable declaration has its meaning at the time
of compilation only, compiler needs actual variable declaration at the time of linking of the
program.
- A variable declaration is useful when you are using multiple files and you define your variable
in one of the files which will be available at the time of linking of the program.

Variable Scope
A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
 Inside a function or a block which is called local variables,
 In the definition of function parameters which is called formal parameters.
 Outside of all functions which is called global variables.

We will learn what a function is, and its parameter in subsequent chapters. Here let us explain what local and
global variables are.
Local Variables
- Variables that are declared inside a function or block are local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not
known to functions outside their own. Following is the example using local variables:
#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
- Global variables are defined outside of all the functions, usually on top of the program. The
global variables will hold their value throughout the life-time of your program.
- A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration. Following is the example using global
and local variables:
#include <iostream>
using namespace std;
int g;
int main () {
// Global variable declaration and initialization
int a = 10;
int b = 20;
int g = a + b;
cout << g;
return 0;
}

GETTING INPUT FROM THE KEYBOARD


#include <iostream>
using namespace std;
int main () {
int num1 = 300;
string name = “Christian Langit”; What if, we want to input the values from
int age = 22; the keyboard when the terminal pops out?
string address = ”Tanza, Cavite, Philippines”; What should we do and use?

cout<<num1<<endl;
cout<<name<<endl;
cout<<age<<endl; “cin” will takes its place. 😊
cout<<address<<endl;
cin>> variable_name;
return 0;
}
Operators
- An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators:

 Arithmetic Operators
 Increment/Decrement Operators
 Assignment Operators
 Relational Operators
 Logical Operators

Arithmetic Operators
The table below shows the following arithmetic operators supported by C++ Language:

Assume that variable A holds 20 and variable B holds 10, then:


Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A – B will give 10
* Multiplies both operands A * B will give 200
/ Divides numerator by denominator A / B will give 2
% Modulus Operator and remainder of after an integer division A * B will give 0

Increment/Decrement Operators
The table below shows the following increment/decrement operators supported by C++ Language.

Operator Description Example


++ Increment operator, increases integer value by one A++ will give 21 | B++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 19, | B-- will give 9

Assignment Operators
The table below shows the following assignment operators supported by C++ Language.

Operator Description Example


= Assigns the value on the right to the variable on the left. A = 20
+= Adds the current value of the variable on left to the value on the A += B)
right and then assigns the result to the variable on the left. can be written as
A=A+B will give 30
-= Subtracts the current value of the variable on left from the value A -= B
on the right and then assigns the result to the variable on the left. can be written as
A=A-B will give 10
*= Multiplies the current value of the variable on left to the value on A *= B
the right and then assigns the result to the variable on the left. can be written as
A=A*B will give 200
/= Divides the current value of the variable on left by the value on A /= B
the right and then assigns the result to the variable on the left. can be written as
A=A/B will give 2
%= Divides the current value of the variable on left by the value on A %=B
the right and then assigns the remainder as a result to the variable Can be written as
on the left. A=A%B will give 0
Developing Algorithms
- Algorithms
- Flowchart
- Psuedocode

In mathematics and computer science, an algorithm is a finite sequence of well-defined, computer-implementable


instructions, typically to solve a class of problems or to perform a computation. Algorithms are unambiguous
specifications for performing calculation, data processing, automated reasoning, and other tasks

A flowchart is a pictorial representation of a step-by-step solution to a problem. It consists of arrows representing


the direction the program takes and boxes and other symbols representing actions. It is a map of what your
program is going to do and how it is going to do it.

Start

Initialization Read Income


and Cost
Start or End
Income >= Yes Calculate Profit as
Do Something Cost? Income - Cost
No
Input or Output
Calculate Loss as
Decision Cost - Income

Decision of Flow Print/Display Print/Display


Loss Profit
On-page
Reference End

Figure 1: Flow Chart Symbols and Flow Chart for Calculating the Profit/Loss when Income=1000, cost=800

Pseudocode is an English-like nonstandard language that lets you state your solution with more precision than
you can in plain English but with less precision than is required when using a formal programming language.
Pseudocode permits you to focus on the program logic without having to be concerned just yet about the precise
syntax of a particular programming language. However, pseudocode is not executable on the computer.

Pseudocode
1. Start
2. Read Income as 1000, cost as 800
3. Income >=Cost? or 1000>=800
4. If yes: Calculate Profit as Income(1000)-Cost(800)
If no: Calculate Loss as Cost(800)-Income(1000)
5. Print/Display Profit
Print/Display Loss
6. End

You might also like