0% found this document useful (0 votes)
2 views12 pages

Cpp

This document serves as a comprehensive guide for a C++ course tailored for students at Masinde Muliro University, covering topics from basic syntax and data types to advanced concepts like object-oriented programming, file handling, and the Standard Template Library. It includes practical examples and exercises to reinforce learning, culminating in a final project idea for student record management. The course aims to equip students with the skills necessary to write C++ programs for their assignments and projects.

Uploaded by

danmuteti57
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)
2 views12 pages

Cpp

This document serves as a comprehensive guide for a C++ course tailored for students at Masinde Muliro University, covering topics from basic syntax and data types to advanced concepts like object-oriented programming, file handling, and the Standard Template Library. It includes practical examples and exercises to reinforce learning, culminating in a final project idea for student record management. The course aims to equip students with the skills necessary to write C++ programs for their assignments and projects.

Uploaded by

danmuteti57
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

#include <iostream>

#include <string>
using namespace std;

int main() {
string password;
int attempts = 0;
const string correctPassword = "mmust2026"; // Change this to your desired password

cout << "=== MMUST Student Portal Login ===\n";

do {
cout << "\nEnter your password: ";
cin >> password;

attempts++;

if (password == correctPassword) {
cout << "\nLogin Successful! Welcome back.\n";
break; // Exit the loop
}
else {
cout << "Wrong password! Attempt " << attempts << " of 3.\n";
}

} while (attempts < 3);

if (attempts >= 3 && password != correctPassword) {


cout << "\nToo many failed attempts. Account locked for security.\n";
}

return 0;
}

data_type array_name[size];

Declaration:
Welcome to your Full C++ Course for Computer Science , tailored for you at Masinde Muliro
University, Kenya!
I'll structure this like a university semester course—starting from absolute basics to advanced
topics, with real examples relevant to CS students (e.g., grading systems, student records, matrix
operations, file handling for data).
Let's go step-by-step. Bookmark this—it's your all-in-one reference.

📘 TABLE OF CONTENTS
1. Introduction & Setup
2. Basics: Syntax, Variables, Data Types
3. Input/Output (cin, cout)
4. Operators & Expressions
5. Control Structures (if, switch, loops)
6. Arrays (1D & 2D)
7. Strings (C-style & std::string)

8. Functions (pass by value, reference, overloading)


9. Pointers & Dynamic Memory
10. Structures & Unions
11. Classes & Objects (OOP)
12. Inheritance & Polymorphism
13. File I/O
14. Exception Handling
15. Templates (Generic Programming)
16. STL (Vectors, Maps, Algorithms)
17. Final Project Idea

1. INTRODUCTION & SETUP


What is C++?
 General-purpose, compiled language.
 Used in systems, game dev, embedded systems, and high-performance computing.
Setup for MMU Students:
 Use Code::Blocks (available in uni labs) or VS Code with MinGW.
 To compile: g++ [Link] -o output

 Run: ./output (Linux/macOS) or [Link] (Windows)

2. BASICS: SYNTAX, VARIABLES, DATA TYPES


Your First Program
cpp
#include <iostream> // for input/output
using namespace std; // so we don't write std::cout every time

int main() {
cout << "Hello, Masinde Muliro University!" << endl;
return 0; // program success
}

Variables & Data Types


Type Size Example
int 4 bytes int age = 20;
float 4 bytes float gpa = 3.7;
double 8 bytes double pi = 3.14159;
char 1 byte char grade = 'A';
bool 1 byte bool isPass = true;
Example:
cpp
int studentID = 2026001;
double feeBalance = 45000.50;
char campus = 'K' ; // K for Kakamega, M for Main
cout << "Student " << studentID << " owes KSh " << feeBalance;

3. INPUT/OUTPUT (cin, cout)


cpp
int marks;
cout << "Enter your Programming marks: ";
cin >> marks; // take input
cout << "You scored " << marks << "%" << endl;

Multiple inputs:
cpp
string name;
int age;
cout << "Enter name and age: ";
cin >> name >> age; // e.g., "John 22"

4. OPERATORS & EXPRESSIONS


 Arithmetic: + - * / %

 Relational: == != < > <= >=

 Logical: && || !

 Assignment: = += -= *= /=

Example – Calculate Semester Average:


cpp
int cat1, cat2, exam;
cout << "Enter CAT1, CAT2, Exam: ";
cin >> cat1 >> cat2 >> exam;
double total = (cat1 + cat2) * 0.3 + exam * 0.4;
cout << "Semester score: " << total;

