Table of Contents
C PROGRAMMING MIDTERM CHEAT SHEET ............................................................... 2
1. BASIC STRUCTURE OF A C PROGRAM ................................................................................ 2
2. VARIABLES AND DATA TYPES ........................................................................................... 2
3. BASIC I/O OPERATIONS ................................................................................................ 3
4. OPERATORS ............................................................................................................... 4
5. CONTROL STRUCTURES ................................................................................................ 5
6. LOOPS...................................................................................................................... 5
7. ARRAYS ..................................................................................................................... 6
8. FUNCTIONS ............................................................................................................... 7
9. POINTERS .................................................................................................................. 8
10. STRINGS ................................................................................................................. 9
11. MEMORY MANAGEMENT ............................................................................................ 10
12. STRUCTS AND ENUMS ............................................................................................... 11
13. FILE I/O ................................................................................................................ 12
FLOWCHART CHEAT SHEET WITH CLEAR STEPS AND ARROWS ................................................... 14
14. EXAMPLE PROGRAMS FOR PRACTICE ............................................................................. 24
C PROGRAMMING MIDTERM PRACTICE ................................................................... 25
SECTION 1: MULTIPLE-CHOICE QUESTIONS ......................................................................... 25
SECTION 2: SOLUTIONS .................................................................................................. 33
SECTION 3: CODING PRACTICE PROBLEMS .......................................................................... 33
SECTION 4: SOLUTIONS FOR CODING PRACTICE PROBLEMS ..................................................... 34
1
C Programming Midterm Cheat Sheet
1. Basic Structure of a C Program
In C, every program starts with main, and code is organized with func9ons and
statements within { }.
Example:
#include <stdio.h>
int main() {
// Your code here
return 0;
}
• #include <stdio.h>: Includes standard I/O library, which allows the use of
func9ons like prinG and scanf.
• int main(): The main func9on where program execu9on begins.
• return 0;: Ends the program and returns a value of 0 to the opera9ng system,
indica9ng successful execu9on.
2. Variables and Data Types
Variables store data that the program can manipulate, while data types define the
type of data a variable can hold.
2
• Data Types:
• int: Stores integers (e.g., int num = 5;)
• float: Stores floa9ng-point numbers (e.g., float temp = 25.5;)
• char: Stores single characters (e.g., char leWer = 'A';)
• double: Stores double-precision floa9ng-point numbers for greater
accuracy.
Example:
int age = 20;
float salary = 3000.50;
char grade = 'A';
3. Basic I/O Opera@ons
• Prin@ng Output: Use prinG to display text or variables.
printf("Hello, World!\n");
printf("Age: %d\n", age); // %d for integer
• Reading Input: Use scanf to get user input.
int age;
printf("Enter your age: ");
scanf("%d", &age); // %d matches int type
3
Format Specifiers:
• %d: integer
• %f: float
• %c: character
• %s: string
• %lf: double
4. Operators
• Arithme@c Operators: +, -, *, /, %
• Rela@onal Operators: ==, !=, >, <, >=, <=
• Logical Operators: && (and), || (or), ! (not)
• Assignment Operators: =, +=, -=, *=, /=
Example:
int x = 10;
int y = 5;
int sum = x + y; // Arithmetic
int isEqual = (x == y); // Relational
4
int isPositive = (x > 0 && y > 0); // Logical
5. Control Structures
If-Else: Executes code based on a condi9on.
if (x > y) {
printf("x is greater than y");
} else {
printf("x is not greater than y");
}
Switch: A mul9-branch statement.
int grade = 'A';
switch(grade) {
case 'A':
printf("Excellent");
break;
case 'B':
printf("Good");
break;
default:
printf("Try harder");
}
6. Loops
Loops allow repeated execu9on of a block of code.
• For Loop:
for (int i = 0; i < 10; i++) {
5
printf("%d ", i);
}
• While Loop:
int i = 0;
while (i < 10) {
printf("%d ", i);
i++;
}
• Do-While Loop (executes at least once):
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 10);
Loop Control Statements:
• break: Exits the loop.
• con9nue: Skips the current itera9on and con9nues with the next.
7. Arrays
6
Arrays are collec9ons of variables of the same type, stored in a con9guous block
of memory and accessed with an index.
Declara@on:
int numbers[5]; // An array of 5 integers
Ini@aliza@on:
int numbers[5] = {1, 2, 3, 4, 5}; // Array initialized
with values
Accessing Elements:
printf("%d", numbers[0]); // Access the first element
Example: Looping Through an Array:
for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
8. Func@ons
Func9ons allow code to be organized into reusable blocks. Func9ons can take
parameters and return values.
Syntax:
return_type function_name(parameters) {
// Function code
return value; // Optional, depends on return_type
}
7
Example:
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(5, 10);
printf("Sum: %d", sum);
return 0;
}
Types of Func@ons:
• Void Func@on: A func9on that does not return a value.
void printHello() {
printf("Hello, World!");
}
• Func@on with Parameters: Takes input parameters.
int multiply(int x, int y) {
return x * y;
}
9. Pointers
8
Pointers are variables that store the memory address of another variable. They
are powerful tools in C for handling memory and manipula9ng arrays and strings.
Declara@on and Ini@aliza@on:
int x = 10;
int *ptr = &x; // ptr now points to the address of x
Accessing Pointer Values:
• *ptr: Dereferences the pointer to access the value stored at the pointed
address.
• ptr: The pointer itself, which holds an address.
Example:
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", *ptr); // Output: 10
10. Strings
In C, strings are arrays of characters ending with a null terminator ('\0').
Declara@on and Ini@aliza@on:
char greeting[] = "Hello";
9
Common String Func@ons (from <string.h>):
• strlen(str): Returns the length of the string.
• strcpy(dest, src): Copies src string to dest.
• strcat(dest, src): Concatenates src string to dest.
• strcmp(str1, str2): Compares two strings.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20];
strcpy(str2, str1);
printf("Copied string: %s\n", str2);
return 0;
}
11. Memory Management
Memory management is essen9al in C for dynamic memory alloca9on and freeing
unused memory.
Func@ons for Dynamic Memory Alloca@on (from <stdlib.h>):
10
• malloc(size): Allocates size bytes of memory and returns a pointer to the
allocated memory.
• calloc(n, size): Allocates memory for an array of n elements of size bytes each
and ini9alizes all bytes to zero.
• realloc(ptr, size): Reallocates memory pointed to by ptr to the new size.
• free(ptr): Frees dynamically allocated memory.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
arr = (int *)malloc(5 * sizeof(int)); // Allocate
memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
printf("%d ", arr[i]);
}
free(arr); // Free the allocated memory
return 0;
}
12. Structs and Enums
Structs allow grouping of different data types under a single name.
Declara@on and Usage:
11
struct Person {
char name[50];
int age;
};
int main() {
struct Person person1 = {"Alice", 25};
printf("Name: %s, Age: %d", person1.name,
person1.age);
return 0;
}
Enums are used to assign names to integral constants for beWer readability.
Example:
enum Weekday { Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday };
enum Weekday today = Monday;
if (today == Monday) {
printf("Start of the workweek.");
}
Thank you for checking in! Here’s the final sec9on covering File I/O and Example
Programs.
13. File I/O
File input/output (I/O) allows reading from and wri9ng to files, which is essen9al
for data persistence in C programs.
Basic Func@ons for File I/O (from <stdio.h>):
12
• fopen(filename, mode): Opens a file. Common modes are "r" (read), "w"
(write), and "a" (append).
• fprinG(file, format, ...): Writes formaWed output to a file, similar to prinG.
• fscanf(file, format, ...): Reads formaWed input from a file, similar to scanf.
• fclose(file): Closes an opened file.
Example of Wri@ng to a File:
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Error opening file!");
return 1;
}
fprintf(file, "Hello, file!\n");
fclose(file);
return 0;
}
Example of Reading from a File:
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "r");
char line[100];
if (file == NULL) {
printf("Error opening file!");
return 1;
}
while (fgets(line, sizeof(line), file)) {
13
printf("%s", line);
}
fclose(file);
return 0;
}
Absolutely! Flowcharts with arrows will clarify the steps and help visualize the
logic beWer. Since I can’t directly draw here, I’ll create a descrip9ve format to
simulate each step and direc9on. Here’s how the examples will look with a clearer
flowchart structure.
Flowchart Cheat Sheet with Clear Steps and Arrows
Example 1: Simple Sequence - Sum of Two Numbers
Flowchart:
1. Start ➔
2. Input: Read two numbers (num1 and num2) ➔
3. Process: Calculate sum = num1 + num2 ➔
4. Output: Display sum ➔
5. End
Transla@on in C:
#include <stdio.h>
14
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;
}
Example 2: Decision Making - Check Even or Odd
Flowchart:
1. Start ➔
2. Input: Read a number (num) ➔
3. Decision: Is num % 2 == 0?
• Yes ➔ Output: “Even”
• No ➔ Output: “Odd” ➔
4. End
Transla@on in C:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
15
scanf("%d", &num);
if (num % 2 == 0) {
printf("Even\n");
} else {
printf("Odd\n");
}
return 0;
}
Example 3: For Loop - Print 1 to 5
Flowchart:
1. Start ➔
2. Ini@alize i = 1 ➔
3. Loop: Is i <= 5?
• Yes ➔ Output i ➔ Increment i++ ➔ Repeat step 3
• No ➔ End
Transla@on in C:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
16
return 0;
}
Example 4: While Loop - Count Down from a Number
Flowchart:
1. Start ➔
2. Input: Read a number (num) ➔
3. Loop: Is num > 0?
• Yes ➔ Output num ➔ Decrement num-- ➔ Repeat step 3
• No ➔ End
Transla@on in C:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
printf("%d ", num);
num--;
}
printf("\n");
return 0;
17
}
Example 5: Summing Elements of an Array
Flowchart:
1. Start ➔
2. Ini@alize: Set sum = 0 ➔
3. Loop: For i = 0 to i < 5 ➔
• Input: Read arr[i] ➔
• Process: Add arr[i] to sum ➔
• Increment i++ ➔ Repeat step 3
4. Output: Display sum ➔
5. End
Transla@on in C:
#include <stdio.h>
int main() {
int arr[5];
int sum = 0;
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
18
sum += arr[i];
}
printf("Sum: %d\n", sum);
return 0;
}
Great! I’ll con9nue with a few more flowchart examples in this format to cover a
wider range of programming concepts. Here we go:
Example 6: FuncRon with Parameters - Product of Two Numbers
Flowchart:
1. Start ➔
2. Input: Read two numbers (num1 and num2) ➔
3. Call Func@on: product(num1, num2) ➔
4. Process in Func@on:
• Mul@ply a * b and return the result ➔
5. Output: Display Product ➔
6. End
Transla@on in C:
#include <stdio.h>
19
int product(int a, int b) {
return a * b;
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Product: %d\n", product(num1, num2));
return 0;
}
Example 7: Nested If Statements - Grading System
Flowchart:
1. Start ➔
2. Input: Enter score (score) ➔
3. Decision: Is score >= 90?
• Yes ➔ Output “Grade: A” ➔ End
• No ➔ Next Decision: Is score >= 80?
• Yes ➔ Output “Grade: B” ➔ End
• No ➔ Next Decision: Is score >= 70?
• Yes ➔ Output “Grade: C” ➔ End
20
• No ➔ Output “Grade: F” ➔ End
Transla@on in C:
#include <stdio.h>
int main() {
int score;
printf("Enter your score: ");
scanf("%d", &score);
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Example 8: Summing Digits of a Number
Flowchart:
1. Start ➔
2. Input: Enter a number (num) ➔
3. Ini@alize: sum = 0 ➔
21
4. Loop: While num > 0
• Process: sum = sum + (num % 10) ➔
• Update: num = num / 10 ➔
5. Output: Display sum ➔
6. End
Transla@on in C:
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
sum += num % 10;
num /= 10;
}
printf("Sum of digits: %d\n", sum);
return 0;
}
Example 9: Finding the Maximum of Three Numbers
Flowchart:
1. Start ➔
22
2. Input: Enter three numbers (a, b, c) ➔
3. Decision: Is a >= b and a >= c?
• Yes ➔ Output “Max: a” ➔ End
• No ➔ Next Decision: Is b >= c?
• Yes ➔ Output “Max: b” ➔ End
• No ➔ Output “Max: c” ➔ End
Transla@on in C:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a >= b && a >= c) {
printf("Max: %d\n", a);
} else if (b >= c) {
printf("Max: %d\n", b);
} else {
printf("Max: %d\n", c);
}
return 0;
}
23
14. Example Programs for Prac@ce
Here are a few example programs to prac9ce and reinforce your understanding:
1. Factorial Calcula@on Using Recursion:
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
2. Fibonacci Sequence:
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
3. Average of N Numbers Using Arrays:
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
24
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Average: %.2f\n", (float)sum / n);
return 0;
}
C Programming Midterm Prac0ce
Sec@on 1: Mul@ple-Choice Ques@ons
1. What does the following C code output?
int main() { int a = 5; printf("%d", a); return 0; }
• A. 4
• B. 5
• C. 6
• D. Undefined
2. Which data type can hold a single character?
• A. int
• B. float
25
• C. char
• D. double
3. What is the output of the following code?
int a = 3;
int b = 2;
printf("%d", a * b);
• A. 6
• B. 5
• C. 3
• D. Undefined
4. What is the result of the following condi@on?
int a = 5;
int b = 10;
if (a > b) { printf("True"); } else
{ printf("False"); }
• A. True
• B. False
• C. Undefined
• D. Error
26
5. What will the following loop print?
for (int i = 0; i < 3; i++) {
printf("%d ", i);
}
• A. 0 1 2
• B. 0 1 2 3
• C. 1 2 3
• D. 0 1
6. What is the output of the following code?
int a = 10;
int b = 20;
if (a > b) {
printf("A is greater\n");
} else {
printf("B is greater\n");
}
• A. A is greater
• B. B is greater
• C. Error
• D. None of the above
27
7. Which of the following operators is used to access the value stored at the
memory address held by a pointer?
• A. *
• B. &
• C. ->
• D. .
8. Which of the following correctly declares a pointer to an integer?
• A. int p;
• B. int *p;
• C. *int p;
• D. int &p;
9. What is the output of the following code?
int arr[3] = {1, 2, 3};
printf("%d", arr[1]);
• A. 1
• B. 2
28
• C. 3
• D. Undefined
10. Which func@on is used to find the length of a string in C?
• A. strcpy()
• B. strlen()
• C. strcat()
• D. strcmp()
11. What will the following code print?
int x = 5;
int y = 10;
int z = x + y;
printf("%d", z);
• A. 5
• B. 10
• C. 15
• D. Error
12. Which of the following is the correct syntax for an if statement?
29
• A. if condi9on {}
• B. if (condi9on) {}
• C. if [condi9on] {}
• D. if {condi9on}
13. Which library must be included to use the prinG func@on?
• A. #include <stdlib.h>
• B. #include <math.h>
• C. #include <stdio.h>
• D. #include <string.h>
14. What does malloc func@on do?
• A. Allocates memory dynamically
• B. Frees memory
• C. Copies memory
• D. Checks memory size
30
15. Which of these are valid data types in C?
• A. string
• B. int
• C. double
• D. Both B and C
15. What is the output of the following code?
int i = 0;
while (i < 3) {
printf("%d ", i);
i++;
}
• A. 0 1 2
• B. 1 2 3
• C. 0 1 2 3
• D. Infinite loop
16. Which of the following is a logical operator in C?
• A. &&
• B. ||
31
• C. !
• D. All of the above
17. Which format specifier is used to print a float value?
• A. %d
• B. %f
• C. %c
• D. %s
18. What will be the output of the following code?
int a = 10, b = 5;
printf("%d", a % b);
• A. 0
• B. 1
• C. 2
• D. 5
19.. What does free() do?
32
• A. Allocates memory
• B. Deallocates memory
• C. Copies memory
• D. Resizes memory
Sec@on 2: Solu@ons
Answers for MulRple-Choice QuesRons
1. B 11.C
2. C 12.B
3. A 13.C
4. B 14.A
5. A 15.D
6. B 16.A
7. A 17.D
8. B 18.B
9. B 19.A
10.B 20.B
Sec@on 3: Coding Prac@ce Problems
1. Write a C program that prints all even numbers from 1 to 50.
33
2. Translate the following flowchart into a C program:
Start → Input a number → Check if it’s even or odd → Print result → End.
3. Create a func@on in C that takes two integers and returns their sum.
4. Write a C program to calculate the factorial of a given number.
5. Translate a flowchart that prints the first 10 numbers in the Fibonacci
sequence into C.
6. Implement a C program that finds the largest number in an array of
integers.
7. Translate a flowchart that takes user input for a number and prints “Even”
or “Odd” into C.
8. Write a C program that reverses an array of integers.
9. Create a C program that calculates the average of N numbers provided by
the user.
10. Translate a flowchart for a simple ATM simulator (Deposit, Withdraw,
Check Balance) into C.
Sec@on 4: Solu@ons for Coding Prac@ce Problems
1. Solu@on for Prin@ng Even Numbers from 1 to 50
#include <stdio.h>
int main() {
for(int i = 1; i <= 50; i++) {
if(i % 2 == 0) {
34
printf("%d ", i);
}
}
return 0;
}
2. Flowchart to C - Even or Odd Check
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num % 2 == 0)
printf("Even\n");
else
printf("Odd\n");
return 0;
}
3. Func@on to Sum Two Integers
#include <stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int a = 5, b = 3;
printf("Sum: %d\n", sum(a, b));
return 0;
}
4. Factorial Calcula@on
#include <stdio.h>
int factorial(int n) {
int result = 1;
for(int i = 1; i <= n; i++)
result *= i;
35
return result;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial: %d\n", factorial(num));
return 0;
}
5. Fibonacci Sequence for First 10 Numbers
#include <stdio.h>
int main() {
int n1 = 0, n2 = 1, n3;
printf("%d %d ", n1, n2);
for(int i = 2; i < 10; ++i) {
n3 = n1 + n2;
printf("%d ", n3);
n1 = n2;
n2 = n3;
}
return 0;
}
6. Finding Largest in Array
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 8, 5};
int max = arr[0];
for(int i = 1; i < 5; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
printf("Largest: %d\n", max);
return 0;
}
36
7. Even or Odd Check Using Flowchart Transla@on
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number % 2 == 0)
printf("Even\n");
else
printf("Odd\n");
return 0;
}
8. Reversing an Array of Integers
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int n = 5;
printf("Original Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\nReversed Array: ");
for (int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
return 0;
}
37
9. Calcula@ng the Average of N Numbers Provided by the User
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int numbers[n];
for (int i = 0; i < n; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
float average = (float)sum / n;
printf("Average: %.2f\n", average);
return 0;
}
10. ATM Simulator (Deposit, Withdraw, Check Balance)
#include <stdio.h>
int main() {
int balance = 100; // Starting balance
int choice, amount;
do {
printf("\nATM Menu:\n");
printf("1. Check Balance\n");
printf("2. Deposit\n");
printf("3. Withdraw\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
38
switch (choice) {
case 1:
printf("Balance: $%d\n", balance);
break;
case 2:
printf("Enter amount to deposit: ");
scanf("%d", &amount);
balance += amount;
printf("Deposit successful! New
balance: $%d\n", balance);
break;
case 3:
printf("Enter amount to withdraw: ");
scanf("%d", &amount);
if (amount <= balance) {
balance -= amount;
printf("Withdrawal successful! New
balance: $%d\n", balance);
} else {
printf("Insufficient funds.\n");
}
break;
case 4:
printf("Exiting ATM.\n");
break;
default:
printf("Invalid choice. Please try
again.\n");
}
} while (choice != 4);
return 0;
}
39