Chapter 2: Programming Basics Flashcards

1
Q

Week 1

Why do we program? What is a program in the first place?

A

A program exists to solve a pre-existing problem.

Since the advent of the computer, many of society’s problems have been solved, such as:

  • Inefficient paper filing systems
  • Difficult access to entertainment.
  • Slow communication.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Week 1

List the problems one must consider when programming.

A

Listed below are the questions one must ask oneself before programming.

  • What problem to solve?
  • Who to design for?
  • Who can collaborate with it/communicate using it?
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Week 1

Why is programming important?

A
  • It is fun
  • It is more than vocational
  • By designing programs, we learn skills that can be applied in numerous fields.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Week 1

What is computational thinking?

A

Computational thinking refers to the thought processes involved in formulating problems so their solutions can be represented as computational steps and algorithms.

Listed below are the steps to engage in computational thinking.

  • Collect data.
  • Analyze data.
  • Find patterns.
  • Decompose problems.
  • Abstract.
  • Build models.
  • Desktop algorithms.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Week 2

Explain the function of the following C++ command

#include <iostream>
#include ”accounts.h”
A

The #include directive in C++ is used to include external files and/or libraries in your program.

In this case, the line of code instructs the program to include a standard library header named iostream and a custom header file named accounts

All header files use a .h extension

The use of angle brackets (<>) signifies that you are including a system or standard library header. Custom header files are encased in quotations (“”)

In short, this line of code instructs the program to include external files that contain other functions and/or variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Week 2

What is the difference between using angle brackets (<>) and quotations (“”) in the #include directive?

A

Let’s look at two examples here

#include <vector>

#include "custom.h"

The first command instructs C++ to include a standard library header (SLH) vector that comes with the language itself i.e. it does not need to be created by the programmer.

The second command instructs C++ to include a custom header file custom.h that the programmer has already created and stored somewhere.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Week 2

What is an algorithm?

A

An algorithm is a set of instructions designed to solve a specific problem or perform a particular task.

It’s like a recipe that guides a computer or person through a series of logical actions to achieve a desired outcome.

Algorithms are a fundamental concept in computer science and are used to solve problems, make decisions, and process data efficiently.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Week 2

Explain the function of the following code snippet

#include <iostream>

int main() {
    int A = 5;
    int B = 6;
    int sum = A + B;

    std::cout << "The sum is: " << sum << std::endl;

    return 0;
}
A
  • #include <iostream>: the function of this command is to include a SLH that facilitates all input/output stream operations.
  • int main() {} is a command where the program essentially starts executing instructions.
  • int A and int B are assigned their respective values.
  • Another integer variable sum is declared. sum contains the sum of int A and int B.
