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

Fundamentals of programming Worksheet II

The document outlines the fundamental steps to create an executable C++ program, including writing source code, preprocessing, compilation, linking, loading, and execution. It also explains key concepts such as preprocessor directives, types of errors caught by the compiler, the importance of the main function, and definitions of source code, object code, and executable code. Additionally, it provides examples of C++ programs for various tasks, such as calculating the area of a circle and converting temperatures.

Uploaded by

ebra4842
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Fundamentals of programming Worksheet II

The document outlines the fundamental steps to create an executable C++ program, including writing source code, preprocessing, compilation, linking, loading, and execution. It also explains key concepts such as preprocessor directives, types of errors caught by the compiler, the importance of the main function, and definitions of source code, object code, and executable code. Additionally, it provides examples of C++ programs for various tasks, such as calculating the area of a circle and converting temperatures.

Uploaded by

ebra4842
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Fundamentals of programming Worksheet II

For 1st Year Computing program Students

1. What are the steps that we have to follow in order to have an executable C++ program?
Describe each step.

In C++ programming there are 6 steps that we have follow in order to have executable
C++ programming.
These are in detail
1. Writing the Source Code
 What happens: You write your C++ code in a text editor or an Integrated Development
Environment (IDE) and save it with a .cpp extension (e.g., main.cpp).
 Purpose: This step creates the human-readable instructions that define the program's
behavior.

2. Preprocessing
 What happens: The preprocessor handles directives that begin with # (e.g., #include,
#define, #ifdef).
 Purpose: It prepares the code for compilation by:
o Including header files,
o Expanding macros,
o Removing comments,
o Handling conditional compilation.
 Tool: C++ Preprocessor (usually part of the compiler).

3. Compilation
 What happens: The compiler translates the preprocessed C++ code into assembly code,
then into machine code stored in an object file (e.g., main.o or main.obj).
 Purpose: Converts human-readable code into code that the computer can understand,
but it's not yet executable.
 Tool: Compiler (e.g., g++, clang++).

4. Linking

1|Page
 What happens: The linker combines the object file(s) with libraries and other
dependencies to create a final executable file (e.g., main.exe or a.out).
 Purpose: Resolves references to external functions or variables, especially from standard
or user-defined libraries.
 Tool: Linker (often built into the compiler).

5. Loading (when executing)


 What happens: When you run the executable, the operating system loads it into
memory, sets up the execution environment, and begins execution at the program’s
main() function.
 Purpose: Starts the actual execution of the program.

6. Execution
 What happens: The CPU follows the machine instructions from the loaded program,
carrying out the logic you wrote.
 Purpose: Produces the actual result or output of the program (e.g., displaying text,
performing calculations, etc.).

1. What is a preprocessor directive? For what purpose do we use it?

A preprocessor directive in C++ is a command that is processed by the preprocessor


before the actual compilation of the code begins.
Definition:
A preprocessor directive is an instruction that begins with the # symbol and is executed
before the compiler translates the source code into machine code.
Purpose:
Preprocessor directives are used for:
1. Including header files
Example: #include <iostream>
This tells the preprocessor to include the contents of the standard input-output stream
library before compilation.
2. Macro definitions
Example: #define PI 3.14
This defines a constant or macro that can be used throughout the program.
3. Conditional compilation
4. This allows compiling code conditionally based on whether a macro (like DEBUG) is
defined.
5. File inclusion guards (to avoid multiple inclusions of a file)

2|Page
2. Tell what kind of errors the compiler catches?

The compiler catches syntax and semantic errors during the compilation process. Here are
the main types of errors it detects:

1. Syntax Errors

These occur when the rules (grammar) of the C++ language are violated.

Examples:

 Missing semicolons (;)


 Incorrect use of parentheses or braces
 Misspelled keywords or identifiers

2. Semantic Errors

These occur when the statements are syntactically correct but make no sense logically to
the compiler.

Examples:

 Using an undeclared variable


 Type mismatches (e.g., assigning a float to an int without conversion)
 Calling a function with the wrong number or type of arguments

