Friday, April 4, 2025

Comparison of Basic Programming Rules in C++ and Python

 Here is a comparison of basic programming rules in C++ and Python, along with simple code examples to illustrate each concept:


🔹 1. Program Structure and Syntax

ConceptC++Python
File extension.cpp.py
CompilationRequired (e.g., g++)Interpreted
SemicolonsRequired (;)Not used
Braces {}Used to define blocksIndentation defines blocks

Example: Hello World

C++

#include <iostream>
using namespace std; int main() { cout << "Hello, World!" << endl; return 0; }

Python

print("Hello, World!")

🔹 2. Variables and Data Types

C++Python
Variables must be declared with a typeDynamically typed
int, float, char, etc.int, float, str, etc.

C++

int age = 25;
float weight = 70.5; char grade = 'A';

Python

age = 25
weight = 70.5 grade = 'A'

🔹 3. Input/Output

C++Python
Uses cin and coutUses input() and print()

C++

#include <iostream>
using namespace std; int main() { int x; cout << "Enter a number: "; cin >> x; cout << "You entered: " << x << endl; return 0; }

Python

x = int(input("Enter a number: "))
print("You entered:", x)

🔹 4. Conditional Statements

C++

int x = 10;
if (x > 5) { cout << "x is greater than 5"; } else { cout << "x is 5 or less"; }

Python

x = 10
if x > 5: print("x is greater than 5") else: print("x is 5 or less")

🔹 5. Loops

For loop

C++

for (int i = 0; i < 5; i++) {
cout << i << " "; }

Python

for i in range(5):
print(i, end=" ")

While loop

C++

int i = 0;
while (i < 5) { cout << i << " "; i++; }

Python

i = 0
while i < 5: print(i, end=" ") i += 1

🔹 6. Functions

C++

int add(int a, int b) {
return a + b; }

Python

def add(a, b):
return a + b

🔹 7. Classes and Objects

C++

class Person {
public: string name; int age; void greet() { cout << "Hello, my name is " << name << endl; } };

Python

class Person:
def __init__(self, name, age): self.name = name self.age = age def greet(self): print("Hello, my name is", self.name)

No comments:

Post a Comment

Basic Comparison of C++ and HTML/JavaScript

 Here’s a basic comparison of C++ and HTML/JavaScript for common programming concepts and  simple code examples for each. This will help ...