5. CONTROL STRUCTURES
if-else
cpp
int score;
cout << "Enter exam score: ";
cin >> score;
if (score >= 70)
cout << "Grade: A" << endl;
else if (score >= 60)
cout << "Grade: B" << endl;
else
cout << "Retake" << endl;

switch (menu system)


cpp
int choice;
cout << "1. Fee balance\n2. Course registration\n3. Exit\nChoose: ";
cin >> choice;
switch(choice) {
case 1: cout << "Your fee balance is KSh 45,000"; break;
case 2: cout << "Register for CS 201"; break;
case 3: cout << "Goodbye!"; break;
default: cout << "Invalid option";
}

Loops
for loop – print 1 to 10
cpp
for(int i=1; i<=10; i++) {
cout << i << " ";
}

while loop – sum of marks until -1


cpp
int mark, sum=0;
cout << "Enter marks (-1 to stop): ";
cin >> mark;
while(mark != -1) {
sum += mark;
cin >> mark;
}
cout << "Total = " << sum;

do-while – at least once


cpp
int pin;
do {
cout << "Enter PIN: ";
cin >> pin;
} while(pin != 1234);

6. ARRAYS (1D & 2D)


1D Array – store 5 student IDs
cpp
int ids[5] = {1001, 1002, 1003, 1004, 1005};
for(int i=0; i<5; i++) {
cout << "ID: " << ids[i] << endl;
}

Input from user:


cpp
int marks[5];
for(int i=0; i<5; i++) {
cout << "Enter mark for student " << i+1 << ": ";
cin >> marks[i];
}

2D Array – matrix (3x3) for course marks


cpp
int scores[3][3] = {
{80, 75, 90}, // student 1
{65, 70, 85}, // student 2
{95, 88, 92} // student 3
};
// Print all
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
cout << scores[i][j] << " ";
}
cout << endl;
}

2D Example – add two matrices:


cpp
int A[2][2], B[2][2], C[2][2];
// Assume A and B are filled
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
C[i][j] = A[i][j] + B[i][j];
7. STRINGS
C-style strings (character arrays)
cpp
char name[20];
cout << "Enter your name: ";
cin >> name; // no spaces
cout << "Hello " << name;

std::string (preferred)
cpp
#include <string>
string fullName;
cout << "Enter full name: ";
getline(cin, fullName); // reads spaces
cout << "Welcome " << fullName;

String operations:
cpp
string course = "Computer Science";
cout << "Length: " << [Link]();
cout << "Substring: " << [Link](0, 8); // "Computer"
if(course == "CS") { ... }

8. FUNCTIONS
Pass by value (copy)
cpp
int add(int a, int b) {
return a + b;
}
// call: int sum = add(5, 3);

Pass by reference (modify original)


cpp
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
// call: swap(a, b); // a and b change

Function overloading (same name, different params)


cpp
int multiply(int a, int b) { return a*b; }
double multiply(double a, double b) { return a*b; }
Example – calculate CGPA:
cpp
double calculateCGPA(int credits[], int grades[], int n) {
int totalCredits=0, totalPoints=0;
for(int i=0; i<n; i++) {
totalCredits += credits[i];
totalPoints += grades[i] * credits[i];
}
return (double)totalPoints / totalCredits;
}

9. POINTERS & DYNAMIC MEMORY


Pointer basics
cpp
int x = 10;
int *ptr = &x; // ptr holds address of x
cout << "Value: " << *ptr; // dereference -> 10

Dynamic array (heap)


cpp
int n;
cout << "How many students? ";
cin >> n;
int *marks = new int[n]; // allocate
for(int i=0; i<n; i++) {
cout << "Enter mark: ";
cin >> *(marks + i); // or marks[i]
}
delete[] marks; // free memory

Why? – When you don't know size at compile time.

10. STRUCTURES & UNIONS


Structure – Student record
cpp
struct Student {
string name;
int regNo;
double gpa;
};

int main() {
Student s1;
[Link] = "Alice";
[Link] = 2026001;
[Link] = 3.8;
cout << [Link] << " GPA: " << [Link];
}
Array of structures:
cpp
Student class[30]; // array of 30 students

Union (shared memory – rarely used)


cpp
union Data {
int intVal;
float floatVal;
};

11. CLASSES & OBJECTS (OOP)