What the compiler does not catch:

 Logical errors (e.g., wrong formulas)


 Runtime errors (e.g., division by zero)

3. Why every C++ program must have a main function?

The main() function is essential in every C++ program because it is the entry point of the
program — this is where the execution of your program begins.

Reasons:

1. Starting Point for Execution


o The C++ runtime environment looks for the main() function when the program
starts.
o Without it, the program has no defined starting point, so it cannot run.
2. Standard Requirement
o The C++ language standard defines main() as the mandatory function where
execution starts.
3|Page
oIt’s how the operating system knows where your code begins.
3. Returns an Exit Status
o The main() function returns an int (usually 0) to indicate whether the program
ended successfully or with an error.

4. Define the following terms: Source code, Object code, and Executable code

Here are the definitions of the three terms:

1. Source Code

 Definition: The original code written by the programmer using a high-level programming
language like C++.
 File extension: .cpp
 Human-readable: Yes

2. Object Code

 Definition: The machine-level intermediate code generated by the compiler after


translating the source code. It’s not yet a complete program.
 File extension: .obj (Windows) or .o (Linux/Unix)
 Human-readable: ❌ No
 Purpose: Needs to be linked with other object files or libraries to create an executable
file.

3. Executable Code

 Definition: The final machine code that can be directly executed by the computer.
 File extension: .exe (Windows), no extension or .out on Unix/Linux
 Human-readable: ❌ No
 Generated by: The linker, which combines all object files and libraries into one file.

5. What is the difference between an algorithm and a program?

Difference Between an Algorithm and a Program


An algorithm and a program are closely related but fundamentally different concepts in
computer science. Here's a detailed explanation:

What is an Algorithm?
An algorithm is a step-by-step method or set of instructions designed to solve a specific
problem or perform a task. It is written in a logical, often language-independent way. You
can think of it like a recipe in cooking — it outlines what steps to follow, but doesn’t specify
the exact tools or kitchen.

4|Page
Characteristics of an Algorithm:
 Language-Independent: You can write an algorithm in plain English, pseudocode, or a
flowchart.
 Not executable by a computer directly: Since it’s not written in programming syntax, it
must be converted into code first.
 Focuses on logic and steps: The main goal of an algorithm is to explain how a task should
be done.
Example:
To find the sum of two numbers, an algorithm might be:
1. Start
2. Read the first number (A)
3. Read the second number (B)
4. Add A and B and store the result in C
5. Display C
6. End

What is a Program?

A program is the actual implementation of an algorithm using a specific programming language


like C++, Python, or Java. It consists of written code that can be compiled and executed by a
computer to perform tasks defined by the algorithm.

Characteristics of a Program:

 Written in a programming language: Like C++, the program must follow the syntax and
rules of that language.
 Executable by a computer: Once compiled, the program runs and performs actions.
 Includes technical details: Like variable declarations, loops, functions, etc.

7. What are C++ statements? What ends every C++ statement?

What are C++ Statements?

In C++, a statement is a single line of code that performs an action. Statements are the basic
building blocks of a C++ program. Each statement tells the computer to do something, such as
declare a variable, perform a calculation, take input, display output, or control the flow of the
program.

Examples of C++ Statements:

5|Page
1. Variable Declaration:
2. Assignment Statement:
3. Input Statement:
4. Output Statement
5. Control Statement:

What Ends Every C++ Statement?

Every C++ statement must end with a semicolon (;).This semicolon tells the compiler that the
current instruction is complete and the next one can begin. Forgetting to use a semicolon results
in a syntax error during compilation.

8. What is the output of the following program?

There are some error in the given programming code

These errors are :

Key corrections made:

1. Changed #include <iostream.h> to #include <iostream> (modern C++ uses the standard
header without .h)
2. Added using namespace std; (since cout is in the std namespace)

// Here is the correct form of the programmer

#include <iostream>

using namespace std;

int main()

cout << "Hello Students!";

cout << "Welcome to C++";

cout << "Introduction to programming!";

6|Page
return 0;

And the out put of this corrected programming code is :

Hello Students!Welcome to C++Introduction to programming!

