C++ Assignment 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

1) To create an executable C++ program, the following steps are typically followed:

1. Write the code: The first step is to write the C++ code using a text editor or an integrated development
environment (IDE). This involves defining variables, functions, and classes that make up the program's logic.
2. Save the code: Once the code is written, it needs to be saved with the ".cpp" extension, indicating that it is a
C++ source file.
3. Compile the code: The next step is to compile the code using a C++ compiler, which converts the source code
into machine-readable code that can be executed by a computer. This step involves checking the syntax of the
code, identifying any errors, and generating object files.
4. Link the code: The next step is to link the object files generated by the compiler into a single executable file.
This step involves resolving dependencies between different parts of the code and creating a standalone
executable file that can be run on a computer.
5. Test the program: Once the executable file is created, it needs to be tested to ensure that it runs correctly and
Produces the desired output. This involves running the program and checking its behavior for correctness and
Consistency.
6. Deploy the program: If the program passes the testing phase, it can be deployed to users. This involves
distributing the executable file to users or making it available for download from a website or other source.

Overall, the process of creating an executable C++ program involves writing the code, compiling it into machine-
readable code, linking it into a single executable file, testing it for correctness, and deploying it to users.

2) A preprocessor directive is a command in computer programming languages that is processed by the preprocessor
before the compilation of the program. It is used to modify the source code before it is compiled and to provide
information to the compiler. Preprocessor directives are typically used to include header files, define constants and
macros, and conditionally compile certain portions of code. For example, the #include directive is used to include
header files that contain declarations of functions and variables that are used in the program. The #define directive
is used to define constants and macros, which are often used to simplify the code and make it more readable.

Another common use of preprocessor directives is to conditionally compile certain portions of code based on the
value of a predefined constant. This allows developers to create code that can be compiled differently for different
platforms or operating systems.

Overall, preprocessor directives are a powerful tool that helps developers to create more efficient, portable, and
maintainable code.

3) There are three types of program errors: syntax errors, runtime errors, and logical errors.
 Syntax Errors: These are errors that occur when the programmer violates the syntax rules of the
programming language. They are detected by the compiler or interpreter during the compilation or
interpretation process. Syntax errors prevent the program from running at all.

 Runtime Errors: These are errors that occur during the execution of a program. They are typically caused
by invalid inputs, hardware or software malfunctions, or incorrect assumptions made by the program.
Runtime errors can cause the program to crash or produce incorrect results.
1|Page
 Logical Errors: These are errors that occur when the program runs without crashing but produces incorrect
output due to flaws in the program's logic. Logical errors are the most difficult to detect and fix because the
program runs without error messages. It requires careful inspection of the code to identify the mistake and
fix it.
4) A compiler is a software program that translates source code written in a programming language into machine
code that can be executed by a computer. One of the primary roles of a compiler is to catch errors in the source
code and report them to the developer.

There are several types of errors that a compiler can catch, including:

 Syntax errors: These occur when the programmer has made a mistake in the syntax of the programming
language. For example, forgetting to close a parenthesis or using an incorrect keyword can result in a syntax
error.
 Type errors: These occur when the programmer tries to use a variable or function in a way that is not consistent
with its declared type. For example, attempting to perform arithmetic operations on a string instead of a number
would result in a type error.
 Semantic errors: These occur when the programmer has used valid syntax and type, but the resulting code does
not behave as intended. For example, a loop that does not terminate correctly or a conditional statement that
always evaluates to true would result in a semantic error.
 Linker errors: These occur when the compiler cannot find a required library or object file that is needed to link
the compiled code into an executable program.
 Runtime errors: These occur when the program is executed and encounters an error that was not caught by the
compiler. For example, attempting to divide by zero or accessing an invalid memory address would result in a
runtime error.

By catching these types of errors, the compiler helps to ensure that the resulting program is free of bugs and operates
as expected.

5) If you forget to include a punctuation symbol such as a semi-colon, it can result in a syntax error. Syntax error-
occurs when the code does not conform to the rules of the programming language. In this case, the lack of a semi-
colon can cause the program to fail to compile or to execute correctly, depending on the programming language
and the specific context in which the semi-colon is missing. The error message generated by the compiler or
interpreter will typically indicate the location of the error and provide some information about the nature of the
problem, such as a missing or misplaced punctuation symbol.
6) When a program runs but produces incorrect results, this is typically referred to as a "logical error" or a "bug." A
logical error occurs when the program's code is syntactically correct and runs without producing any errors or
crashes, but the program does not produce the expected output or behavior. This can be caused by issues such as
incorrect algorithms, incorrect logic flow, incorrect assumptions about input data, or incorrect variable values.
Debugging is the process of identifying and correcting these logical errors in the code.
7) In C++, the main function is the entry point of a program. When you run a C++ program, the operating system
calls the main function to start the execution of the program.

2|Page
The main function is required in every C++ program because it provides the necessary structure for the program to
execute. Without a main function, the program would not know where to start and how to proceed. The main function
also allows the program to receive any command line arguments that may be passed to it.

Additionally, the main function is responsible for returning an exit code to the operating system, which indicates the
success or failure of the program. This exit code is typically used by other programs or scripts that call the C++
program, allowing them to take appropriate action based on the outcome of the program.

8) An algorithm is a step-by-step procedure or a set of instructions that are followed in order to solve a specific
problem. It is a high-level description of how a task is performed, without specifying any particular programming
language or implementation details. Algorithms can be expressed in natural language, flowcharts, pseudo code, or
other forms.

A program, on the other hand, is a set of instructions written in a specific programming language that is executed by
a computer to perform a particular task. A program typically includes not only the algorithm but also the
implementation details such as the data structures, control structures, and other programming constructs required to
carry out the task. Programs can be compiled or interpreted, and can run on different computer platforms.

In summary, an algorithm is a high-level description of a procedure, while a program is a specific implementation of


that procedure in a particular programming language. An algorithm can be implemented in multiple programs, and a
program can be based on multiple algorithms.

9) In C++, a statement is a single line of code that performs a specific action or operation. C++ supports a variety of
statements, including assignment statements, conditional statements, loop statements, and function calls.

Every C++ statement is terminated by a semicolon (;). This semicolon serves as a delimiter, indicating the end of the
statement. For example, the following line of code assigns the value 10 to the variable x:

This line is a single C++ statement, and it ends with a semicolon. Without the semicolon, the compiler would generate
an error, since it would interpret the next line of code as a continuation of the previous line.

In general, it is important to include the semicolon at the end of every statement in your C++ code, as this is required
by the language syntax.

3|Page
10) What is the output of the following program?

#include <iostream.h>

Int main()

cout<<”Hello guys!”:

cout<<”Welcome to :\n”;

cout<<”introduction to programming!”;

return 0;

The output is:

Figure 1.1 : Quincy Code.

4|Page
10) DEFINE THE FOLLOWING TERMS

 Source code :

Refers to the set of instructions or statements written in a programming language that a computer can
interpret and execute. It is the human-readable version of a software program that developers write and use
to create computer software. The source code serves as the foundation for creating software, allowing
developers to modify and improve its functionality. The source code is usually saved in text files, and it can
be compiled into an executable program that a computer can run.

 Object code :

Refers to the compiled output of a source code file that has been translated into machine code, which can
be executed directly by a computer's processor. Object code is essentially a sequence of instructions in
binary format that represents the program logic and data structures of a software application.

Object code is often generated by a compiler, which takes the source code written in a high-level
programming language and translates it into machine code that can be understood by the computer's CPU.
Object code is an essential component of the software development process, as it is the final output of the
compilation phase before the program is linked and executed.

 Executable Code :

Refers to computer code that can be directly executed by a computer or a compatible device without the need
for further processing or compilation. It consists of machine-readable instructions written in a programming
language such as C, Python, or Java, which can be compiled or interpreted to generate a binary executable file.
This file can be run on an appropriate operating system or hardware platform, allowing the computer to perform
the intended task or program.

 Syntax Error :
A type of programming error that occurs when code violates the rules of a programming language.

These errors are caused by mistakes in the syntax or structure of the code and are usually detected by the
compiler or interpreter during the compilation or execution of the program. Examples of syntax errors
include misspelled keywords, incorrect punctuation, and missing or mismatched brackets. When a syntax
error occurs, the program will usually fail to compile or execute, and an error message will be displayed
indicating the location and nature of the error.