std::cout << "The sum is: " << sum << std::endl;`
  • The code snippet above basically instructs the language to output the value stored in the sum variable along with contextual text.
  • We’ve essentially created a simple calculator that can add two numbers and output the sum.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Week 2

List common pseudocode conventions.

A
  • Indentation: Use indentation to represent control structures like loops and conditionals. This helps visualize the flow of the algorithm.
  • Variables: Declare variables and assign values using a colon or arrow (: or ->).
  • Operations: Use standard mathematical notations (+, -, *, /, etc.) for operations.
  • If-Else: Use if, else if, and else for conditional statements.
  • Looping: Use for, while, or repeat for loops.
  • Declare functions and procedures with a keyword.
  • Specify parameters and return types if needed.
  • Use input or similar keywords for taking input.
  • Use output or similar keywords for displaying output.
  • Comments: Use plain language comments to explain complex parts of the algorithm.
  • Naming Conventions: Use meaningful names for variables, functions, and procedures to improve clarity.
  • Flow Control Keywords: Use words like break, continue, and return to indicate flow control actions.
  • Boolean Logic: Use AND, OR, NOT or their symbols (&&, ||, !) for logical operations.
  • Initialization: Explicitly show variable initialization.
  • Termination: Indicate the end of the algorithm with a clear keyword or marker.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Week 2

What is the function of the return 0; command in C++

A

In C++, return 0; is a statement commonly used in tandem with the int main() function.

Its solitary purpose is to signal to the operating system that the program has successfully completed execution.

This convention comes from the historical practice where a return value of 0 indicates success and non-zero values indicate various error conditions or issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Week 2

Name the operators in C++

A

The operators used to perform arithmetic operations in C++ fall into the following categories: High precedence, and low precedence

Types of Low Precedence Operators

  • Addition (+)
  • Subtraction (-)

Types of High Precedence Operators

  • Multiplication (*)
  • Division (/)
  • Modulus (%)
  • (Parentheses) take the highest precedence regardless

C++ will always prioritize high-precedence operations while executing an arithmetic sequence.

If C++ executes two operations with the same precedence, it will execute them from left to right, in sequence.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Week 2

What is the function of the mod operator?

A

The mod (%) operator in C++ returns the remainder of division, useful for checking even/odd, cycling values, and time wrapping.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain the function of the following program

#include<iostream>

int main () {
    int n = 19;
    int u = n % 10;
    int d = n / 10;
    int rev = u * 10 + d;
    
    std::cout<<"reverse of "<<n<< " = "<<rev<<std::endl;
    
    return 0;
    
}
A

#include<iostream>

This command asks the program to include the SLH named iostream, which enables input/output operations with the console.

int main () {

This serves as the entry point for the program execution. At this point, the program starts executing instructions.

    int n = 19;
    int u = n % 10;
    int d = n / 10;
    int rev = u * 10 + d;
		

These series of commands declare integer variables and store all the calculations required to store the inverse of int n

std::cout<<"reverse of "<<n<< " = "<<rev<<std::endl;

This command line asks the program to output the value of int rev along with a string of text.

return 0;

This command line returns error code 0 to the operating system, which indicates to it that the program has successfully executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Week 2 (L) / Week 3

How many bits do different data types take up in C++?

A

First off, let’s define all the ARM data types for 32-bit and 64-bit systems.

  • A byte consists of 8 bits.
  • A word consists of 32 bits.
  • A half word consists of 16 bits.
  • A double word consists of 64 bits.
  • A quad word consists of 128 bits.

Now, let’s define the capacity of several data types in C++ in terms of the aforementioned ARM conventions.

Primitive Data Types

  • int : word (32 bits)
  • short : half-word (16 bits)
  • long : double word (64 bits)
  • char : byte (8 bits)
  • float : word (32 bits)
  • double : double word (64 bits)
  • boolean : byte (8 bits)
  • void : double word (64 bits)

The “string” data type

Unlike its counterparts, string is a dynamic data type that occupies storage based on how many characters are stored in it.

Each character occupies a byte, so, for example, 10 characters would occupy 10 bytes or 80 bits. So, if 10 characters are stored in a string variable, that variable will occupy 10 bytes of storage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Week 3

List different types of software.

A

For a detailed explanation with exact definitions and infographics, visit this link.

Computer software can be divided into two subcategories: application software and system software

System Software

System software is designed to communicate with the hardware of your system, hence, you don’t interact with it that often; it acts as a messenger between your application software and your system software.

The types of system software are as follows:

  • Operating systems
  • Device drivers
  • Utility programs

Types of Application Software

Application software is designed to be operated by a human user in order to allow them to communicate with a computer, instruct it to perform specific actions, and read the output of said actions, if any.

Application software can be divided into two categories:

  • Specific application software
  • General purpose application software
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Week 3

What is an operating system (OS)?

A

An operating system is a type of system software that allows the user to communicate with the hardware of the computer.

The OS instructs the hardware to open different software, perform different actions ( such as copy/paste), and enumerate different mathematical calculations based on the user’s input.

The OS essentially serves as a translator with the human (the user) and the machine (the hardware).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Week 3

Where is the OS stored?

A

In the HDD/SSD of your computer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Week 3

What are the different types of operating systems?

A

Command Line Operating Systems

In a command-line interface, the use types keywords or press special keys as a keyboard command to enter data and instructions. The instruction set used to communicate with the computer is called the command language

Command-line interfaces, albeit efficient, are very difficult to interpret and learn for a layman; the necessity of an easy-to-use operating system prompted the invention of Graphical User Interfaces (GUI)

The Graphical User Interface

As a graphical user interface does not need you to memorize the command language, it is easier to understand and use the command-line interface.

The Graphic User Interface (GUI) allows you to allocate a command to a graphical object.

Some examples of very popular GUIs are as follows:

  • Windows
  • Linux
  • macOS
  • Ubuntu
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Week 3

Define booting.

A

The process of loading the operating system (OS) into the computer’s memory upon startup so that it can be used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Week 3

What are the different categories of operating systems?

A
  • stand-alone operating systems: run natively on laptops and desktop computers
  • **server operating systems: **designed to operate servers, these operating systems are what most computers rely on
  • embedded operating systems:These operating systems find use in most mobile phones, as they are stored on a ROM chip that is very light-weight and portable, which is also a hallmark of every mobile phone.
21
Q

Week 3

What is a device driver?

A

The device driver, also known as the driver, is a small program that tells the operating system how to communicate with the device. It acts as a “link” between the hardware on the computer system and the OS.

The operating system relies on device drivers to communicate with each device on the computer. Each device on a computer, such as a mouse, keyboard, etc., has its own specific set of commands and thus needs its own particular drivers. When you boot a computer, the operating
system loads the driver of each device. Without their correct drivers, these devices will not work.

22
Q

Week 3

What is utility software?

A

The utility program is the type of system software that performs a specific task, usually related to the management of a computer, its devices, or its program. It’s also called a utility. It helps with the management of computer hardware and application software. The typical example for utility software:

  • File management softwares.
  • Anti-virus softwares.
  • Disk cleanup softwares.

Most utility programs run in the background.

23
Q

Week 3

What is a general-purpose application software?

A

This type of application software is developed to cater to the needs of many people. As a result, these softwares tend to be the some of the most well-known to the average user.

You may buy these programs from the vendors in retail stores or on the Internet.

Examples of general-purpose applications include word processing, spreadsheet, presentation, and database management.

24
Q

Week 3

What is a specific-purpose application software?

A

Special purpose application software is a type of software designed to perform a particular task. A web browser, for example, whose basic aim is to show you the websites, and to make it easier for you to surf the internet.

Sometimes, the need of the business is so specific that there isn’t any ready-made solution available in the market or on the internet. So to get a specialized solution, a business has to get fresh specific software developed for their needs. The main advantages of this software are that they work exactly as we want as if these are designed according to our needs. Examples of specific purpose software are:

  • Accounting Management
  • Reservations Systems
  • HR Management
  • Attendence System
  • Payroll System
  • Inventory Control System
25
Q

Week 3

What are some of the tools required to code?

A

Text Editor

You write your code in the text editor. The text editor does nothing with the program; it just displays the code to the programmer.

Pre-processors

A preprocessor is a software tool or component used in the early stages of compilation in many programming languages.

Its primary role is to perform text manipulations on the source code before it’s sent to the actual compiler. Key tasks of a preprocessor include:

  • File Inclusion using the #include directive.
  • Conditional Compilation.
  • It removes all the comments before compilation.
  • It tells the compiler which line a specific snippet of code is on.

A pre-processor directive is a command interpreted only by the pre-processor. An example of a pre-processor directive is # include.

Compilers & Interpreters

A compiler reads the program line-by-line, lists down problems with the code, and doesn’t execute until they are fixed.

An interpreter reads each line and executes it immediately while checking for errors.

Common compiled languages are C++ and Java
Common interpreted languages are Python and JavaScript.

Debuggers

A debugger is a software tool that helps programmers find and fix errors (bugs) in their code during development.

It allows programmers to halt the execution using breakpoints and inspect their code for errors.

Linker

A linker is a program used in software development to combine multiple object files and libraries into a single executable or loadable program.

Linkers are a crucial part of the compilation process, as they generate the final binary code that can be run on a computer.

Loader

A loader is a system component responsible for loading executable files into a computer’s memory for execution.

A loader fetches the program located in the system storage and transfers it to the working memory of a computer.

26
Q

Week 3

What is the function of the system("pause")command?

A

In C++, the system("pause") command is often used to pause the execution of a program when running it in a console or terminal window. It is a platform-dependent way to keep the console window open after a program has finished executing, allowing the user to view any output or error messages before the window automatically closes.

27
Q

Week 3

What is a conditional statement?

A

A conditional statement is a command that is only executed when a certain conditions are met.

Conditional statements serve many different purposes, which is why there exist many types, such as:

  • If/else statements
  • For Loops
  • While Loops
  • Case Statements
28
Q

Week 3

Explain the if/else statement in C++.

A

Let’s apply if/else statements in a practical use case. Read the following code and interpret it.

#include <iostream>
using namespace std;

int main () {

int a = 5
if (a == 5) {

cout<<" a is equal to 5"<<endl;

}

else {  

cout<<"a is not equal to 5"<<endl;

}

return 0;

}

In the code snippet above, the program defines a variable and assigns it a value. In the succeeding lines, the program evaluates the value of a, and checks if its equal to 5.

If a is equal to 5, the program acknowledges it and outputs the confirmation.

The else statement is excecuted only when the if statement is not met. In this example, if the value of a were not 5, the program would execute the else statement.

else if statements may be used for more than two possible scenarios.

29
Q

Week 3

Explain logical operators in C++

A

Logical Operators are used for Boolean logic and are commonly used to combine and evaluate conditions in control structures like if statements and loops.

Examples include:

  • Logical NOT operator (!)
  • Logical AND operator (&&)
  • Logical OR operator (||)
  • Equal to (==)
  • Not equal to (!=)
  • Greater than (>)
  • Greather than or equal to (>=)
  • Less than (<)
  • Less than or equal to (<=)

Let’s apply logical operators in practice.

#include <iostream>
using namespace std;

int main () {

int a = 5
int b = 6
if (a == 5 && b==6 ) {

cout<<" true"<<endl;

}

else {  

cout<<"false"<<endl;

}

return 0;

}

The code above resembles a simple logic gate. If the values of a and b are equal to 6 simultaneously, the program will output true (1).

If a or b are any other value, the program will return false (0).

30
Q

Week 3

What are switch statements?

A

Switch statements are ideally used when there are many possible outputs based on many different scenarios.

Let’s look at this example

#include <iostream>
using namespace std;

int main () {

int a = 0;

cout<<"Enter a number between 1 and 7"<<endl;
cin>>a;

switch (a)

case 1:

cout<<"Monday"<<endl;

break;

case 2:

cout<<"Tuesday"<<endl;

break;

case 3:

cout<<"Wednesday"<<endl;

break;

case 4:

cout<<"Thursday"<<endl;

break;

case 5:

cout<<"Friday"<<endl;

break;

case 6:

cout<<"Saturday"<<endl;

break;

case 7:

cout<<"Sunday"<<endl;

break;

default:

cout<<"Error"<<endl;

}

return 0;

}

From this code snippet, we can deduce that switch statements are essentially serve the same purpose as multiple if statements without the clumsy syntax.

The default keyword is used to instruct the program to default to a predifined routine if a fails to match a case statement.

31
Q

Week 3 (L)

explain the rand() function in C++

A

The rand() function returns a random value between 0 and 32767.

The rand() function’s value can be output as follows

#include<iostream>
#include<cstdlib>
#include"string"
using namespace std;

int main () {

cout<<rand()<<endl;

return 0;

}

Obtaining a Random Integer up to a Certain Value

#include<iostream>
#include<cstdlib>
#include"string"
using namespace std;

int main(){

int N = 100;

for (int j = 0; j < 5; j++){

    cout<< rand () % N << " "<<endl;
}

return 0;

}

In this code snippet, we declared an integer variable N and assigned it a random value.

We run a for loop to output five random integers.

In order to obtain a rand() value between 1 and 99, we must perform the mod operation on rand() with N.

The resultant value cannot be greater than 99, so we always obtain a rand() value between 0 and 99.

Obtaining a Random Integer Within a Certain Range

int main () {

int lb = 20;
int ub = 80;

for (int i = 0; i < 5; i++) {

cout<< rand() % (ub - lb + 1) + lb << " ";

}

return 0;

}

This code snippet follows the same principle as the one before it, but with a few minor tweaks.

This time, we declare two variables ub (upper bound) and lb (lower bound).

We then start a for loop to output five random numbers between lb and ub

The random value is calculated using a series of mathematical operations, which are as follows:

  • The boundary is calculated by subtracting the lower bound from the upper bound and adding 1. If we stopped here, we would have only output random values from 0 to ub (including ub).
  • Since we need values between the upper bound and the lower bound, we must add the value of the lower bound to the resultant to ensure that even if the rand() function returns 0, the output will be the lower bound.

You must use the #include<cstdlib> directive every time you want to use the rand() function.

32
Q

Week 3 (L)

Explain the stoi() function in C++

A

The stoi() (string to integer) function converts any string value into an integer.

There are a few exceptions one must note before using the stoi() function

  • The function cannot convert lexical string characters into an integer.
  • The function will only omit lexical characters if they succeed the integer values stored in the string field

For example:

string a = "xyz123"; will not be converted into an integer. The compiler will return with an error.

string b = "123xyz"; will be converted into an integer. The compiler will omit the “xyz” in front of the integers and return 123 as the output.

string c = "123xyz5"; will be converted into an integer. The compiler will omit the “xyz5” in front of the integers and return 123 as the output. The integer value that succeeds the lexical characters will also be omitted.

the stoi() function is applied in the code below:

#include <iostream>
#include <string>  
using namespace std;

int main () {

    string a = "123xyz5";
    int b = stoi (a);
    cout<< b <<endl;

return 0;

}

the atoi() function in C++ serves the same function, but stoi () is still superior due to better functionality and error detection.

33
Q

Week 3 (L)

Explain the sizeof() function in C++

A

In C++, the sizeof operator calculates and returns the size, in bytes, of data types, variables, or expressions. It’s used to understand memory usage and ensure portability across platforms.

Size of Data Types

You can use sizeof to find the size of fundamental data types, such as int, char, float, double, and more. For example:

cout << "Size of int: " << sizeof(int) << " bytes" <<endl;

Size of Variables

You can use sizeof to determine the size of a specific variable or object in memory. For example:

int x;
cout << "Size of x: " << sizeof(x) << " bytes" << endl;

It’s important to note a few key points about the sizeof operator:

  • The result of sizeof is determined at compile-time, not at runtime. It calculates the size based on the data type or object’s definition.
  • The size reported by sizeof is in bytes. It’s a fundamental unit of memory storage.
  • The exact size can vary depending on the compiler, platform, and data type alignment requirements. Therefore, it’s not guaranteed to be the same across different systems.
  • sizeof is often used when working with memory allocation, data structures, and ensuring portability of code across different platforms.
34
Q

Week 3 (SS)

What is the function of the » and « operators in C++

A

The bitwise shift operators are used to perform binary shifts on a number.

There are two types of bitwise shift operators.

Right Shift Operators

» (Right Shift Operator) is used for bitwise right shifting. It shifts the bits of a number to the right by a specified number of positions. The vacant positions are filled depending on the sign bit (for signed integers) or with zeros (for unsigned integers).

Left Shift Operators

« (Left Shift Operator): This operator is used for bitwise left shifting. It shifts the bits of a number to the left by a specified number of positions, filling the vacant positions with zeros.

« and » operations are also used in stream insertion and extraction operators, such as:

cout<<"Hello World!";
35
Q

Week 3 (SS)

What is the function of the “chrono” library in C++?

A

The “chrono” library in C++ provides functionality for precise time measurement, duration, and time point handling, aiding in tasks like timing events, measuring intervals, and time-based calculations.

36
Q

Week 4 (SS)

What are arithmetic and logical assignment operators?

A

Arithmetic and Logical Assignment (ALA) operators, like regular assignment operators (=), assign values to variables but with an additional operation on the variable before storing it. For example:

int x = 0;

int x += 3       //Equivalent to x = x + 3;

cout<<x;

visit this link for a detalied list of all ALAs with examples.

37
Q

Week 4 (SS)

What operator is commonly used for concatenating strings in C++?

A

String concatenation in C++ involves combining two or more strings to create a single, longer string. It’s akin to joining pieces together, but with a specific method.

String concatenation uses the + operator to connect strings, like so:

std::string firstString = "Hello, ";
std::string secondString = "world!";
std::string concatenatedString = firstString + secondString; // Concatenation
std::cout << concatenatedString;
38
Q

Week 4 (SS)

How do you find the length of a string in C++

A

Finding the length of a string in C++ involves using the length() or size() member functions, similar to regular variable assignment. These functions return the number of characters in the string.

For instance:

#include <iostream>
#include <string>

int main() {
    std::string text = "Hello, World!";
    int length = text.length();  // or text.size();

    std::cout << "Length of the string: " << length << std::endl;
    return 0;
}
39
Q

Week 4

Explain the function of for loops in C++.

A

for loops in C++ enable repetitive code execution as long as a condition is met. They typically involve an iteration variable and facilitate tasks like iterating through arrays or performing actions a fixed number of times.

Let’s consider an example:

#include <iostream>
using namespace std;

int main() {
    string text = "Hello, World!";
    int length = 0;

    for (int i = 0; i < text.length(); i++) {
        length++;
    }

    cout << "Length of the string: " << length << endl;
    return 0;
}

The code utilizes a C++ for loop to find the length of a string. It initializes a length variable, iterates through the characters of the string, incrementing length, and then displays the result.

40
Q

Week 4

What are nested loops

A

Nested for loops are a programming concept where one loop is placed inside another. This structure allows for the execution of the inner loop multiple times for each iteration of the outer loop. It’s commonly used for iterating through multidimensional data structures or performing repetitive tasks with varying degrees of complexity.

For example:

int main () {

for (int i = 0; i  <  4; i++) {

   for (int j = 0; j < 5; j++) {
	 
	 cout<<j<<endl;
	 
	 }
	 
}

return 0;

The output of this code would be

01234012340123401234

i will only iterate once the for loop inside has completed one cycle i.e. j has iterated by one increment all the way from 0 to 4.

41
Q

Week 4 (SS)

How does C++ handle operations when operators have different data types?

A

Let’s look at an example:

int main (){

int a = 5;
float b = 6.5;
float c = 0.0;
int intc = 0;

c = a + b // output is 11.5. The program converts a into float automatically. a becomes 5.0

intc = a + b // output is 11. The program converts a into float, but still rounds down in the end because it is an int variable.

cout<<c<<"\n"<<intc<<;

return 0;

}
42
Q

Week 4 (L)

What is the function of the abs() function?

A

The abs() function returns the absolute value of any int variable.

the abs() function can work with floating point decimals, but it will truncate the decimals and return an integer value.

Let’s look at an example

int a = -5

int b = abs(a);

cout<<a<<"\n"<<b;
Output: 

-5
5

If we want to find the absolute value of decimal numbers, we must use the fabs() function included in the <cmath> SLH

43
Q

Week 5

Explain while () {} and do{} while() loops in C++

A

Definition

In C++, “while” and “do-while” loops are used for repetitive tasks. The key difference is in when the condition is checked. In a “while” loop, the condition is checked before the loop’s execution, so it’s possible the loop won’t run at all. In a “do-while” loop, the condition is checked after the loop’s execution, ensuring the loop runs at least once.

Syntax

Example of a “while” loop:

int i = 1;
while (i <= 5) {
    cout << i << " ";
    i++;
}

Example of a “do-while” loop:

int i = 1;
do {
    cout << i << " ";
    i++;
} while (i <= 5);
44
Q

Suppose you declared an integer variable i and store its incremented value in another integer variable y, how would your outputs differ if you use ++i as opposed to i++?

A

Let’s examine this code:

int i = 5;
int y = i++;

cout<<i<<", "<<y;
Output: 6, 5

i only increments after it assigns its value to y

Let’s examine another code snippet:

int i = 5;
int y = ++i;

cout<<i<<", "<<y;
Output: 6, 6

i increments first and then assigns its value to y

45
Q

Describe the operator precedence hierarchy in C++

A
  • Highest Precedence:: Brackets/Parentheses | () , []
  • Second Order Precedence: Postfix Increment/Decrement | a++ , a--
  • Third-Order Precedence: Prefix Increment/Decrement | --a , ++ a
  • Fourth Order Precedence: Multiplication, Division, Modulus | *, / , %
    -Fifth-Order Precedence: Addition, Subtraction | + , -
  • Sixth-Order Precedence Relational Operators | < , > , >= , <=
  • Seventh-Order Precedence:Equality Operators | != , ==
  • Eigth-Order Precedence: Logical AND (&&)
  • Ninth-Order Precedence: Logical OR (II)
  • Tenth-Order Precedence: Assignment Operators | = , += , -= , etc.
  • Eleventh-Order Precedence: Comma (,)
46
Q

Explain Boolean Logic in Conditional Statements in C++

A

In conditional statements, if an equality comparison operator is not specified ( ==, != ), the condition inside the parentheses will act as a boolean statement.

Example:

if (70%70) {

cout<<"1"<<endl;

}

else { cout<<"2"<<endl; }
Output:

2

Explanation: Since there isn’t an equality comparison stated anywhere inside the condition declaration of the if statement, the result of 70 % 70, which is 0, will act as a boolean value of false, which means that the if statement will never execute, and will automatically jump to the else condition.

47
Q

Evaluate !(!31)

A

In boolean terms, any non-zero integer returns a value of true, so ! (! 31) can be re-written as ! (! true), which would return true since both Logical NOTs cancel out.

48
Q

What would be the output of the following statement?

cout<<'abc'<<endl;
A

Since the output abc is enclosed in single quotations (‘ ‘), the output will be treated as a char, but since char can only store 8 bytes, it will output a non-specific code instead of the actual string output.

The compiler might also print a warning in some cases, but the code will execute anyways.

Output

6382179

If you would like to print the ASCII value of a character, do the following:

cout<<int( 'a' ) // Output : 97 (ASCII value of lowercase a)
49
Q

What would be the output of the following statement?

int a = 30;

cout<< (a = 10);
A
Output 

10

Explanation: Since the assignment operation is done within the parentheses, a is assigned the value of 10 before it is output, hence resulting in an output of 10.

Note: If the assignment operation was not placed inside parentheses, the compiler would have thrown an error.

Bonus: What would be the output of cout<<(a == 10) instead?

Since we are now comparing a and 10 instead of assigning a to 10, the compiler will return with the output of 0 (false), since the value of a is not equal to 10.