9. Write a program that calculates and displays the area and the circumference of a circle
based on its radius entered from the keyboard ?

#include <iostream>
#define PI 3.1416

using namespace std;

int main() {
float radius, area, circumference;

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


cin >> radius;

area = PI * radius * radius;


circumference = 2 * PI * radius;

cout << "Area of the circle: " << area << endl;
cout << "Circumference of the circle: " << circumference << endl;

return 0;
}
10. Write a program that swaps the values of two variables and displays their former
and current values. The values of the variables are to be entered from the keyboard ?

#include <iostream>
using namespace std;

int main() {
int a, b, temp;

7|Page
cout << "Enter the first value (a): ";
cin >> a;
cout << "Enter the second value (b): ";
cin >> b;
cout << "\nBefore swapping:" << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;

b = temp;

cout << "\nAfter swapping:" << endl;

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

return 0;
}

11. Write a program that accepts a character from the keyboard and displays its ASCII
code ?

#include <iostream>
using namespace std;

int main() {
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << "The ASCII code of '" << ch << "' is: " << int(ch) << endl;

return 0;
}

12. Write a program that converts a letter entered from the keyboard to its uppercase
or lowercase equivale

#include <iostream>
using namespace std;

int main() {

8|Page
char ch;
cout << "Enter a letter: ";
cin >> ch;
if (ch >= 'a' && ch <= 'z') {
ch = ch - 32;
cout << "Uppercase equivalent: " << ch << endl;
}
else if (ch >= 'A' && ch <= 'Z') {
ch = ch + 32;
cout << "Lowercase equivalent: " << ch << endl;
}
else {
cout << "Invalid input. Please enter a letter (A-Z or a-z)." << endl;
}

return 0;
}

13. Write a program that converts a temperature given in Fahrenheit into Celsius and
vice versa. The program should distinguish temperature entered from the keyboard as
in degree centigrade or as in degree Fahrenheit by the letters 'C/c' or 'F/f' that must be
written in front of the numeric values of temperatures.
For example: If the user enters 10 C or 10 c, the program must understand that the
input is in degree centigrade so it should change to degree Fahrenheit and must
display the temperature as 50 for 50 F ?

#include <iostream>
#include <cctype> // for toupper()
using namespace std;

int main() {
double temp;
char scale;

cout << "Enter temperature (e.g., 32 F or 100 C): ";


cin >> temp >> scale;

scale = toupper(scale); // Convert to uppercase for easier comparison

9|Page
if (scale == 'C') {
// Convert Celsius to Fahrenheit
double fahrenheit = (temp * 9/5) + 32;
cout << temp << " C = " << fahrenheit << " F" << endl;
}
else if (scale == 'F') {
// Convert Fahrenheit to Celsius
double celsius = (temp - 32) * 5/9;
cout << temp << " F = " << celsius << " C" << endl;
}
else {
cout << "Invalid temperature scale. Please use C or F." << endl;
}

return 0;
}

14. Write a program that requests the user to input his/her height in cms and weight in kg
from the keyboard and tells the user whether he/she is balanced, underweight or overweight.
A balanced person must weigh in the range of x ± (10 percent of x).
Where x = height in cms – 100 ?

#include <iostream>

using namespace std;

int main() {

float height, weight;

float idealWeight, lowerLimit, upperLimit;

// Input height and weight

cout << "Enter your height in cm: ";

cin >> height;

10 | P a g e
cout << "Enter your weight in kg: ";

cin >> weight;

// Calculate ideal weight and range

idealWeight = height - 100;

lowerLimit = idealWeight - (0.10 * idealWeight);

upperLimit = idealWeight + (0.10 * idealWeight);

// Display results

cout << "\nIdeal weight: " << idealWeight << " kg" << endl;

cout << "Acceptable weight range: " << lowerLimit << " kg to " << upperLimit << " kg" << endl;

// Check weight status

if (weight < lowerLimit) {

cout << "You are underweight." << endl;

else if (weight > upperLimit) {

cout << "You are overweight." << endl;

else {

cout << "You are balanced." << endl;

return 0;

11 | P a g e

You might also like