Basic class
cpp
class Book {
private:
string title;
string author;
int pages;
public:
void setData(string t, string a, int p) {
title = t; author = a; pages = p;
}
void display() {
cout << title << " by " << author << ", " << pages << " pages";
}
};

int main() {
Book b1;
[Link]("C++ Primer", "Lippman", 1376);
[Link]();
}

Constructor & Destructor


cpp
class Student {
public:
string name;
Student(string n) { // constructor
name = n;
cout << "Student " << name << " created";
}
~Student() { // destructor
cout << "Student " << name << " destroyed";
}
};

Encapsulation (getters/setters)
cpp
class BankAccount {
private:
double balance;
public:
void deposit(double amt) { if(amt>0) balance+=amt; }
double getBalance() { return balance; }
};

12. INHERITANCE & POLYMORPHISM


Inheritance – base and derived class
cpp
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
void display() { cout << name << ", " << age; }
};

class Student : public Person {


private:
int studentID;
public:
Student(string n, int a, int id) : Person(n, a) {
studentID = id;
}
void display() { // override
Person::display();
cout << ", ID: " << studentID;
}
};

Polymorphism (virtual functions)


cpp
class Shape {
public:
virtual double area() { return 0; }
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() override { return 3.14 * radius * radius; }
};
// Now Shape* ptr can point to Circle and call correct area()

13. FILE I/O


Write to file
cpp
#include <fstream>
ofstream outFile("[Link]");
outFile << "RegNo: 2026001, Name: Alice, GPA: 3.8\n";
[Link]();

Read from file


cpp
ifstream inFile("[Link]");
string line;
while(getline(inFile, line)) {
cout << line << endl;
}
[Link]();

CS Application – store student results in a CSV file for analysis.

14. EXCEPTION HANDLING


cpp
int divide(int a, int b) {
if(b == 0)
throw "Division by zero!";
return a/b;
}
int main() {
try {
cout << divide(10, 0);
} catch(const char* msg) {
cerr << "Error: " << msg << endl;
}
return 0;
}

15. TEMPLATES (Generic Programming)


Function template
cpp
template <typename T>
T maxVal(T a, T b) {
return (a > b) ? a : b;
}
// Works for int, double, string, etc.

Class template
cpp
template <class T>
class Box {
T content;
public:
void set(T c) { content = c; }
T get() { return content; }
};
// Box<int> intBox; Box<string> strBox;

16. STL (Standard Template Library)


Vector (dynamic array)
cpp
#include <vector>
vector<int> marks;
marks.push_back(80);
marks.push_back(90);
for(int i=0; i<[Link](); i++)
cout << marks[i] << " ";
// Or range-based for
for(int m : marks) cout << m << " ";

Map (key-value pairs) – like dictionary


cpp
#include <map>
map<string, double> feeBalances;
feeBalances["Alice"] = 45000.0;
feeBalances["Bob"] = 23000.0;
cout << "Alice owes: " << feeBalances["Alice"];

Algorithm – sort
cpp
#include <algorithm>
sort([Link](), [Link]()); // ascending
reverse([Link](), [Link]()); // descending

17. FINAL PROJECT IDEA (For your CS coursework)


System: MMU Student Record Management
Features:
 Add student (name, regNo, course, fee balance)
 Display all students
 Search by regNo
 Update fee balance
 Save/load from file
Sample snippet (using classes + vectors + file I/O):
cpp
class StudentRecord {
vector<Student> students;
public:
void addStudent(Student s) { students.push_back(s); }
void saveToFile() { /* write to CSV */ }
void loadFromFile() { /* read CSV */ }
};

✅ FINAL SUMMARY – What you can now do:


 Write C++ programs for assignments.
 Use arrays, strings, functions, and pointers.
 Apply OOP (classes, inheritance, polymorphism).
 Handle files and exceptions.
 Use STL for efficient coding.
 Build a complete mini-project.

🧪 Quick Practice (For MMU Labs)


1. Write a program that reads 10 students' marks, computes average, and prints grade.
2. Create a class Course with attributes code, name, creditHours. Use a vector to store
5 courses and display them.
3. Write a function that swaps two numbers using pointers.
4. Read a text file containing student names and scores, compute the highest scorer.

Karibu sana Masinde Muliro! If you need deeper explanation on any section (e.g., pointers,
inheritance, templates), just ask – I'll expand with more examples from a Kenyan university context
(fees, courses, grading systems).
Happy coding! 💻🇰🇪

You might also like