C Programming Practice: Hello World, Calculator, and Swap Numbers
This tutorial provides beginner-friendly practice programs in C programming, including a "Hello World" program, a simple calculator, and swapping two numbers. These examples help beginners understand program structure, input/output, operators, and variables.
1. Hello World Program
Description
The first program in C that demonstrates basic syntax and output using printf().
Code Example
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Output
Hello, World!
2. Simple Calculator
Description
A program to perform basic arithmetic operations (+, -, *, /) using user input and switch statement.
Code Example
#include <stdio.h>
int main() {
char operator;
float num1, num2, result;
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if(num2 != 0)
result = num1 / num2;
else {
printf("Error! Division by zero.\n");
return 1;
}
break;
default:
printf("Invalid operator\n");
return 1;
}
printf("Result: %.2f\n", result);
return 0;
}
Sample Output
Enter operator (+, -, *, /): +
Enter two numbers: 10 5
Result: 15.00
3. Swap Two Numbers
Description
A program to swap the values of two variables using:
- A temporary variable
- Without temporary variable
Method 1: Using Temporary Variable
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Method 2: Without Temporary Variable
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Sample Output
Enter two numbers: 10 20
After swapping: a = 20, b = 10
Key Points to Remember
- Always include
<stdio.h>for I/O functions - Use
return 0;to indicate successful program execution - Take care of operator precedence in calculations
- Swapping can be done with or without a temporary variable