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

Chapter 2 Basics of Programming

This document provides an overview of the fundamentals of C++ programming, including the structure of a C++ program, the Integrated Development Environment (IDE) for writing and compiling code, and the basic elements such as data types, variables, and operators. It explains how to write, compile, link, and run a C++ program, along with examples of basic syntax and operations. Additionally, it covers reserved keywords, identifiers, comments, and various types of operators used in C++.

Uploaded by

Simegn Mulugeta
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)
4 views

Chapter 2 Basics of Programming

This document provides an overview of the fundamentals of C++ programming, including the structure of a C++ program, the Integrated Development Environment (IDE) for writing and compiling code, and the basic elements such as data types, variables, and operators. It explains how to write, compile, link, and run a C++ program, along with examples of basic syntax and operations. Additionally, it covers reserved keywords, identifiers, comments, and various types of operators used in C++.

Uploaded by

Simegn Mulugeta
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/ 27

Fundamentals of Programming

Chapter Two
Basics of C++ Programming Language

By:- Tizazu B. (MSC Software Engineering)


Structure of C++ Program
A C++ program has the following structure
 [Comments]
 [Preprocessor directives]
 [Global variable declarations]
 [Prototypes of functions]
 [Definitions of functions]
 return 0; - indicates that the program ends successfully
C++ IDE(Integrated Development
Environment)
1. Writing a Program
 To write a source code, your compiler may have its own built-in
text editor, or you may be using a commercial text editor or
word processor that can produce text files.
 Examples of safe editors include Windows Notepad,
WordPad etc.
 The files you create with your editor are called source files.
 For C++ they typically are named with the extension .CPP.
2. Compiling
 Your source code file can't be executed, or run, as a program can.
 To turn your source code into a program, you use a compiler.
 Open the file you saved with .cpp extension.
 Example in Quincy, code blocks, Dev cppPortable
Go to Project>Click Compile or Press F5
After your source code is compiled, an object file is produced.
Cont’d….
3. Linking : C++ programs are typically created by linking together one or
more .OBJ files with one or more libraries.
 A library is a collection of linkable files that were supplied with your
compiler, that you purchased separately, or that you created and
compiled.
 All C++ compilers come with a library of useful functions (or
procedures) and classes that you can include in your program.
4. Running
 After completion of the compiling your program should be executed
something that you provided.
 To run your program is the final step of development cycle in C++
Example in Quincy: Go to Debug>Click Run or Press F9
Summary
• Create a source code file, with a .CPP extension.
• Compile the source code into a file with the .OBJ extension.
• Link your OBJ file with any needed libraries to produce an executable
program.
• Run your program
Showing Sample Code
For example, the following is a very basic C++ program:
1: #include <iostream.h>//sample programs
3: int main()
{
cout << "Hello World!\n";
return 0;
}
Description
 include is a preprocessor instruction that says, "What follows is a
filename.
 iostream.h (Input-Output-Stream) is used by cout, which assists with
writing to the screen.
 The preprocessor translates any line that begins with a pound symbol (#)
into a special command, getting your code file ready for the compiler.
 main(). Every C++ program has a main() function.
 cout, followed by the output redirection operator (<<) and enclosed by
double quotes(“ ”)
Basic Elements of programming
language
 Reserved/Key words have a unique meaning within a C++ program.
 All reserved words are in lower-case letters.
 The following are some of the reserved words of C++.

Asm auto bool break case catch


const_cast class const char continue default
dynamic_cast do double delete else enum
Explicit extern false float for friend
Goto if inline int long mutable
namespace new operator private protected public
reinterpret_cast register return short signed sizeof
static_cast static struct switch template this

Throw true try typedef typeid typename


Union unsigned using virtual void volatile
wchar_t
Identifiers
 An identifier is name associated with a function or data object and used
to refer to that function or data object.
 Identifiers are case sensitive(small letters and capital letters are different
for c++).
 No need of space between identifier characters.
 Start with a letter or underscore
 Consist only of letters, the digits 0-9, or the underscore symbol _
 Not be a reserved word
Length days_in_year DataSet1 Profit95
 Valid identifier Int _Pressure first_one first_1

 Invalid identifier days-in-year 1data int first.val


Throw my__best No## bestWish!
Comments
 A comment is a piece of descriptive text which explains some aspect of a
program.
 Program comments are text totally ignored by the compiler and are only
intended to inform the reader how the source code is working at any particular
point in the program.
 A comment is a piece of descriptive text which explains some aspect of a
program.
 Program comments are totally ignored by the compiler and are only intended
for human readers.
 C++ provides two types of comment delimiters:
1. Single line comment:- Anything after // (until the end of the line on
which it appears) is considered a comment.
2. Double line comment:- Anything enclosed by the pair /* and */ is
considered a comment.
Variables
A variable is a reserved place in memory to store information or
some values.
Variables are used for holding data values so that they can be
used in various computations in a program.
All variables have three important properties:
 Data Type: a type which is established when the variable is
defined. (e.g. integer, real, character etc). Data type
describes the property of the data and the size of the
reserved memory
 Name: a name which will be used to refer to the value in
the variable. A unique identifier for the reserved memory
location.
 Value: a value which can be changed by assigning a new
value to the variable.
Variable Declaration
• Declaring a variable means defining (creating) a variable.
• Variable is the name of memory location allocated by the compiler
depending upon the datatype of the variable.
• Examples
 int i; // declared but not initialised
 char c;
 int i, j, k; // Multiple declaration
int for variable with integral values

char For variables to store character types.

bool For variable to store boolean values( True or False )