5|Page
11) Write A C++ Code for the following questions

 Find the average of two numbers given by user.

#include <iostream>

using namespace std;

int main() {

// Declare variables for the two numbers and the average

float X, Y, average;

// Ask the user to enter two numbers

cout << "Enter the first number: ";

cin >> x;

cout << "Enter the second number: ";

cin >> y;

// Calculate the average of the two numbers

average = (x+ y) / 2;

// Display the result to the user

cout << "The average of " << x<< " and " << y << " is " << average << endl;

return 0;

6|Page
 Find the average, maximum, minimum, and sum of three numbers given by the user.

#include <iostream>

using namespace std;

int main() {

// Declare variables to store the three numbers

float x, y, z;

// Ask the user to enter three numbers

cout << "Enter the first number: ";

cin >> x;

cout << "Enter the second number: ";

cin >> y;

cout << "Enter the third number: ";

cin >> z;

// calculate the average, maximum, minimum, and sum

float average = (x + y + z) / 3;

float maximum = max(x, max(y, z));

float minimum = min(x, min(y, z));

float total = x + y + z;

// Print out the results

cout << "The average of the three numbers is: " << average << endl;

cout << "The maximum of the three numbers is: " << maximum << endl;

cout << "The minimum of the three numbers is: " << minimum << endl;

cout << "The sum of the three numbers is: " << total << endl;

return 0;

7|Page
 Find the area of the circle where the radius is provided by the user

#include <iostream>

using namespace std;

int main()

double radius, area;

const double pi = 3.14159; // defining constant value for pi

cout << "Enter the radius of the circle: ";

cin >> radius;

area = pi * radius * radius;

cout << "The area of the circle is: " << area << endl;

return 0;

Another way of doing this problem :

#include <iostream>

using namespace std;

#define PI 3.14159

int main()

double radius, area ;

cout<<"Please enter the radius of the circle"<<endl;

cin>>radius;

area = PI * radius * radius;

cout<<"The area of a circle of that number is\n"<<area;

return 0;

}
8|Page
 Swap the contents of two variables using third variable.

First of all let’s see a major keyword which is “temp”.

In C++, when we want to swap the contents of two variables, we usually use a temporary (temp) variable to hold one
of the values while we replace it with the other value.

The reason we use a temporary variable is to prevent losing the original values of the variables we are swapping. If
we didn't use a temporary variable and simply assigned the value of one variable to the other, we would overwrite the
original value and lose it.

By using a temporary variable, we can store the value of one variable before replacing it with the value of the other
variable. Then, we can use the value stored in the temporary variable to assign it to the other variable. This way, we
can successfully swap the contents of the two variables without losing any data.

For example, let's say we have two variables `a` and `b`, and we want to swap their values. If we do:

This way, the original value of `a` is saved in `temp`, and `b` is assigned the value of `a`. Then, we can assign the
original value of `a` stored in `temp` to `b`, which completes the swap.

So, using a temporary variable is a simple and effective way to swap the contents of two variables without losing
any data.

9|Page
#include <iostream>

int main() {

int a = 10, b = 20, temp;

std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;

// swapping the values

temp = a;

a = b;

b = temp;

std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;

return 0;

 Swap the content of two variables without using third variable.

#include <iostream>

using namespace std;

int main() {

int a = 10;// Initialization

int b = 20;// Initialization

cout << "Before swapping: " << endl;

cout << "a = " << a << ", b = " << b << endl;

// Swapping the values of a and b without using a third variable

a = a + b;

b = a - b;

a = a - b;

cout << "After swapping: " << endl;

cout << "a = " << a << ", b = " << b << endl;

return 0;

10 | P a g e
REFERENCE

1. https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp0_Introduction.html ;
2. https://en.m.wikibooks.org/wiki/C_Programming/Preprocessor_directives_and_macros
3. https://www.inf.unibz.it/~calvanese/teaching/ip/lecture-notes/uni10/node2.html
4. https://www.techtarget.com/whatis/definition/algorithm
5. https://www.sololearn.com/Discuss/1080011/what-is-temp-in-c-and-when-we-can-use-it

11 | P a g e

You might also like