CSC 233: Computer Programming II - Assignment Answers
1a) Difference between Object-Oriented Programming (OOP) and Procedural Programming:
- Object-Oriented Programming (OOP):
* Focuses on objects which contain data and methods.
* Follows concepts like inheritance, polymorphism, encapsulation, and abstraction.
* Promotes code reuse and modularity.
- Procedural Programming:
* Focuses on functions and procedures to perform tasks.
* Follows a top-down approach.
* Less modular, less reusable.
Object-Oriented Programming Techniques:
- Polymorphism: One function behaves differently based on context.
- Encapsulation: Wrapping data and functions together.
- Inheritance: One class can inherit from another.
- Abstraction: Hiding internal details from the user.
2a) C++ Program:
#include <iostream>
using namespace std;
int main() {
int age;
float gpa;
char grade;
age = 20;
gpa = 3.75;
grade = 'A';
cout << "Student Age: " << age << endl;
cout << "Student GPA: " << gpa << endl;
cout << "Student Grade: " << grade << endl;
return 0;
2b) C++ Program for Area of Rectangle:
#include <iostream>
using namespace std;
int main() {
float length, width, area;
cout << "Enter length: ";
cin >> length;
cout << "Enter width: ";
cin >> width;
area = length * width;
cout << "Area = " << area << endl;
return 0;
3a) Naming Variables in C++:
Rules:
- Start with a letter or underscore.
- Can include letters, digits, underscores.
- Avoid C++ keywords.
Best Practices:
- Use meaningful names.
- Use camelCase or snake_case.
- Avoid single letters.
Examples:
- Good: studentAge, totalMarks
- Bad: x, 123name, int
3b) Conditional Statements:
Types:
1. if
2. if...else
3. switch
Example:
int score = 75;
if (score >= 50) cout << "Passed";
else cout << "Failed";
4a) IF-ELSE Statement:
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter number: ";
cin >> number;
if (number > 0) cout << "Positive";
else if (number < 0) cout << "Negative";
else cout << "Zero";
return 0;
4b) Loops in C++:
1. for loop:
for(int i=0; i<5; i++) { cout << i << endl; }
2. while loop:
int i = 0;
while(i < 5) { cout << i << endl; i++; }
3. do...while loop:
int i = 0;
do { cout << i << endl; i++; } while(i < 5);