Loading...

PROGRAMMING CONCEPTS  

>

LEARNING OUTCOME 4

C++ PROGRAM STRUCTURE

A well-structured C++ program is organized into logical components that enhance readability, maintainability, and modularity. Here's a breakdown of the essential elements:

1. Preprocessor Directives (# lines):

2. Global Declarations:

3. Functions:

4. Local Declarations:

5. Valid C++ Statements:

6. Comments:

Example:

				
					#include 
						using namespace std; // Avoids repeatedly writing `std::` for standard
						library elements
						int main() {
						 // Local variable declaration
						 int number;
						 cout << "Enter a number: ";
						 cin >> number;
						 cout << "You entered: " << number << endl;
						 return 0; // Indicates successful program execution
						}
				
			  

Key Points:

FUNDAMENTAL PROGRAMMING CONCEPTS

Data Types:

Variables:

Operators:

Expressions:

Control Flow Statements:

Functions:

Comments:

Input and Output:

Memory Management:

PROGRAMMING ERRORS

1. Syntax Errors:

2. Runtime Errors:

3. Logical Errors:

4. Linker Errors:

5. Semantic Errors:

IDENTIFIER:

Types of Identifiers:

  1. Predefined Identifiers:
    • These identifiers are already defined by the programming language itself.
    • They represent keywords like int, float, if, else, for, while, etc., or standard library functions like printf, cin (C++), print, input (Python).
    • You cannot use predefined identifiers as your own variable or function names because they have special meanings in the language.
  2. User-Defined Identifiers:
    • These identifiers are created by the programmer to name variables, functions, constants, etc., specific to their program.
    • They allow you to create meaningful names that reflect the element's purpose.

Rules for Naming Identifiers:

Variable and Constant Identifiers:

				
					#include 
						using namespace std;
						int main() {
						 // User-defined identifiers: variables
						 int age;
						 double accountBalance;
						 // User-defined identifier: constant (by convention)
						 const double PI = 3.14159;
						 // Predefined identifiers (keywords)
						 cout << "Enter your age: ";
						 cin >> age;
						 cout << "You are " << age << " years old." << endl;
						 return 0;
						}
						
				
			  

DATA TYPES

Define the kind of values a variable can hold and the operations that can be performed on them.

Standard Data Types:

C++ provides a variety of built-in data types for storing different kinds of data:

User-Defined Data Types:

While standard data types are fundamental, C++ allows you to create your own complex data structures:

OPERATORS

Operators are symbols that perform specific operations on data (operands) in C++ expressions. Understanding operators is essential for manipulating data, making decisions, and controlling program flow. Here's a breakdown of some common operators:

  1. Arithmetic Operators:
    • Perform mathematical calculations on numeric operands (integers, floating-point numbers).
    • Examples:
      • + (addition)
      • - (subtraction)
      • * (multiplication)
      • / (division)
      • % (modulo - remainder after division)
  2. Assignment Operator (=):
    • Assigns a value to a variable.
    • Examples:
      • x = 5: Assigns the value 5 to the variable x.
    • Compound Assignment Operators: Combine assignment with an arithmetic operation.
      • x += 3: Equivalent to x = x + 3 (increases x by 3)
      • y -= 2: Equivalent to y = y - 2 (decreases y by 2)
  3. Relational Operators:
    • Compare operands and return Boolean values (true or false).
    • Examples:
      • == (equal to)
      • != (not equal to)
      • < (less than)
      • > (greater than)
      • <= (less than or equal to)
      • >= (greater than or equal to)
  4. Logical Operators:
    • Combine Boolean expressions to form more complex conditions.
    • Examples:
      • && (AND): Both conditions must be true for the expression to be true.
      • || (OR): At least one condition must be true for the expression to be true.
      • ! (NOT): Inverts the truth value of an expression.
  5. Ternary Operator (?:):
    • Shorthand conditional expression.
    • Syntax: condition ? expression_if_true : expression_if_false
    • Example:
      age >= 18 ? cout << "You are eligible to vote." << endl; : cout << "You are not eligible to vote." << endl;
  6. Comma Operator (,):
    • Evaluates multiple expressions from left to right, returning the value of the rightmost expression.
    • Often used to combine multiple expressions within a statement.
    • Example:
      int x = 10, y = 20;
      Declares and initializes both x and y in one statement.
  7. Dot/Member Operator (.):
    • Accesses members (variables or functions) of objects or structures.
    • Syntax: object_name.member_name
    • Example: person.age: Accesses the age member variable of an object named person.

FUNCTIONS

What is a Function?

A function is a reusable block of code that performs a specific task. It encapsulates a set of instructions that can be called from different parts of your program, promoting modularity and code organization.

Benefits of Using Functions:

  1. Code Reusability: The same function can be called multiple times within your program or even in different programs, avoiding code duplication and saving time.
  2. Modularity: Functions break down complex programs into smaller, manageable units, making the code easier to understand, maintain, and modify.
  3. Improved Readability: Well-named functions clearly convey their purpose, enhancing code readability.
  4. Reduced Errors: By encapsulating logic within functions, you can isolate and test specific functionalities, leading to fewer errors.
  5. Enhanced Organization: Functions help organize code logically, promoting maintainability and collaboration.
  6. Information Hiding: Functions can hide implementation details, exposing only necessary functionality through their interfaces (parameters and return type). This promotes encapsulation and reduces coupling between program parts.
  7. Easier Debugging: By isolating functionality in functions, it's easier to debug specific parts of your code.
  8. Improved Testability: Reusable functions can be easily tested independently, leading to more robust and reliable programs.

PREDEFINED AND USER-DEFINED FUNCTIONS

C++ provides both predefined (built-in) functions and user-defined functions:

  1. Predefined Functions:
    • These functions are already defined by the C++ standard library and available for use in your programs.
    • Examples:
      • cout (standard output), cin (standard input) for input/output operations.
      • sqrt (square root), sin, cos (mathematical functions).
      • strlen (string length), strcpy (string copy) (string manipulation functions).
    • They are typically declared in header files like <iostream>, <cmath>, <cstring>, etc.
  2. User-Defined Functions:
    • You create these functions to perform specific tasks in your program.
    • Structure:
      • return_type function_name(parameter_list) { function body }
        • return_type: The data type of the value the function returns (or void if it doesn't return anything).
        • function_name: A unique identifier for the function.
        • parameter_list: A comma-separated list of parameters (variables) that the function takes as input (optional).
        • function body: The code that executes when the function is called.
					
						#include 
							using namespace std;
							// User-defined function to calculate the area of a rectangle
							double calculateArea(double length, double width) {
							 return length * width;
							}
							int main() {
							 double rectLength = 5.0;
							 double rectWidth = 3.0;
							 double area = calculateArea(rectLength, rectWidth);
							 cout << "Area of the rectangle: " << area << endl;
							 return 0;
							}
							
							
					
				  

In this example, calculateArea is a user-defined function that takes two parameters

(length and width) and calculates the area, returning the result. The main function calls calculateArea to perform the calculation and print the result.

By understanding and utilizing both predefined and user-defined functions, you can write efficient, modular, and reusable C++ programs.

VOID AND VALUE RETURNING FUNCTIONS

Void vs. Value-Returning Functions

Feature Void Function Value-Returning Function
Return Type void Any data type (or void)
Returns a Value No Yes
Typical Use Performing actions without needing to return a specific value (e.g., printing to the console) Providing a calculated value or data to be used in the calling code
Example void printMessage() { cout << "Hello!" << endl; } int addNumbers(int x, int y) { return x + y; }

PARAMETER PASSING IN C++

Parameter passing refers to the mechanism by which arguments (values or variables) are passed to functions when they are called. C++ uses pass-by-value for parameter passing. This means that a copy of the argument's value is passed to the function, not the original variable itself.

Example:

			
				void modifyValue(int num) {
					num = 10; // This modifies the copy of num, not the original variable
				   }
				   int main() {
				   int x = 5;
					modifyValue(x);
				   cout << x << endl; // Output: 5 (original value remains unchanged)
				   }
				   
					
			
		  

However, for arrays and objects (complex data structures), passing a copy of the entire structure might be inefficient.

In these cases, C++ provides references, which allow you to pass a reference to the original memory location of the variable.

VARIABLE SCOPE AND RULES

Variable scope refers to the part of the program where a variable is accessible and usable. Understanding scope is crucial for avoiding naming conflicts and ensuring proper data access.

Types of Scope:

  1. Block Scope: Variables declared within a code block (e.g., if statement, loop) are only accessible within that block.
  2. Function Scope: Variables declared within a function are only accessible within that function and any nested functions within it.
  3. File Scope (Global Scope): Variables declared outside any function but within the same source file are accessible throughout the file. Use global variables sparingly as they can lead to naming conflicts and make code harder to maintain.

Scope Rules:

  1. A variable can't have the same name as a predefined identifier (keyword) in C++.
  2. A variable can't be declared twice within the same scope (block or function).
  3. A variable declared within an inner scope (e.g., nested function) takes precedence over a variable with the same name in an outer scope.

Example:

				
					int globalVar = 10; // Global scope
void outerFunction() {
int localVar = 20; // Function scope
if (true) {
 int blockVar = 30; // Block scope
 cout << blockVar << endl; // Accessible here
 }
// cout << blockVar << endl; // Error: blockVar not accessible here
(out of scope)
cout << localVar << endl; // Accessible here
cout << globalVar << endl; // Accessible here (global)
}
int main() {
// cout << localVar << endl; // Error: localVar not accessible here
(out of scope)
cout << globalVar << endl; // Accessible here (global)
 outerFunction();
return 0;
}

						
				
			  

FUNCTION PROTOTYPE VS. FUNCTION DEFINITION

Feature Function Prototype Function Definition
Purpose Announces a function's existence Provides the function's implementation
Location Placed before the function's first call or at the beginning of the source file Placed after all other code in the source file
Body Does not contain the function body (code) Contains the function body (code) with curly braces {}
Return Type Specifies the return type Must specify the return type and match the prototype
Parameters Specifies parameter list (data types and names) Must specify parameter list and match the prototype
Semicolon Ends with a semicolon (;) Does not end with a semicolon (;)
Example void greet(string name); void greet(string name) { cout << "Hello, " << name << endl; }

FUNCTION OVERLOADING

Function overloading refers to the ability to define multiple functions with the same name but different parameter lists. This allows you to create functions that perform similar tasks but can accept different types or numbers of arguments.

Benefits of Function Overloading:

Example

		
			// Function to calculate area of a rectangle (overload 1)
double calculateArea(double length, double width) {
 return length * width;
}
// Function to calculate area of a square (overload 2)
double calculateArea(double side) {
 return side * side;
}
int main() {
 double rectArea = calculateArea(5.0, 3.0);
 double squareArea = calculateArea(4.0);
 cout << "Rectangle area: " << rectArea << endl;
 cout << "Square area: " << squareArea << endl;
 return 0;
}

				
		
	  

Function Overloading

In this example, we have two calculateArea functions with different parameter lists. The compiler can identify which function to call based on the arguments provided in the main function.

Note: Function overloading works based on the combination of function name and parameter list. You cannot overload functions based solely on the return type.

C++ CONTROL STRUCTURES

They dictate the flow of execution in your program. They allow you to control which parts of your code run and when, making your programs more dynamic and interactive. Here's a breakdown of the three fundamental control structures:

1. Sequence:

Example:

C++
	int x = 5;
	double y = 3.14;
	cout << "x = " << x << endl;
	cout << "y = " << y << endl;
	

2. Selection:

Example:

C++
	int grade = 85;
	if (grade >= 90) {
		cout << "Excellent work! You earned an A." << endl;
	} else if (grade >= 80) {
		cout << "Great job! You earned a B." << endl;
	} else {
		cout << "Keep studying! You earned a C or lower." << endl;
	}
	

3. Iteration (Looping):

Example:

C++
	for (int i = 1; i <= 5; ++i) {
		cout << "Iteration " << i << endl;
	}
	int count = 0;
	while (count < 3) {
		cout << "Looping..." << endl;
		count++;
	}
	

Code examples demonstrating control structures

1. Sequence:

Example:

		  #include 
			using namespace std;
			int main() {
			 int num1, num2, sum;
			 cout << "Enter two numbers: ";
			 cin >> num1 >> num2;
			 // Sequence: Statements execute one after another
			 sum = num1 + num2;
			 cout << "The sum of " << num1 << " and " << num2 << " is " << sum
			<< endl;
			 return 0;
			}
			
				  
		  
		

Exam Question:

Write a C++ program that prompts the user to enter two numbers, calculates their sum, and displays the result.

Selection (if-else):

Example:

C++
	  #include <iostream>
	  using namespace std;
	  int main() {
		  int age;
		  cout << "Enter your age: ";
		  cin >> age;
		  // Selection: Code block based on the condition
		  if (age >= 18) {
			  cout << "You are eligible to vote." << endl;
		  } else {
			  cout << "You are not eligible to vote." << endl;
		  }
		  return 0;
	  }
	  

Exam Question:

Write a C++ program that asks the user for their age and determines if they are eligible to vote (voting age is 18 or older). Print a message indicating their eligibility.

Iteration (for loop):

Example:

C++
	  #include <iostream>
	  using namespace std;
	  int main() {
		  int num_students;
		  cout << "Enter the number of students: ";
		  cin >> num_students;
		  // Loop: Repeats the code block for each iteration
		  for (int i = 1; i <= num_students; ++i) {
			  cout << "Student " << i << endl;
		  }
		  return 0;
	  }
	  

DATA STRUCTURE

Data Structure:

ARRAYS

Array Implementation:

  1. Define Array:
    C++
    	  data_type array_name[size];
    			  
  2. Declare Array (One-Dimensional):
    C++
    	  int numbers[10]; // Array to store 10 integers
    			  
  3. Initialize Array (One-Dimensional):
    • There are two main ways to initialize arrays:
      • During declaration:
        C++
        	  int fruits[5] = {1, 2, 3, 4, 5}; // Initialize elements directly
        							  
      • After declaration (using an assignment operator):
        C++
        	  int scores[3];
        	  scores[0] = 85;
        	  scores[1] = 90;
        	  scores[2] = 78; // Assign values to individual elements
        							  
  4. Two-Dimensional Arrays:
    • Two-dimensional arrays represent a grid or table-like structure.
    • Declare them with two square brackets:
      C++
      	  data_type array_name[rows][columns];
      					  
    • Example:
      C++
      	  int matrix[3][2]; // 3 rows, 2 columns
      					  
  5. Accessing and Manipulating Elements:
    • Elements are accessed using their index (starting from 0).
    • Example:
      C++
      	  numbers[2] = 100; // Assigns 100 to the element at index 2
      	  cout << matrix[1][0] << endl; // Prints the element at row 1, column 0
      					  

Additional Notes:

Example Problem: Calculating Student Averages

Suppose you have an array to store the scores of 5 students. Write a C++ program to calculate the average score:

C++
	  #include <iostream>
	  using namespace std;
	  int main() {
		  int scores[5];
		  double average;
		  int sum = 0;
		  // Get student scores
		  for (int i = 0; i < 5; ++i) {
			  cout << "Enter score for student " << i + 1 << ": ";
			  cin >> scores[i];
		  }
		  // Calculate sum
		  for (int i = 0; i < 5; ++i) {
			  sum += scores[i];
		  }
		  // Calculate average
		  average = static_cast(sum) / 5; // Cast to double for accurate division
		  cout << "The average score is: " << average << endl;
		  return 0;
	  }
	  

This program demonstrates how to declare, initialize, access, and manipulate elements in a one-dimensional array to solve a simple problem. You can extend this concept to more complex scenarios using arrays effectively.

STRUCTURES (STRUCTS) IN PROBLEM SOLVING

  1. Define Structure (struct):

    A structure (struct) is a user-defined data type that groups variables of potentially different data types under a single name. This allows you to create composite data types that represent real-world entities with various attributes.

  2. Create Structure:
    C++
    struct structure_name {
        // Member variables (data types and names)
    };

    Example:

    C++
    struct Person {
        string name;
        int age;
        double height;
    };
  3. Instantiate Structure:

    Declare a variable of the structure type to create an instance:

    C++
    Person person1;
  4. Manipulate Structure Members:
    • Access and modify member variables using the dot (.) operator:
    • C++
      person1.name = "Alice";
      person1.age = 30;
      person1.height = 1.75;
  5. Implementing Structures in Problem Solving:

    Structures are versatile and can be used for various problem-solving tasks:

    • Representing Complex Objects: Define a structure to group related data for tasks like storing student information (name, ID, grades), product information (name, price, quantity), or employee data (name, position, department).
    • Organizing Data: Structures help maintain data integrity and make code more readable.
    • Passing Data as a Unit: You can pass structures as arguments to functions, making it easier to work with complex data.
  6. Example: Library Book Management

    Imagine a library system where you need to store information about books. You can create a Book structure to represent each book:

    C++
    struct Book {
        string title;
        string author;
        int year_published;
        bool is_available;
    };

    This structure defines four member variables to hold the book's title, author, publication year, and availability status. You can then declare an array of Book structures to manage a collection of books in the library.

  7. Benefits of Using Structures:
    • Data Organization: Organize related data into a single unit, making code more readable and maintainable.
    • Data Integrity: Ensures that data elements are always grouped together, reducing errors.
    • Efficiency: Can be more efficient than using separate variables for each data element, especially when passing data to functions.

CLASSES

  1. Class:

    A class is a user-defined blueprint or template that represents real-world entities with their attributes (data members or variables) and behaviors (methods or functions). Classes provide a powerful way to encapsulate data and functionality, promoting modularity and code reusability.

  2. Creating a Class:
    C++
    class class_name {
    private:
        // Data members (private by default)
    public:
        // Member functions (public by default)
    };

    Access Specifiers (they are optional):

    • private: Members are accessible only within the class.
    • public: Members are accessible from anywhere in the program.
    • protected: Members are accessible within the class and derived classes (inheritance).
  3. Instantiate Class (Object Creation):
    C++
    class_name object_name;
  4. Overload Class Method:
    • Define multiple methods with the same name but different parameter lists.
    • The compiler selects the appropriate method based on the arguments provided at the call.
  5. Example: Implementing a Bank Account Class
    C++
    #include 
    using namespace std;
    
    class BankAccount {
    private:
        string name;
        double balance;
    public:
        // Constructor (optional) - Initializes object's state
        BankAccount(string account_name, double initial_balance = 0.0) {
            name = account_name;
            balance = initial_balance;
        }
        // Member functions (methods)
        void deposit(double amount) {
            balance += amount;
        }
        bool withdraw(double amount) {
            if (balance >= amount) {
                balance -= amount;
                return true; // Successful withdrawal
            } else {
                return false; // Insufficient funds
            }
        }
        double getBalance() const { // const prevents accidental modification
            return balance;
        }
        // Method overloading (deposit with different parameter)
        void deposit(string depositor_name, double amount) {
            cout << depositor_name << " deposited $" << amount << endl;
            deposit(amount); // Call internal deposit method
        }
    };
    
    int main() {
        BankAccount account("John Doe");
        account.deposit(100.0);
        if (account.withdraw(50.0)) {
            cout << "Withdrawal successful. New balance: $" << account.getBalance() << endl;
        } else {
            cout << "Insufficient funds." << endl;
        }
        account.deposit("Jane Doe", 75.0); // Overloaded deposit method
        return 0;
    }

FILES

File streams provide a mechanism for your C++ programs to interact with files, allowing you to read data from or write data to external storage.

TEXT VS. BINARY FILES:

FILE STREAMS

C++ provides file streams for working with files. Here are the main classes:

File Stream Operations:

Example: Reading a Text File:

#include 
#include 
using namespace std;

int main() {
    ifstream inputFile("data.txt");
    if (inputFile.is_open()) {
        string line;
        // Read contents line by line
        while (getline(inputFile, line)) {
            cout << line << endl;
        }
        inputFile.close();
    } else {
        cerr << "Error: Could not open file." << endl;
    }
    return 0;
}

Important Note:

CREATING TEXT FILES:

C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream outputFile("new_file.txt"); // Creates "new_file.txt" if it doesn't exist, overwrites if it does
    if (outputFile.is_open()) {
        outputFile << "This is some text written to the new file.\n";
        outputFile << "Another line of text can be added here.\n";
        outputFile.close();
        cout << "File created and written to successfully." << endl;
    } else {
        cerr << "Error: Could not create file." << endl;
    }
    return 0;
}

FILE OPENING MODES:

WRITE OPERATIONS:

C++
ofstream outputFile("data.txt", ios::app); // Open "data.txt" for appending
if (outputFile.is_open()) {
    outputFile << "\nMore data to be appended." << endl;
    outputFile.close();
}

READ OPERATIONS:

C++
ifstream inputFile("data.txt");
if (inputFile.is_open()) {
    string line;
    while (getline(inputFile, line)) {
        cout << line << endl;
    }
    inputFile.close();
} else {
    cerr << "Error: Could not open file for reading." << endl;
}

Example Program:

Here's a C++ program that demonstrates reading a text file, counting the number of lines, and displaying the result:

C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
    string filename;
    int lineCount = 0;
    // Get the filename from the user
    cout << "Enter the name of the file: ";
    getline(cin, filename);
    // Open the file for reading
    ifstream inputFile(filename);
    if (inputFile.is_open()) {
        string line;
        // Read each line and increment the counter
        while (getline(inputFile, line)) {
            lineCount++;
        }
        // Close the file
        inputFile.close();
        cout << "The file '" << filename << "' has " << lineCount << " lines." << endl;
    } else {
        cerr << "Error: Could not open file '" << filename << "'." << endl;
    }
    return 0;
}

Explanation:

  1. Include headers:
    • <iostream> for input/output operations (cout, cin)
    • <fstream> for file stream operations (ifstream)
  2. Declare variables:
    • filename: A string to store the file name entered by the user.
    • lineCount: An integer to keep track of the number of lines.
  3. Get filename:
    • Prompt the user to enter the file name and store it in the filename variable using getline (to handle spaces).
  4. Open the file:
    • Create an ifstream object named inputFile and pass the filename as an argument.
    • Use is_open() to check if the file was opened successfully.
  5. Read and count lines (if file opened successfully):
    • Create a string variable line to store each line read from the file.
    • Use a while loop with getline(inputFile, line) to read each line until the end of file is reached.
    • Inside the loop, increment the lineCount for each line read.
  6. Close the file:
    • Use inputFile.close() to close the file stream and release resources.
  7. Display results:
    • If the file was opened successfully, print a message with the file name, line count, and a newline character (endl).
    • If there was an error opening the file, print an error message with the file name.
  8. Return 0:
    • Indicate successful program execution.

End of Outcome Quiz

1 of 20

    Quiz Score

    Percentage: 0%

    Answered Questions: 0

    Correct Answers: 0

    Faults: