C++ Mini Project

Problem Statement

Company’s board member requested admin to provide MIS report of all employees with total, average, min, max, minimum salaried employees, maximum salaried employees and department wise salary.

You need to create a program for the same using following concepts of c++ programming language

  • Encapsulation
  • Abstraction
  • Inheritance

MVPs

  • P0
    1. Create a class Person with datamembers: name, age, city
    2. Create a class Employee which will inherit features of Person class with it’s own datamembers: empid, department, salary
  • P1
    1. Create array of 10 employees and print its data using for loop
  • P2
    1. Find and Print Total Salary, Average Salary, Max Salary, Min Salary
  • P3
    1. Create function getMaxSalEmps() to print employees having highest salary
    2. Create function getMinSalEmps() to print all employees having minimum salary
  • P4
    1. Create function getDeptWiseSalary() to print department wise total salary

Sample Output

How to deploy express app on netlify

Step 1: Login to netlify.com from browser (preferably from default browser using github account)

https://www.netlify.com/

Install netlify locally

npm install netlify-cli -g

Login to netlify from console

netlify init

Step 2: Create project locally with api file projectfolder/functions/api.js

const express = require('express');
const serverless = require('serverless-http');
const app = express();
const router = express.Router();

router.get('/', (req, res) => {
  res.send('App is running..');
});

app.use('/.netlify/functions/api', router);
module.exports.handler = serverless(app);

//const port = 8080;
//app.listen(process.env.PORT || port, () => {	
//	console.log(`Listening on port ${port}`);
//});

Step 3: As we are deploying using lambda function create projectfolder/netlify.toml in project root directory

[build]
    functions = "functions"

Step 4: Modify package.json file

{
    "scripts": {
      "build": "netlify deploy --prod"
    },
    "dependencies": {
      "express": "^4.18.2",
      "netlify-cli": "^12.7.2",
      "netlify-lambda": "^2.0.15",
      "serverless-http": "^3.2.0"
    }
}

Step 5: Install required packages/modules

npm i express

Step 6: Test application locally

netlify functions:serve

Step 7: Build the project and deploy on netlify

NOTE: If you are running it for 1st time then chose Create & configure a new site

npm run build

Access api from browser/postman

https://yourproject.netlify.app/.netlify/functions/api

You can check your functions api in netlify portal as well

https://app.netlify.com/sites/<your-project>/functions/api

CRUDL APP

api.js

const conn_str = "mongodb+srv://<username>:<password>@cluster0.<clusterid>.mongodb.net/<databasename>?retryWrites=true&w=majority";
const mongoose = require("mongoose");

mongoose.connect(conn_str)
.then(() => console.log("Connected successfully..."))
.catch( (error) => console.log(error) );


const express = require("express");
const serverless = require('serverless-http');
const app = express();
const router = express.Router();
var cors = require('cors')
app.use(express.json());
app.use(cors())

const empSchema = new mongoose.Schema(    {
    name: String,
    contact_number: String,
    address: String,
    salary: Number,
    employee_id: Number,
    role: String
});

const emp = mongoose.models.emps || new mongoose.model("emps", empSchema);

router.get('/', (req, res) => {
    res.send('App is running..');
});

router.get("/employees", async (req, res) => {
    // var data = [{name: "hari", salary: 25000}, {name: "sameer", salary: 23000}]
    let data = await emp.find();
    res.send(data)
})

//fetch single document by id
//http://localhost:8989/employees/657d397eea713389134d1ffa

router.get("/employees/:id", async (req, res) => {
    // console.log(req.params)
    let data = await emp.find({_id: req.params['id']});
    res.send(data[0])
})

//update document by id
router.put("/employees", async (req, res) => {

	let u_data = await emp.updateOne({"_id": req.body.id}, {
		"$set": {
			"name" : req.body.name,
			"salary" : req.body.salary,
		}
	});
	
	res.send(u_data);

})


//http://localhost:8989/employees?id=657d397eea713389134d1ffe
router.delete("/employees", async (req, res) => {
    let d_data = await emp.deleteOne({"_id": req.query['id']});
	res.send(d_data);
})

