1.1 Statements and the structure of a program
Understanding Statements
A
computer program is a set of instructions for the computer to execute. In C++,
an instruction that makes the program do something is called a statement.
Statements are like sentences in a language, conveying complete ideas. Most
statements in C++ end with a semicolon (;).
For example:
std::cout
<< "Hello, world!";
This line is a statement that tells the computer to display "Hello, world!" on the screen.
Types of Statements
There are
various kinds of statements in C++:
1.
Declaration statements - The declaration statement establishes
a name and associated data type.
Eg:
int x;
2.
Expression statements - An expression is something that can
be evaluated to a value.
Eg:
x = 5;
3.
Compound statements - A group of statements contained
in curly brackets {} is a compound statement.
Eg: if(x <= 5)
{
int y = 10;
x = y + 5;
}
4.
Selection statements - A selection
statement selects one of the several possible control flows.
These are following
types of selection statements:
if
statement, Nested if, if else statement, switch
Statement
5.
Iteration statements - iteration refers
to looping through the contents.
These include while
loop, do-while loop, range for loop, for
loop
Eg:
for (int i = 0; i <
5; ++i) {
std::cout << i;
}
6.
Jump statements - Jump statements enable one
to modify a program's flow by jumping to a specific section of code.
These include break
statement, continue statement, goto statement, return statement
Eg:
return 0;
Functions and the Main Function
A function is a block of code that performs a specific task. Every C++ program must have a main function, which is the starting point of the program.
Example
of a simple C++ program:
1.
#include
<iostream>
2.
int
main() {
3.
std::cout
<< "Hello, world!";
4.
return
0;
5.
}
Here #include
<iostream> includes the standard library for input and output, int main()
defines the main function, {} indicate the start and end of the main function's
body.
Conclusion
C++ programs are
built from statements organized into functions, with main being the entry
point. Understanding the different types of statements and their syntax is
crucial for writing and debugging C++ programs effectively.
1.2 Comments
Comments
in programming are notes added to the code to help programmers understand and
remember the purpose of the code. These notes are ignored by the compiler and
are only for human readers.
Types of Comments in C++
In
C++, there are two types of comments:
1. Single-line comments: These start with // and continue to the end of the line. Single-line comments are useful for brief notes, to keep the code readable
Eg: std::cout << "Hello world!"; // Prints "Hello world!" to the console
2. Multi-line comments: These start with /* and end with */. They can span multiple lines.
Eg: /* To calculate the final grade,
we sum all the weighted midterm and homework scores and
then divide by the number of scores*
Commenting Out Code
To
temporarily disable code, you can comment it out. This can be done using //
for single lines or /* */ for blocks of code.
Reasons to Comment Out Code:
· To compile and run the program when parts of the code are not ready.
· To debug by isolating parts of the code causing errors.
· To try new code while keeping the old code for reference.
Best Practices
· Comment generously and write as if explaining to someone unfamiliar with the code.
· Avoid redundant comments that state the obvious.
· Use comments to clarify the purpose and reasoning behind the code.
1.3 Introduction
to objects and variables
In
C++, direct access to memory is discouraged. Instead, we use objects to store
values. An object is a region of memory with associated properties. A variable
is a named object.
An object stores a value in memory, and a
variable is an object with a name.
Eg: int x; // defines a
variable named x of type int
At
compile time, the compiler notes that x is an integer variable. When the
program runs, x is assigned a memory address and can be used to store
values.
Data Types
A
data type determines what kind of value an object can store.
For example:
· int x; defines an integer variable x, which can store integers.
· double width; defines a double variable width, which can store decimal numbers.
Variables
must have a known type at compile-time, and this type cannot be changed without
recompiling the program.
Eg: double width; // defines a
variable named width of type double
Defining Multiple Variables
You
can define multiple variables of the same type in a single statement by
separating them with commas.
Eg: int a, b; // defines two
integer variables, a and b
Best Practice: Define each variable on its own line for clarity.
int a; // variable a for
storing integer values
double b; // variable b for storing double values
Conclusion
In
C++, objects access memory, and named objects are called variables. Variables
have an identifier, type, and value. The type determines how the value is
interpreted. Using objects and variables, programmers can manage data
effectively without worrying about the underlying memory management.
1.4 Variable
assignment and initialization
In
C++ , it involves giving a value to a variable after it has been defined. This
process is called assignment, and the operator used is the assignment operator
(=).
Eg:
int
width; // define an integer variable named width
width
= 5; // assignment of value 5 into variable width
Initialization
is the process of specifying an initial value for an object. This can be done
in several ways:
Different
Forms of Initialization
1. No Initializer (Default Initialization): int a;
2. Initial Value after Equals Sign (Copy Initialization): int b = 5;
3. Initial Value in Parenthesis (Direct Initialization): int c( 6 ); //// define variable c and initialize with value 5
4. Initial Value in Braces (Direct List Initialization): int d { 7 }; // define variable width and initialize with initial value 5
5. Initial Value in Braces after Equals Sign (Copy List Initialization): int e = { 8 };
6. Initializer is Empty Braces (Value Initialization): int f {}; // define variable f and initialize with default value
· Prefer direct list initialization (or value initialization) for initializing variables.
· Initialize variables upon creation.
· Avoid initializing multiple variables in a single statement.
1.5 Introduction
to iostream: cout, cin, and endl
iostream in C++
The iostream library
is a fundamental part of C++ that provides input and output functionality using
streams. It is used to interact with the standard input and output streams,
which are cin and cout, respectively. The library also includes
other stream objects like cerr and clog for error handling
and logging.
Key Components of iostream
1. cout:
· cout is an instance of the ostream class, which is used
for outputting data to the standard output stream.
·
It is used with the insertion operator << to insert data
into the stream.
Example:
#include
<iostream>
int
main() {
int x = 5;
std::cout << "The value of x is:
" << x << std::endl;
return 0;
}
2. cin:
· cin is an instance of the istream class, which is used
for inputting data from the standard input stream.
·
It is used with the extraction operator >> to extract
data from the stream.
Example:
#include <iostream>
int
main() {
int x;
std::cout << "Enter a number:
";
std::cin >> x;
std::cout << "You entered:
" << x << std::endl;
return 0;
}
3. endl:
·
endl is a manipulator that inserts a new line and flushes the
output buffer.
·
It is used to separate output lines.
Example:
#include
<iostream>
int
main() {
int x = 5;
std::cout << "The value of x is:
" << x << std::endl;
std::cout << "This is a new
line." << std::endl;
return 0;
}
Why Use iostream?
1. Increased Type-Safety: iostream provides type-safe input and output operations.
2. Reduced Errors: It eliminates the need for redundant tokens and reduces errors.
3. Extensibility: It allows for easy input and output of user-defined types.
4. Inheritability: It provides real classes like std::ostream and std::istream that can be inherited to create user-defined types.
Conclusion
The iostream library
is a powerful tool in C++ that simplifies input and output operations.
Understanding cout, cin, and endl is essential for
effective use of the library.
1.6 Uninitialized variables and undefined behaviour
Uninitialized Variables
Uninitialized
variables in C++ are variables that have not been assigned a value before they
are used. This can lead to unexpected behavior and errors.
Undefined Behavior
Undefined
behavior is a result of various factors such as:
1. Uninitialized Variables: Reading the value of an uninitialized variable is undefined behavior.
2. Using Pointers to Deallocated Memory: Accessing memory that has been deallocated is undefined behavior.
3. Out-of-Bounds Memory Access: Accessing memory outside the bounds of an array or other data structure is undefined behavior.
Examples of Undefined Behavior
1. Uninitialized Variable Read:
unsigned int x;
std::cout << x; // undefined behavior
2. Signed Integer Overflow:
int x = INT_MAX;
x++; // undefined behavior
Best Practices1. Compiler Optimizations: Undefined behavior can lead to unexpected compiler optimizations that change the program's behavior.
2. Portability: Undefined behavior can make the program non-portable across different platforms.
3. Debugging: Undefined behavior can make it difficult to debug the program.
1. Initialize Variables: Always initialize variables before using them.
2. Check for Errors: Check for errors and handle them properly to avoid undefined behavior.
3. Use Safe Functions: Use safe functions that handle errors and undefined behavior.
Conclusion
Uninitialized
variables and undefined behavior are common pitfalls in C++ programming.
Understanding these concepts and following best practices can help prevent
errors and ensure the reliability of your code.
1.7 Keywords
and naming identifiers
Keywords are predefined words that have
special meanings to the compiler. They are reserved for specific purposes and
cannot be used as identifiers. Here is a list of C++ keywords:
throw, true.
try, typedef, typeid, typename etc
Identifiers
are the unique names given to variables, classes, functions, or other entities
by the programmer. They can be composed of letters, digits, and underscores,
but must begin with a letter or underscore. Here are some examples of valid and
invalid identifiers:
Eg:
// Valid identifiers
int money;
double accountBalance;
// Invalid identifiers
int 1list;
int float;
Best Practices for Naming
Identifiers
1. Use Meaningful Names: Choose names that clearly indicate the purpose of the variable or function.
2. Use Consistent Naming Conventions: Use either underscore-separated or camelCase naming conventions consistently throughout your code.
3. Avoid Reserved Names: Avoid using keywords as identifiers, and avoid names that start with underscores unless they are part of a standard library or OS function.
4. Use Case-Sensitive Names: C++ is case-sensitive, so ensure that your identifiers are consistent in their case usage.
Conclusion
In
C++, keywords and identifiers are crucial components of the language.
Understanding the differences between them and following best practices for
naming identifiers can help ensure that your code is readable, maintainable,
and efficient.
1.8 Whitespace
and basic formatting
Whitespace
in C++ refers to characters used for formatting purposes, primarily spaces,
tabs, and newlines. It is used to:
1. Whitespace is necessary to separate certain language elements, such as keywords and identifiers, to ensure the compiler can distinguish them.
2. Whitespace is used to make code easier to read by aligning values or comments and adding spacing between blocks of code.
Basic
formatting in C++ includes:
1. Indentation: Indentation is used to indicate the level of nesting within a block of code. It is generally recommended to use either tabs or spaces for indentation, with a consistent width.
2. Function Braces: There are two conventional styles for function braces: placing the opening curly brace on the same line as the statement or on its own line. This section follows the common alternative where the opening brace appears on its own line.
3. Statement Alignment: Each statement within curly braces should start one tab in from the opening brace of the function it belongs to.
4. Line Length: Lines should not be too long. Typically, 80 characters has been the de facto standard for the maximum length a line should be. If a line is going to be longer, it should be split into multiple lines.
Eg:
#include
<iostream>
using
namespace std;
int
main() {
int x, y = 1;
cin >> x;
while(x > 0) {
y = 2*y;
x--;
}
cout << y << endl;
return 0;
}
1. Use Consistent Indentation: Use either tabs or spaces for indentation, and ensure that the width is consistent throughout the code.
2. Use Blank Lines: Use blank lines to separate sections of code and improve readability.
3. Avoid Long Lines: Avoid long lines by splitting them into multiple lines if necessary.
Conclusion
Whitespace
and basic formatting are essential for writing readable and maintainable C++
code. By following best practices and using whitespace effectively, you can
ensure that your code is easy to understand and debug.
1.9 Introduction
to literals and operators
Literals
are values that are inserted directly into the source code. They are used to
represent constant values and can include numbers, characters, strings, and
more. C++ supports various types of literals, including:
1. Integer Literals: Whole numbers without fractional or decimal parts.
Example: int x = 42;
2. Floating Point Literals: Numbers with fractional or decimal parts.
float e = 2.7f;
3. Character Literals: Individual characters or escape sequences.
char grade = 'A';
4. String Literals: Sequences of characters.
const char* message = "Hello, World!";
5. Boolean Literals: Truth values.
bool flag = true;
Operators
are symbols used to perform operations on literals and variables. They can be
categorized into four types based on the number of operands they take:
1. Unary Operators: Act on one operand.
int x = -5;
2. Binary Operators: Act on two operands.
int sum = 3 + 4;
3. Ternary Operators: Act on three operands.
int result = (x > 5) ? 10 : 20;
4. Nullary Operators: Act on zero operands.
throw "Error";
#include
<iostream>
int
main() {
int x = 42; // integer literal
float e = 2.7f; // floating point
literal
char grade = 'A'; // character
literal
const char* message = "Hello,
World"; // string literal
bool flag = true; // boolean
literal
std::cout << "Integer Literal:
" << x << std::endl;
std::cout << "Floating Point
Literal: " << e << std::endl;
std::cout << "Character Literal:
" << grade << std::endl;
std::cout << "String Literal:
" << message << std::endl;
std::cout << "Boolean Literal:
" << flag << std::endl;
return 0;
}
Conclusion
Literals
and operators are essential components of C++ programming. Understanding how to
use them effectively can improve code readability and maintainability.
1.10
Introduction to expressions
Expressions
are a fundamental concept in C++ programming. This section provides an overview
of expressions, including their definition, types, and examples.
Definition
An
expression is a sequence of operators and their operands that specifies a
computation. Expression evaluation may produce a result, such as a value, a
side effect, or both.
Types of Expressions
1. Constant Expressions: Consist of numeric or fixed values only.
2. Integral Expressions: Return integral values after computation.
3. Float Expressions: Return float values after computation.
4. Pointer Expressions: Return the address of any defined variable or code.
5. Relational Expressions: Define the relation between two numerics or arithmetic values.
6. Logical Expressions: Return logical relations of two relational expressions or arithmetic values.
7. Bitwise Expressions: Apply operations on the bit level.
8. Special Assignment Expressions: Assign values in a chain.
Example Code
#include
<iostream>
int
main() {
int x = 5; // constant expression
int y = 2 + 3; // integral
expression
float z = 3.54; // float
expression
int arr[5];
int* ptr = &arr[0]; //
pointer expression
int a = 5;
int b = 3;
bool result = (a > b); //
relational expression
int x = 5;
int y = 3;
bool result2 = (x > y) &&
(x < 10); // logical expression
int x = 5;
int y = 3;
int result3 = x & y; //
bitwise expression
int x = 5;
x = x + 3; // special assignment
expression
return 0;
}
Conclusion
Expressions
are a crucial part of C++ programming. Understanding the different types of
expressions and how they are used can help you write more efficient and
effective code.
Comments
Post a Comment