Sure! Below are some examples of C code demonstrating different concepts:
1. Hello World Program
This is a simple program that prints "Hello, World!" to the console.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2. Basic Arithmetic Operations
This program takes two integers as input and performs basic arithmetic operations.
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
printf("Sum: %d\n", num1 + num2);
printf("Difference: %d\n", num1 - num2);
printf("Product: %d\n", num1 * num2);
printf("Quotient: %d\n", num1 / num2);
return 0;
}
3. Using Functions
This program demonstrates the use of a function to calculate the factorial of a number.
#include <stdio.h>
int factorial(int n) {
if (n > 1)
return n * factorial(n - 1);
else
return 1;
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
printf("Factorial of %d = %d\n", number, factorial(number));
return 0;
}
4. Array and Loop
This program shows how to handle arrays and loops in C.
#include <stdio.h>
int main() {
int numbers[5], i, sum = 0;
printf("Enter 5 integers:\n");
for (i = 0; i < 5; i++) {
scanf("%d", &numbers[i]);
}
for (i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum = %d\n", sum);
return 0;
}
5. Structures
This program demonstrates how to use structures to represent data.
#include <stdio.h>
struct Student {
char name[50];
int age;
float grade;
};
int main() {
struct Student student;
printf("Enter name: ");
scanf("%s", student.name);
printf("Enter age: ");
scanf("%d", &student.age);
printf("Enter grade: ");
scanf("%f", &student.grade);
printf("Student Info:\n");
printf("Name: %s\n", student.name);
printf("Age: %d\n", student.age);
printf("Grade: %.2f\n", student.grade);
return 0;
}
6. File I/O
This program demonstrates reading from and writing to a file.
#include <stdio.h>
int main() {
FILE *fptr;
char filename[100], c;
printf("Enter the filename to open for reading: ");
scanf("%s", filename);
// Open the file
fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("Cannot open file %s.\n", filename);
return 1;
}
// Read content from the file
while ((c = fgetc(fptr)) != EOF) {
printf("%c", c);
}
fclose(fptr);
return 0;
}
Feel free to ask if you need explanations for any of these examples or if you want to see more specific C programming concepts!