router.post("/employees", async (req, res) => {

    // doc = {
    //     "name":"harsha newly added",
    //     "contact_number":"9833910512",
    //     "address":"mumbai",
    //     "salary":20000,
    //     "employee_id":98829,
    //     "role":"operations"
    // }

    doc = req.body;

    let u = await emp(doc);
	let result = u.save();
	res.send(doc);

})

app.use('/.netlify/functions/api', router);
module.exports.handler = serverless(app);

C crash course

Day 1: Introduction to C Programming

  • Session 1 (3 hours): Introduction to C Programming.
  • Explanation: Learn about the basics of C programming, the structure of a C program, and how to use the printf function to display output.
  • Syntax Example:
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Assignment 1: Write a program that displays “Hello, World!” on the screen.

Output:

  Hello, World!

Assignment 2: Create a program that calculates the area of a rectangle using user-provided width and height.

#include <stdio.h>

int main() {
    float width, height, area;

    printf("Enter width: ");
    scanf("%f", &width);

    printf("Enter height: ");
    scanf("%f", &height);

    area = width * height;
    printf("Area: %.2f\n", area);

    return 0;
}

Output (example):

  Enter width: 4.5
  Enter height: 7.2
  Area: 32.40
  • Session 2 (3 hours): Data types, variables, and basic input/output.
  • Explanation: Learn about different data types, how to declare variables, and use the scanf function to read user input. Perform basic arithmetic calculations.
  • Syntax Example:
#include <stdio.h>

int main() {
    int num1, num2, sum;

    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    sum = num1 + num2;
    printf("Sum: %d\n", sum);

    return 0;
}
  • Assignment 1: Write a program that takes user input for two numbers, adds them, and displays the result. Output (example):
  Enter two numbers: 3 5
  Sum: 8

Assignment 2: Develop a program that converts temperature from Fahrenheit to Celsius.

“`c
#include

int main() {
    float fahrenheit, celsius;

    printf("Enter temperature in Fahrenheit: ");
    scanf("%f", &fahrenheit);

    celsius = (fahrenheit - 32) * 5 / 9;
    printf("Temperature in Celsius: %.2f\n", celsius);

    return 0;
}

Output (example):

  Enter temperature in Fahrenheit: 68
  Temperature in Celsius: 20.00

Day 2: Control Flow and Functions

  • Session 1 (3 hours): Conditional statements (if, else if, else), logical operators.
  • Explanation: Learn about conditional statements to make decisions in your program based on conditions. Use logical operators to combine conditions.
  • Syntax Example:
#include <stdio.h>

int main() {
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num > 0) {
        printf("Positive\n");
    } else if (num < 0) {
        printf("Negative\n");
    } else {
        printf("Zero\n");
    }

    return 0;
}
  • Assignment 1: Write a program that checks if a given number is positive, negative, or zero.
    Output (example):
  Enter a number: -7
  Negative
  • Assignment 2: Create a program that determines the largest of three user-provided numbers.
```c
#include <stdio.h>