float and double are also types for variables with large and floating point values
Cont’d….
Example
#include <iostream>
using namespace std;
int main()
{
int x=10; // Initialized once
int y=20; // Initialized again
cout <<“x = "<< x<<endl;
cout <<“y= "<< y<<endl;
cout <<“First value of x = "<< x;
cout <<“The value of y= "<< y;
return 0;
}
#Question: What will be the out put?
Basics of Data Types
 Data types are sets (ranges) of values that have similar
characteristics.
 Several data types are built into C++.
 Basic (fundamental) data types in C++ can be
conveniently divided into numeric and character types.
 Numeric variables can further be divided into integer
variables and floating-point variables.
 The numeric data type can be short, long, signed and
unsigned.
 Signed integers are either negative or positive.
 Unsigned integers are always positive.
Cont’d.....
Data Type Size Range of Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to 2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256 character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
Example to display correct size of various data types
// correct size of various data types
#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;
cout <<"Size of wchar_t : "<<sizeof(wchar_t)<< endl;
return 0;
}
Operators
 C++ provides operators for different expressions.

 The most fundamental operators are:

1. Arithmetic (operand) operators

2. Assignment operators

3. Relational operators

4. Logical operators

5. Increment/decrement Operators

6. Precedence operators.
Arithmetic (operand) operators

Except for remainder or modulo (%), all other


arithmetic operators can accept a mix of integers and
real operands.
if both operands are integers then, the result will be
an integer.
Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 //gives 1
Sample program for Arithmetic Operator
#include <iostream>
using namespace std;
int main()
{
double x, y;
cout << "Enter two floating-point values: \n ";
cin >> x >> y;
cout << "The average Value is: “ << (x + y)/2.0 <<
endl;
return 0;
}
Exercise
1. What is the output of the above C++ Program?
2. Write the program that will display the sum, product and difference of two numbers?
Assignment Operators
 An assignment operation is itself an expression whose value is
the value stored in its left operand.
 The assignment operator causes the operand on the left side of
the assignment statement to have its value changed to the value
on the right side of the statement.
 The assignment operator assigns a value to a variable.
 Syntax: Operand1=Operand2;
 Examples:
• A literal constant: Eg: x=12;
• A variable: Eg: x=y;
• An expression: Eg: x=y+2;
Relational Operators
 In order to evaluate a comparison between two expressions we can
use the relational and equality operators.
 The result of a relational operation is a Boolean value that can only
be true or false, according to its Boolean result.
 If the result is true it can be executes 1 and if is false it executes 0
Relational operators
Operator Name Example

== Equality 5 == 5 // gives 1

!= Inequality 5 != 5 // gives 0

< Less Than 5 < 5.5 // gives 1


<= Less Than or Equal 5 <= 5 // gives 1

> Greater Than 5 > 5.5 // gives 0


>= Greater Than or Equal 6.3 >= 5 // gives 1
Cont’d….
#include <iostream>
using namespace std;
int main()
{
int i=2, j=8;
cout<<(i==j)<<endl; //outpt 0
cout<<(i!=j)<<endl; //outpt 1
cout<<(i>j)<<endl; //outpt 0
cout<<(i<j)<<endl; //outpt 1
cout<<(i>=j)<<endl; //outpt 0
cout<<(i<=j)<<endl; //outpt 1
return 0;
}
Logical Operators
 The Operator ! is the C++ operator to perform the Boolean
operation NOT, it has only one operand,
 The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
 The operator && corresponds with Boolean logical operation
AND,
 This operation results true if both its two operands are true,
and otherwise false.
 The operator || corresponds with Boolean logical operation OR.
 This operation results true if either one of its two operands
is true, thus being false only when both operands are false
themselves.
Cont’d…
Sample program to evaluate the logical Operator
#include <iostream>
using namespace std;
int main()
{
int i=6, j=10;
cout<<!(5==5)<<endl;//outpt 0
cout<<(i>1&&j>6)<<endl;//outpt 1
cout<<(i>j||j<i)<<endl; //outpt 0
cout<<(i<j||j>i)<<endl;//outpt 0
return 0;
}
Increment/decrement Operators
 The increment operator ++ modifies the operand by adding 1 to
its value and cannot be used with constants for this reason.
 ++i i is incremented first and the new value of i is then applied.
 i++ the original value of i is applied before i is incremented.
 The decrement operator -- modifies the operand by reducing the
value of the operand by 1.
 Example:
int i=2, j=8;
cout << i++ << endl; // Output: 2
cout << i << endl; // Output: 3
cout << j-- << endl; // Output: 8
cout << --j << endl; // Output: 6
C++ Code for increment/decrement operator
//increment and decrement operator
#include<iostream>
using namespace std;
int main()
{
int x=100;
cout<<"The Value of X is : "<<x<<'\n';
cout<<"The Value of X is : "<<x++<<'\n';
cout<<"The Value of X is : "<<++x<<'\n';
cout<<"The Value of X is : "<<x--<<'\n';
cout<<"The Value of X is : "<<--x<<'\n';
return 0;
}
Precedence Operators
 The order in which operators are evaluated in an expression is
significant and is determined by precedence rules.
 These rules divide the C++ operators into a number of precedence
levels.
 Operators in higher levels take precedence over operators in lower
levels.
Eg.
a == b + c * d
c * d is evaluated first because * has a higher precedence
Class Exercise
1. Write a C++ code that displays your name and department?
2. Write a C++ code that displays the division and Modulation
results and compare two variables in logical operator types.
Hint take x and y and values 44 and 58 respectively.
3. Based on the question #2, write a program that will compare
and contrast in different relational operator type and display
the output.
4. Consider question no#2, if the value of x is incrementing by
two times and decrementing by two times of the y. what will
be the finial result of x and y. write with c++ code.
5. Write a C++ program that accepts input from keyword and
display the inputs. Hint: input to be Name, Gender, Age,
CGPA and your hobbies.

You might also like