What is Computer Program?
A computer program is a set of instructions that tells a computer what tasks to perform. We use programs to interact with and control computers.
On the other hand, computer programming is the process of creating those programs. It involves writing code using a text editor and a chosen programming language to develop software that performs specific tasks or solves problems.
Programming language is a formal system used to communicate instructions to a computer. It comprises a set of rules, symbols, and syntax that enables programmers to write code the computer can understand and execute. Programming languages are essential for developing software applications, websites, games, operating systems, and various other digital solutions.
Building blocks of a program are the essential structures and elements that form the foundation of any computer program. They are the core concepts that programmers rely on when designing, writing, and organizing code.
Building blocks of a program can be:
- Control Structures : within a program, control structures are programming components that dictate the direction of execution flow. Based on criteria or recurring events, they enable developers to specify how and when particular code blocks should be run. These structures typically include
- You can use an
if
statement to print a message only if the condition is met. - The
if-else
statement provides an alternate block of code to execute when the condition is false. - The
switch
statement allows checking a variable against multiple values and executing a matching block of code. - Functions: are strong tools that let you put a collection of instructions under one name and then use that group of instructions repeatedly in your program. Functions aid in the organization, modularity, and manageability of code. Code reusability and redundancy are reduced when you define a function only once and can call it from different sections of your code. Functions in C++ can be defined with a particular name, return type, and optional parameters.
- return_type: Specifies the type of data (such as
int
,void
, orfloat
) that the function will provide as an output. - function_name: The identifier that is used to call or invoke the function.
- parameters: Optional inputs that the function can accept, which may or may not be provided when calling the function.
- Function Body: The block of code within the function that performs the desired task or computation.
- return: If the function is designed to produce a value, it will use the return statement to send the result back.
- Objects and Classes: The ideas of classes and objects are central to object-oriented programming, or OOP. They enable you to represent and simulate real-world entities in a reusable and organized manner.
- Arrays and Lists:are data structures used in C++ is to store several values under a single variable, but their implementation and usage are very different. All of the elements in an array are kept close to one another in memory since arrays are fixed-size, contiguous blocks of memory. This makes it possible to use an index to quickly and consistently access elements.
However, it is inefficient to shift other components in order to add or remove elements because their size is defined at the time of declaration.
On the other hand, lists in C++ are implemented as doubly linked lists, notably std::list from the Standard Template Library. Lists provide efficient insertion and deletion at any place since each element is kept independently in memory and connected by pointers. - Exceptions or Error :Unexpected issues that may arise during program execution , and if they are not handled properly, they may result in program crashes or unpredictable behavior. This is where exception handling comes in, as it enables a program to handle these errors gracefully.
A programming method called exception handling is used to identify and handle errors—also known as exceptions,that arise while a program is running. When something goes wrong, it transfers control to a particular block of code called a catch block, which is intended to address the error, rather than letting the program crash. This method improves the program's dependability and user experience by ensuring that it can either operate continuously or terminate gracefully.
Conditional Statements
Conditional statements are used to control the flow of execution. They allow certain blocks of code to run only when specified conditions are true.
Basic programming constructs like if
, if-else
, and switch
fall under this category and help determine which code executes based on given criteria.
Looping Statements
Looping statements are essential for repeating a block of code until a certain condition is met or becomes false. This is useful for tasks like processing elements in a collection, doing repeated calculations, or automating repetitive tasks.
Common looping structures in C++ include for
, while
, and do-while
loops.
Syntax
return_type function_name(parameters) {
// Function body
return value; // Optional return statement
}
Note
#include <iostream>
using namespace std;
void introduce(string name) {
cout << "My Name is: " << name;
}
int main() {
introduce("Yilma");
return 0;
}
Class
Object
#include <iostream>
using namespace std;
class Department {
public:
string name; // Data member
void Detail() { // Member function
cout << "Department Name:" << name;
}
};
int main() {
Department dept; // dept is an object
dept.name = "Information Systems"; // Assign values to dept's data member
dept.Detail(); // Calling
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num[5] = {1,8,2,3,4}; // Fixed-size array
cout << "First element:" << num[0]; // Outputs 1
return 0;
}
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> num = {10, 2, 3}; // Declare and initialize a list of integers
num.push_back(4); // Add at the end
num.push_front(50); // Add at the beginning
cout << "elements:";
for (int value : num) {
cout << value;
}
return 0;
}
Note: The above building blocks make up the language of programming used to write software.
Basic elements:are the core components of any programming language, defining how a program is structured and how it operates. They are the most minimal and essential units required to create a program. These elements work within the rules of the language’s syntax, meaning they must follow specific formats and conventions.
Examples of basic elements include variables, data types, operators, constants, reserved keywords, and punctuation marks like semicolons,braces and Each of these elements plays a specific role in telling the computer what to do.
#include <iostream>
using namespace std;
int main() {
int a = 8; // 'int' is a data type, 'a' is a variable, '=' is an assignment operator
int b = 9;
int sum = a + b; // '+' is an arithmetic operator
cout<<"A: " <<a; // 'cout' is used for output
return 0;
}
Variables: Variables are designated (named) storage spaces in a computer’s memory that can hold values which may change during the program’s execution.They are fundamental to programming because they allow you to:
- Store information (like numbers, text, etc.)
- Retrieve and manipulate that information later
- Think of a variable like a labeled container where you can place something (a value), take it out, or replace it with something else
Identifier:is the name you assign to components in your software so you can refer to them later in the program. These components include variables, functions, classes, structures, objects, constants, namespaces, and more. The main goal of using identifiers is to provide both the computer and the programmer with a clear, readable, and distinct name for each element in the code. This helps improve understanding, organization, and control throughout the development process.
Note :all identifiers are not variables, even if all variables are identifiers.
Rules of Syntax for Identifiers
- Able to utilize underscores (_), numbers (0–9), and letters (A–Z, a–z).
- Not able to begin with a number.
- Special symbols like @, #, -, +, !, etc., cannot be used.
- Languages such as C++, Java, and JavaScript are case-sensitive (e.g., score and Score are different).
- Should not be the same as reserved keywords such as return, class, or int.
#include<iostream>
using namespace std;
struct Person { // 'Person' is an identifier for a structure
string name; // 'name' is an identifier (a member variable)
};
void info(string name) { // 'info' is an identifier for a function
cout<<"Name:"<<name;
}
int main() {
Person p1; // 'p1' is an identifier for a Person object
p1.name = "Tom";
info(p1.name);
return 0;
}
Literals : are fixed values that represent constant data and are written straight into the code. Because their meaning is clear-cut (self-evident) and remains constant while the program is running, they are also referred to as constant values.
Since literals are hardcoded into the program, their values are stated clearly and aren't determined by calculation or other factors. These values stay the same during the program's execution and cannot be changed. Because literals are fixed and direct, their meaning is obvious and self-evident simply by looking at them; no assessment or calculation is necessary.
Integer literals
-
Decimal: We utilize this conventional number system (0–9) on a daily basis.
Example:int x = 1;
-
Octal: Leading 0 (zero) is used at the beginning of octal literals. The only numbers used are 0–7.
Example:int y = 015;
-
Hexadecimal: Use numbers 0–9 and letters A–F, and start with
0x
or0X
.
Example:int z = 0xB;
-
Floating point literals: Real numbers represented with decimal points or scientific notation.
Example:double c = 2.5e2;
Character literals
char
and consist of a single character enclosed in single quotes.Example:
char grade = 'C';
Note: Every character literal corresponds to a Unicode or ASCII value. For instance, the ASCII value of 'A' is 65.
String literal
" "
). Even an empty set of quotes (""
) is a valid string literal representing an empty string.Example:
string name = "Yilma";
Note: The compiler automatically adds a null character ('\0') at the end of every string literal. Therefore, the total size of a string literal is always one character larger than the number of visible characters.i.e "abc" is same as "abc\0"
Constants: are variables with unchangeable fixed values. Once they are defined in the program, they are not changed while the program is running and kept in the program's code segment of memory as read-only tokens.Any C++ data type, including int, char, or string is acceptable for constants.
In c++,we can declare Constants in three ways:
const keyword
const
keyword in the variable definition.Syntax: →
const DATATYPE variable_name = value;
A constant variable must be initialized at the time of declaration because its value cannot be changed later in the program.
Example:
const int id = 30;
← OKconst int id; id = 30;
← Error (not allowed)
constexpr keyword
constexpr
are initialized at compile time.The
constexpr
keyword is compatible with MinGW GCC (GNU Compiler Collection).Syntax:
constexpr DATATYPE variable_name = value;
Example:
constexpr int hours = 24;
← OK
#define preprocessor
#define
preprocessor are called macro constants.This method is less preferable in C++ due to the lack of type safety.
Syntax:
#define MACRO_name replacement_value
Example:
#define Size 6
← OK
Keywords:are words with predefined meanings.In most programming languages, keywords are reserved words that developers and programmers cannot use as the names of variables,constants, or functions.
In programming languages, keywords such as int, return, if, for, and class have specific predefined meanings. For instance, if starts a conditional statement, for starts a loop, class defines a class, return returns a value from a function, and int declares an integer variable. Variables, functions, and other identifiers cannot be named using these reserved terms.
Comments :are text notes that provide an explanation about the source code.it serves as a source code documentation and make the program easier to read.
Datatypes: are the type of data it can store, the range of values it can hold. To instruct the computer on how to handle and understand the data stored in a variable, you assign it a datatype when you declare it.Data types assist the compiler or interpreter in deciding what kinds of operations are permitted on the data and allocating the proper amount of memory.
Data types can be
Primitive Data types
Example → Primitive data types:
- Integer numbers like 10 or -3 are stored in the
int
type. - A single character, such as "A" or "z," can be stored in the
char
type. - The
double
type offers better precision for larger or more precise decimal values, while thefloat
type stores values like 3.14. - Boolean values, either
true
orfalse
, are represented by thebool
type and are commonly used in logic and conditionals.
Non-primitive Data types
They support dynamic memory allocation, complex data structures, and object-oriented programming.
Examples: String, Arrays, and Classes are common non-primitive (reference) types.
String b = "world";
← creates a variable b
that holds the address of the string "world".
Expression In programming, an expression is a set of variables, operators, functions, and values that are evaluated to yield a different value. The equation a + b, for instance, evaluates to a single value after the + operator adds the values of a and b.
Three common categories can be used to classify expressions.
Arithmetic expression
Relational expression
Operators include:
less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=)
.
Logical expression
Common operators are:
AND (&&), OR (||), and NOT (!)
.
Statement: A statement in C++ is a single instruction that instructs the computer to carry out a certain task. It functions as a program's basic unit of execution.Simple activities like declaring a variable or more intricate ones like loops, conditionals, or function calls can all be done with statements. Statements run in the order they appear by default, unless control flow constructions change this.
Common Types of Statements
Expression Statements
Example:
y = 4;
(assignment statement)
Declaration Statement
Syntax:
data_type variable_name;
Example:
int age;
Control Flow Statement
- If statement: Executes a block if a condition is true.
- Else statement: Provides alternative execution if condition is false.
- For loop: Repeats code a set number of times.
- While loop: Repeats as long as a condition is true.
- Do-while loop: Executes at least once, then repeats if condition is true.
Jump Statement
Examples:
break
: Exit a loop or switch immediately.continue
: Skip to the next loop iteration.return
: Exit a function and optionally return a value.
Compound Statement
{ }
, used where a single statement is expected.Example:
{
int x = 16;
x += 5;
}
Function Call Statement
Example:
add();
Empty Statement
;
by itself that performs no action.Example:
for(int i=0; i<4; i++);
Switch Statement
Syntax:
switch(value) {
case 1: Statement 1; break;
case 2: Statement 2; break;
case 3: Statement 3; break;
}
Operators are unique class of functions that accept one or more parameters and return an altered result. It is a symbol that instructs the compiler to carry out the logical and mathematical operations. Operators in C++ can be
Common logical operators include:
AND (&&)
: Returns true only if all combined conditions are true.OR (||)
: Returns true if at least one condition is true.NOT (!)
: Negates a condition, changing true to false and vice versa.
=
, but compound operators combine assignment with arithmetic or bitwise operations.Example:
+=, -=, *=, /=, %=
combine arithmetic with assignment, while &=, |=, ^=, <<=, >>=
combine bitwise operations with assignment. These operators make code concise and efficient.
int a = 2; // binary: 0010
int b = 3; // binary: 0011
int c = a & b; // binary result: 0010 (decimal 2)
int a = 2; // binary: 0010
int b = 3; // binary: 0011
int c = a | b; // binary result: 0011 (decimal 3)
int a = 2; // binary: 0010
int b = 3; // binary: 0011
int c = a ^ b; // binary result: 0001 (decimal 1)
int a = 2; // binary: 0010
int b = ~a; // binary: 1101 (in 4-bit representation)
int a = 3; // binary: 0011
int c = a << 1; // binary result after left shift by 1: 0110 (decimal 6)
int a = 3; // binary: 0011
int c = a >> 1; // binary result after right shift by 1: 0001 (decimal 1)
if-else, switch
and loops for, while, do-while
are examples.Flow control statements are especially helpful for:
- Break out of a loop early
- In a loop, skip the current iteration.
- Go to a particular section of the code.
- Leave a function and give back a value.
In general, the concepts discussed above,demonstrated together using the following simple example.
#include <iostream>
using namespace std;
const int Value = 100; // const keyword
constexpr int HOURS = 24; // constexpr keyword
#define Size 5 // #define macro constant
void showMessage() { //Function definition
cout <<"Hello";
}
int main() {
showMessage(); //Function call
char sex = 'M'; //identifier
string studentName = "John"; // non-primitive identifier
int a = 10; //Decimal integer literal
int b = 012; //Octal literal (starts with 0)
int c = 0xA; //Hexadecimal literal (starts with 0x)
float d = 12.5; // Floating-point literal
char e = 'b'; //Character literal
string f = "Hello"; //String literal, implicitly ends with '\0'
const int age = 30; // Must be initialized at declaration
int total = a + b; //Arithmetic expression
bool isValid = score > 50; // Relational expression
if (score >= 50) { //Control flow statement
cout << "valid";
} else {
cout <<"Try again.";
}
for (int i = 0; i < 5; i++) { // Jump statement
if (i == 3) continue; // Skip when i is 3
cout << "i = " << i;
}
for (int i = 0; i < 3; i++); // Empty statement
int num = 2;
switch (num) { // Switch statement
case 1:
cout << "Number 1";
break;
case 2:
cout <<"Number 2";
break;
default:
cout << "Another number";
break;
}
int a = 5, b = 3;
int final;
final = a + b; //arithmetic operator
bool r = a > b; //relational operator
final = a = b; //assignment operator
final = a & b; //Bitwise AND operator
return 0;
}