int main() {
    int num1, num2, num3, largest;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    if (num1 >= num2 && num1 >= num3) {
        largest = num1;
    } else if (num2 >= num1 && num2 >= num3) {
        largest = num2;
    } else {
        largest = num3;
    }

    printf("Largest: %d\n", largest);

    return 0;
}
```

Output (example):

  Enter three numbers: 15 9 12
  Largest: 15
  • Session 2 (3 hours): Loops (while, for) and switch statements.
  • Explanation: Learn how to create loops for repetitive tasks using while and for. Use the switch statement for multiple choices.
  • Syntax Example:
#include <stdio.h>

int main() {
    int num, i;

    printf("Enter a number: ");
    scanf("%d", &num);

    for (i = 1; i <= 10; i++) {
        printf("%d * %d = %d\n", num, i, num * i);
    }

    return 0;
}
  • Assignment 1: Implement a program that prints a multiplication table for a given number. Output (example):
  Enter a number: 7
  7 * 1 = 7
  7 * 2 = 14
  ...
  7 * 10 = 70

Assignment 2: Write a program that calculates the sum of all even numbers between 1 and a user-provided limit using a loop.

#include <stdio.h>

int main() {
    int limit, sum = 0, i;

    printf("Enter a limit: ");
    scanf("%d", &limit);

    for (i = 2; i <= limit; i += 2) {
        sum += i;
    }

    printf("Sum of even numbers: %d\n", sum);

    return 0;
}

Output (example):

  Enter a limit: 10
  Sum of even numbers: 30

Day 3: Arrays and Strings

  • Session 1 (3 hours): Introduction to arrays, declaring and initializing arrays.
  • Explanation: Learn about arrays, how to declare them, and access their elements. Understand the concept of indexing and looping through arrays.
  • Syntax Example:
#include <stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    printf("Third element: %d\n", numbers[2]);

    return 0;
}
  • Assignment 1: Write a program to find the sum of all elements in an array. Output (example):
  Sum of array elements: 150
  • Assignment 2: Develop a program that finds the smallest element in an array of integers.
#include <stdio.h>

int main() {
    int array[5] = {25, 10, 15, 20, 5};
    int smallest = array[0], i;

    for (i = 1; i < 5; i++) {
        if (array[i] < smallest) {
            smallest = array[i];
        }
    }

    printf("Smallest element: %d\n", smallest);

    return 0;
}

Output (example):

  Smallest element: 5
  • Session 2 (3 hours): Introduction to strings, string functions (strlen, strcpy, etc.).
  • Explanation: Learn about strings in C, which are arrays of characters. Explore various string functions for manipulation.
  • Syntax Example:
#include <stdio.h>

int main() {
    char name[20] = "John";
    printf("Hello, %s!\n", name);

    return 0;
}
  • Assignment 1: Create a program that checks if a given string is a palindrome. Output (example):
  Enter a string: radar
  Palindrome

Assignment 2: Write a program that counts the number of vowels in a user-provided string.

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int i, vowels = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    for (i = 0; i < strlen(str); i++) {
        char ch = tolower(str[i]);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            vowels++;
        }
    }

    printf("Number of vowels: %d\n", vowels);

    return 0;
}

Output (example):

  Enter a string: education
  Number of vowels: 5

Day 4: Pointers and Memory Management

  • Session 1 (3 hours): Pointers, pointer arithmetic, and references.
  • Explanation: Learn about pointers, memory addresses, and how to use pointers to manipulate variables and arrays.
  • Syntax Example:
#include <stdio.h>

int main() {
    int num = 5;
    int *ptr = &num;

    printf("Value of num: %d\n", num);
    printf("Value at ptr: %d\n", *ptr);

    return 0;
}
  • Assignment 1: Write a program that swaps the values of two variables using pointers. Output (example):
  Before swapping: num1 = 5, num2 = 10
  After swapping: num1 = 10, num2 = 5
  • Assignment 2: Develop a program that uses pointers to reverse an array of integers. Output (example):
  Original array: 5 10 15 20 25
  Reversed array: 25 20 15 10 5
  • Session 2 (3 hours): Dynamic memory allocation (malloc, free) and memory leaks.
  • Explanation: Understand dynamic memory allocation using malloc, and how to free allocated memory using free. Learn to prevent memory leaks.
  • Syntax Example:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int n, i, sum = 0;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    for (i = 0; i < n; i++) {
        printf("Enter element %d: ", i + 1);
        scanf("%d", &arr[i]);
        sum += arr[i];
    }

    printf("Average: %.2f\n", (float)sum / n);

    free(arr);

    return 0;
}
  • Assignment 1: Implement a program that dynamically creates an array, populates it with user input, and calculates the average. Output (example):
  Enter the number of elements: 4
  Enter element 1: 12
  Enter element 2: 15
  Enter element 3: 20
  Enter element 4: 10
  Average: 14.25

Assignment 2: Write a program that removes duplicates from an array using dynamic memory allocation.

#include <stdio.h>
#include <stdlib.h>

int* removeDuplicates(int *arr, int *size) {
    int *temp = (int *)malloc(*size * sizeof(int));

    if (temp == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }

    // ... code to remove duplicates ...

    return temp;
}

int main() {
    // ... code to input array ...

    int *result = removeDuplicates(array, &size);

    // ... code to display result ...

    free(result);

    return 0;
}

Output (example):

  Original array: 5 10 15 10 20 25 15 30
  Array after removing duplicates: 5 10 15 20 25 30

Day 5: Functions, Structures, and File I/O

  • Session 1 (3 hours): Functions, function prototypes, and header files.
  • Explanation: Learn about functions, how to declare and define them. Understand the concept of recursion for solving problems.
  • Syntax Example:
#include <stdio.h>

int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main() {
    int num;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    printf("Factorial of %d is %d\n", num, factorial(num));

    return 0;
}
  • Assignment 1: Write a program that calculates the factorial of a given number using a recursive function. Output (example):
  Enter a positive integer: 5
  Factorial of 5 is 120

Assignment 2: Create a program that calculates the nth term of the Fibonacci sequence using a recursive function.

#include <stdio.h>

int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int num;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    printf("Fibonacci(%d) = %d\n", num, fibonacci(num));

    return 0;
}

Output (example):

  Enter a positive integer: 7
  Fibonacci(7) = 13
  • Session 2 (3 hours): Introduction to structures and file I/O.
  • Explanation: Learn about structures, how to define them, and how to use them to group related data. Explore file input/output operations.
  • Syntax Example:
#include <stdio.h>

struct Student {
    char name[50];
    int marks[3];
};

int main() {
    struct Student student1;

    printf("Enter student name: ");
    scanf("%s", student1.name);

    printf("Enter marks for three subjects: ");
    scanf("%d %d %d", &student1.marks[0], &student1.marks[1], &student1.marks[2]);

    // ... code to calculate grade ...

    return 0;
}
  • Assignment 1: Develop a program that reads data from a text file, calculates the sum and average, and writes the results to another file. Output (example):
  Sum: 85
  Average: 17.00

Assignment 2: Write a program that reads student data from a file, calculates their grades, and outputs the result to another file.

#include <stdio.h>

struct Student {
    char name[50];
    int marks[3];
};

char calculateGrade(int marks) {
    // ... code to calculate grade ...
}

int main() {
    FILE *inputFile = fopen("students.txt", "r");

FILE *outputFile = fopen(“grades.txt”, “w”);

    struct Student student;

    while (fscanf(inputFile, "%s %d %d %d", student.name, &student.marks[0], &student.marks[1], &student.marks[2]) != EOF) {
        // ... code to calculate grade ...

        fprintf(outputFile, "Student Name: %s\n", student.name);
        fprintf(outputFile, "Marks: %d %d %d\n", student.marks[0], student.marks[1], student.marks[2]);
        fprintf(outputFile, "Grade: %c\n", calculateGrade(totalMarks));
    }

    fclose(inputFile);
    fclose(outputFile);

    return 0;
}

Output (example):

  Student Name: John Doe
  Marks: 80 85 90
  Grade: A
#include <stdio.h>

struct Student {
    char name[50];
    int marks[3];
};

char calculateGrade(int marks) {
    // ... code to calculate grade ...
}

int main() {
    FILE *inputFile = fopen("students.txt", "r");


    FILE *outputFile = fopen("grades.txt", "w");

    struct Student student;

    while (fscanf(inputFile, "%s %d %d %d", student.name, &student.marks[0], &student.marks[1], &student.marks[2]) != EOF) {
        // ... code to calculate grade ...

        fprintf(outputFile, "Student Name: %s\n", student.name);
        fprintf(outputFile, "Marks: %d %d %d\n", student.marks[0], student.marks[1], student.marks[2]);
        fprintf(outputFile, "Grade: %c\n", calculateGrade(totalMarks));
    }

    fclose(inputFile);
    fclose(outputFile);

    return 0;
}

Output (example):

  Student Name: John Doe
  Marks: 80 85 90
  Grade: A