Exam 1 Cheat sheet

Structure of Program

C

#include <stdio.h>
int main(){
//body
return 0;
}

C++

#include <iostream>
using namespace std;
int main(){
//body
return 0;
}

User Input

C

int main(){
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old.", age);
return 0;
}

C++

int main(){
int age;
cout << "Enter your age: ";
cin >> age;
cout<<"Your age is: " << age << endl;
return 0;
}

For String:

string name;
cout<<"Enter your name: ";
getline(cin, name);
cout<<"Hello,"<< name <<endl;

Function

C

#include <stdio.h>
void greet(){
printf("Hello!\n);
}
int main(){
greet();
return 0;
}

C++

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

Dynamic Memory Allocation

  • malloc() (C-style) – Allocates memory but does not initialize.

int main() {
// Allocate memory for one integer
int *ptr = (int *)malloc(sizeof(int));

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

// Assign a value (since malloc() does not initialize)
*ptr = 42;
printf("Value: %d\n", *ptr);

// Free the allocated memory
free(ptr);

return 0;
}
  • new (C++ style) – Allocates and initializes memory.

int main() {
// Allocate memory for one integer and initialize it to 42
int *ptr = new int(42);

if (!ptr) {
cout << "Memory allocation failed" << endl;
return 1;
}

cout << "Value: " << *ptr << endl;

// Free the allocated memory
delete ptr;

return 0;
}

Allocating Memory for Arrays

Using malloc() (C-Style)
int *arr = (int *)malloc(5 * sizeof(int));  // Allocate an array of 5 integers
Using new[] (C++ Style)
int *arr = new int[5];  // Allocate an array of 5 integers

Understanding NULL & Safe Deletion

  • If a pointer is deleted, it should be set to NULL to avoid dangling pointers:

int *p = new int(10); 
delete p;
p = NULL;

robot