Fundamentals of Sequential Programming (CSC 218)
1. Basics of Programming
What is Programming?
Programming is the process of writing instructions (code) that a computer can understand and
execute.
Programming Syntax and Semantics
- Syntax: The rules of writing code correctly (like grammar in English).
- Semantics: The meaning of the code (does it do what you expect?).
Example (C Programming):
#include <stdio.h>
int main() {
printf("Hello, World!\n"); // Prints text to the screen
return 0;
}
- #include <stdio.h> -> This allows input/output operations (like printf).
- main() -> The starting point of every C program.
- printf("Hello, World!\n"); -> Prints "Hello, World!" on the screen.
- return 0; -> Ends the program successfully.
Variables and Data Types
A variable is a named storage location in memory that holds data.
Common data types in C:
- int -> Stores whole numbers (e.g., 5, 100).
- float -> Stores decimal numbers (e.g., 3.14).
- char -> Stores a single character (e.g., 'A').
- double -> Stores larger decimal numbers (e.g., 3.1415926535).
Example:
int age = 20; // Integer variable
float pi = 3.14; // Floating-point number
char grade = 'A'; // Character
Operators in Programming
Operators are symbols that perform operations on variables and values.
Types of Operators
1. Arithmetic Operators: +, -, *, /, %
2. Relational Operators: ==, !=, <, >, <=, >=
3. Logical Operators: && (AND), || (OR), ! (NOT)
Example:
int a = 10, b = 5;
int sum = a + b; // sum = 15
int result = (a > b) && (b < 10); // result = 1 (true)
2. Control Structures (Decision Making & Loops)
Conditional Statements (if, else, switch)
If-Else Statement:
int number = 10;
if (number > 0) {
printf("Positive number");
} else {
printf("Negative number or zero");
}
Switch Statement (Used for multiple conditions):
int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day");
}
If day is 3, the output will be "Wednesday".
Loops (for, while, do-while)
Loops allow us to execute code multiple times.
For Loop (Used when you know how many times to loop):
for(int i = 1; i <= 5; i++) {
printf("%d ", i);
}
Output: 1 2 3 4 5