Key Concepts
- History and importance of C programming
- Applications in system programming, embedded systems, and software development
- Course roadmap and progression
- Live coding environment for hands-on practice
Welcome to the LearnX C Programming course! This course is designed to take you from a complete beginner to a professional-level C programmer. You'll learn C syntax, memory management, advanced functions, file handling, structures, pointers, and real-world project applications.
C is a versatile, high-performance programming language developed in the 1970s. It's widely used for system-level programming, building operating systems, embedded devices, and performance-critical applications. Mastering C gives you a solid foundation for learning modern languages like C++ and Python.
C teaches you how computers manage memory, processes, and low-level operations, which is essential for software engineering, firmware development, and embedded systems. Understanding C also improves debugging skills, logical thinking, and performance optimization.
/* Simple Hello World program in C */
#include <stdio.h>
int main() {
printf("Welcome to LearnX C Programming!\\n");
return 0;
}
This "Hello World" example introduces you to compiling and running C programs, foundational for building more complex applications such as calculators, file parsers, and embedded system utilities.
<stdio.h>C is a powerful general-purpose programming language that has influenced almost every modern programming language. Its simplicity and efficiency make it ideal for low-level system programming and high-performance applications.
C code is compiled, not interpreted, which allows programs to run quickly. It provides precise control over system resources such as memory and CPU, making it a go-to language for system programming, embedded systems, and performance-critical applications.
In C, programs are composed of functions, with main() being the entry point. C uses semicolons to
terminate statements, curly braces for code blocks, and supports variables, loops, conditionals, and
user-defined functions.
#include <stdio.h>
int main() {
int age = 25;
printf("Your age is %d\\n", age);
return 0;
}
Variables like int age are fundamental in programs such as user registration forms, calculators,
or inventory tracking systems.
printf()Before writing your first C program, you need a compiler and a basic understanding of C program structure. Modern editors like VS Code, Code::Blocks, or online compilers like Replit make it easy to start coding.
A typical C program includes preprocessor directives, a main() function, and statements. Programs
are compiled into machine code before execution, ensuring fast performance and efficiency.
#include <stdio.h>
int main() {
printf("C programming setup successful!\\n");
return 0;
}
Setting up your environment is the first step to building real-world applications like file parsers, embedded system firmware, and software utilities.
.c required)C programs follow a structured syntax that is easy to learn. Understanding the rules of syntax is essential to write error-free programs and debug efficiently.
C syntax defines how programs should be written. Each statement ends with a semicolon (;), and
code blocks are enclosed in curly braces ({ }). C is case-sensitive, so Variable and
variable are treated as different identifiers.
#include <stdio.h>
int main() {
int num = 10;
if (num > 5) {
printf("Number is greater than 5\\n");
}
return 0;
}
Proper syntax is critical in projects like calculators, decision-making programs, and any software that depends on conditional logic.
Output in C is primarily handled using the printf() function, which allows you to display text,
variables, and formatted data to the console.
printf() for console outputThe printf() function is versatile. You can combine text and variables using format specifiers.
Escape sequences allow you to format output for readability.
#include <stdio.h>
int main() {
int age = 22;
char grade = 'A';
printf("Age: %d\\n", age);
printf("Grade: %c\\n", grade);
printf("Welcome to LearnX!\\n");
return 0;
}
Console output is used in debugging, creating command-line tools, and displaying program results in real-time.
Comments are notes in your code that the compiler ignores. They are essential for documenting logic, making code readable, and helping with debugging.
///* ... */Proper commenting makes your code easier to maintain. While single-line comments are ideal for brief explanations, multi-line comments are useful for documenting functions, loops, or algorithms.
#include <stdio.h>
int main() {
// This is a single-line comment
printf("Hello, LearnX!\\n");
/*
This is a multi-line comment
explaining the next line of code
*/
printf("C programming is fun!\\n");
return 0;
}
Comments are used in professional projects to explain algorithms, mark TODO items, and document code for future developers or teammates.
Variables are named memory locations used to store data. They allow programs to manipulate and track information dynamically.
Variables must be declared before use. A declaration specifies the type and name of the variable. Proper naming conventions improve readability and prevent conflicts.
#include <stdio.h>
int main() {
int age = 30; // Integer variable
float salary = 55000.50; // Floating point variable
char grade = 'A'; // Character variable
printf("Age: %d\\n", age);
printf("Salary: %.2f\\n", salary);
printf("Grade: %c\\n", grade);
return 0;
}
Variables are used in inventory systems, payroll calculations, game scores, and any program that requires storing and processing data dynamically.
C provides several built-in data types to store different kinds of data. Choosing the correct type ensures efficient memory usage and accurate computations.
Understanding data types is critical for memory management. For example, an int typically uses 4
bytes, while a char uses 1 byte. Using the right type helps prevent overflow and data loss.
#include <stdio.h>
int main() {
int age = 28;
float gpa = 3.75;
double salary = 75000.55;
char grade = 'B';
printf("Age: %d\\n", age);
printf("GPA: %.2f\\n", gpa);
printf("Salary: %.2f\\n", salary);
printf("Grade: %c\\n", grade);
return 0;
}
Data types are used in payroll systems, grading systems, scientific calculations, and any program requiring numeric or textual data storage.
float for decimal numbers, double for higher precisionType conversion in C allows changing a variable from one data type to another. It can be done implicitly (type promotion) or explicitly (type casting).
Implicit conversion happens when C automatically converts smaller types to larger types in expressions, such as int → float. Explicit conversion uses casting operators to manually convert a variable.
#include <stdio.h>
int main() {
int num = 10;
float result;
// Implicit conversion
result = num + 5.5;
printf("Result: %.2f\\n", result);
// Explicit conversion
result = (float)num / 4;
printf("Result after casting: %.2f\\n", result);
return 0;
}
Type conversion is essential in financial applications, scientific calculations, and any program where precise numeric operations are required.
Constants are fixed values in C that do not change during program execution. They are useful for values that remain the same, improving readability and reducing errors.
#define for symbolic constantsconst keyword for typed constantsConstants are often used for values like Pi, maximum array sizes, or configuration parameters that should remain fixed throughout the program.
#include <stdio.h>
#define PI 3.14159
int main() {
const int DAYS_IN_WEEK = 7;
printf("PI: %.2f\\n", PI);
printf("Days in a week: %d\\n", DAYS_IN_WEEK);
return 0;
}
Constants are used in physics calculations (like Pi), software configuration settings, and fixed system limits (like array sizes).
const for typed constants#define for symbolic constantsOperators in C are symbols that perform operations on variables and values. They form the core of all computations and logic in a program.
Operators allow performing calculations, comparisons, and logical decisions. Mastering operators is essential for programming, algorithms, and problem-solving.
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("Sum: %d\\n", a + b);
printf("Difference: %d\\n", a - b);
printf("Product: %d\\n", a * b);
printf("Division: %d\\n", a / b);
printf("Remainder: %d\\n", a % b);
printf("Is a > b? %d\\n", a > b);
printf("Logical AND (a > 5 && b < 10): %d\\n", a > 5 && b < 10);
return 0;
}
Operators are used in calculations, decision-making, and building algorithms like sorting, searching, or financial computations.
= instead of comparison ==C does not have a dedicated boolean type in standard C (pre-C99). Booleans are represented using integers: 0
for false, non-zero for true. C99 introduced _Bool and stdbool.h for clarity.
_Bool and stdbool.hBoolean logic is essential in decision-making, loops, and validating conditions. Using stdbool.h
improves code readability by allowing true and false keywords.
#include <stdio.h>
#include <stdbool.h>
int main() {
bool isLoggedIn = true;
if (isLoggedIn) {
printf("User is logged in\\n");
} else {
printf("User is not logged in\\n");
}
return 0;
}
Booleans are used in login validation, feature flags, game logic, and any conditional checks in programs.
bool for readabilityThe if and else statements are used for conditional execution of code blocks. They
are fundamental for decision-making in C programs.
if statementif-else for alternative pathsif statementsConditional statements allow programs to respond differently based on input or computation. Nested and combined conditions enable more complex decision-making.
#include <stdio.h>
int main() {
int score = 85;
if (score >= 90) {
printf("Grade: A\\n");
} else if (score >= 75) {
printf("Grade: B\\n");
} else if (score >= 60) {
printf("Grade: C\\n");
} else {
printf("Grade: F\\n");
}
return 0;
}
If-else statements are used in grading systems, authentication checks, and conditional workflows in software applications.
The switch statement is used to perform multiple selections based on the value of a variable. It
is an alternative to multiple if-else statements.
switch with case labelsbreak to exit casesdefault caseSwitch statements are ideal for handling menu selections, commands, or any situation with multiple discrete options. Each case must be unique and followed by a break to prevent fall-through.
#include <stdio.h>
int main() {
int day = 3;
switch(day) {
case 1:
printf("Monday\\n");
break;
case 2:
printf("Tuesday\\n");
break;
case 3:
printf("Wednesday\\n");
break;
default:
printf("Other day\\n");
}
return 0;
}
Switch statements are commonly used in menu-driven programs, CLI tools, and embedded device state machines.
break statementdefault to handle unexpected valuesThe while loop allows repeated execution of a block of code as long as a condition is true. It's
ideal when the number of iterations is unknown beforehand.
while(condition) { ... }
#include <stdio.h>
int main() {
int count = 1;
while(count <= 5) {
printf("Count: %d\\n", count);
count++;
}
return 0;
}
While loops are used for reading input until a sentinel value is entered, retrying network requests, or waiting for a condition in embedded systems.
The for loop is used when the number of iterations is known. It combines initialization,
condition, and increment/decrement in one concise statement.
for(init; condition; increment){ ... }
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
printf("Iteration: %d\\n", i);
}
return 0;
}
For loops are widely used in processing arrays, generating reports, and iterating over known ranges like days of the week or menu options.
i, j, index appropriatelyThe break and continue statements control loop execution. break exits
the loop entirely, while continue skips the current iteration.
break exits the loop immediatelycontinue skips the remaining statements in the current iteration
#include <stdio.h>
int main() {
for(int i = 1; i <= 10; i++) {
if(i == 7) break; // exit loop at 7
if(i % 2 == 0) continue; // skip even numbers
printf("Number: %d\\n", i);
}
return 0;
}
Break and continue are used in menu navigation, skipping invalid input, and early exit from loops for performance optimization.
Arrays are collections of elements of the same type stored in contiguous memory locations. They allow efficient storage and access to multiple values using indices.
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for(int i = 0; i < 5; i++) {
printf("Number[%d]: %d\\n", i, numbers[i]);
}
return 0;
}
Arrays are used for storing sensor data, student marks, inventory quantities, and other sequential datasets.
Strings in C are arrays of characters terminated by a null character '\0'. They are used to handle
text and textual data.
char str[50]'\0' marks end of stringscanf and printfstring.h functions for manipulation
#include <stdio.h>
#include <string.h>
int main() {
char name[20] = "LearnX";
printf("Name: %s\\n", name);
printf("Length: %lu\\n", strlen(name));
return 0;
}
Strings are used for usernames, messages, file names, and any text data in software applications.
strncpy and snprintf for safe operationsFunctions in C allow you to divide a program into smaller, reusable blocks of code. They improve readability, modularity, and maintainability.
#include <stdio.h>
void greet() {
printf("Hello from a function!\\n");
}
int main() {
greet();
return 0;
}
Functions are used in all modular software, from calculators to web servers, to encapsulate repeated logic like input validation, calculations, or database queries.
Parameters allow functions to receive data from the caller. They make functions more flexible and reusable.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
printf("Result: %d\\n", result);
return 0;
}
Parameters allow calculator functions, data processors, and configuration handlers to work dynamically with different inputs.
Scope defines where a variable is accessible within a program. Understanding scope prevents naming conflicts and errors.
#include <stdio.h>
int globalVar = 100; // global variable
void func() {
int localVar = 50; // local variable
printf("Local: %d\\n", localVar);
printf("Global: %d\\n", globalVar);
}
int main() {
func();
// printf("%d", localVar); // ERROR: localVar not visible here
return 0;
}
Proper scope management avoids bugs in large programs, especially when multiple developers work on the same codebase.
A function declaration (prototype) informs the compiler about a function’s name, return type, and parameters before its actual definition. It enables calling functions before they are defined.
returnType functionName(parameterTypes);
#include <stdio.h>
// Function declaration
int multiply(int a, int b);
int main() {
int result = multiply(5, 6);
printf("Result: %d\\n", result);
return 0;
}
// Function definition
int multiply(int a, int b) {
return a * b;
}
Function declarations are essential for multi-file programs, libraries, and APIs where definitions are separate from the main code.
This challenge reinforces function usage by combining multiple concepts: parameters, return values, and modular code.
#include <stdio.h>
float celsiusToFahrenheit(float c) {
return (c * 9 / 5) + 32;
}
int main() {
float tempC = 25;
float tempF = celsiusToFahrenheit(tempC);
printf("%.2f°C = %.2f°F\\n", tempC, tempF);
return 0;
}
Functions challenges simulate tasks like unit converters, calculators, and data processing to solidify understanding of modular code.
C provides standard math functions via math.h for calculations like power, square root,
trigonometry, and rounding.
<math.h>sqrt(), pow(), sin(), cos(),
ceil(), floor()double
#include <stdio.h>
#include <math.h>
int main() {
double num = 9.0;
printf("Square root: %.2f\\n", sqrt(num));
printf("Power: %.2f\\n", pow(num, 3));
return 0;
}
Math functions are used in physics simulations, finance calculations, games, and any numeric-heavy program.
math.h-lm when compiling math functionsInline functions suggest the compiler to replace function calls with the function code, improving performance for small functions.
inline
#include <stdio.h>
inline int square(int x) {
return x * x;
}
int main() {
int n = 5;
printf("Square of %d: %d\\n", n, square(n));
return 0;
}
Inline functions are used in performance-critical code, embedded systems, or math-heavy calculations.
Recursion occurs when a function calls itself. It's used to solve problems that can be broken into smaller subproblems, like factorials, Fibonacci numbers, or tree traversals.
#include <stdio.h>
int factorial(int n) {
if(n == 0) return 1; // base case
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d: %d\\n", num, factorial(num));
return 0;
}
Recursion is used in algorithms like sorting (quick sort, merge sort), tree traversal, and backtracking problems.
Function pointers store addresses of functions. They allow dynamic function calls, callbacks, and implementing plugin-like behavior.
returnType (*ptr)(parameterTypes);ptr(args);
#include <stdio.h>
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
int main() {
int (*operation)(int, int);
operation = add;
printf("Add: %d\\n", operation(5, 3));
operation = multiply;
printf("Multiply: %d\\n", operation(5, 3));
return 0;
}
Function pointers are used in event-driven programming, callbacks, plugin architectures, and jump tables.
File handling in C allows programs to store and retrieve data persistently. To create a file, we use the fopen() function with the appropriate mode.
fopen("filename", "mode") to open or create files"w" (write), "r" (read), "a" (append)fclose() to close the fileNULL to handle errors
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if(file == NULL) {
printf("Error creating file.\\n");
return 1;
}
printf("File created successfully.\\n");
fclose(file);
return 0;
}
Creating files is essential for logging, saving user data, configuration files, and exporting results in applications.
fopen() returns NULLfclose()Writing to files stores data for later use. We use fprintf(), fputs(), or fwrite() depending on the data type and format.
fprintf() for formatted textfputs() for simple stringsfwrite() for binary data
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "w");
if(file == NULL) {
printf("Unable to open file.\\n");
return 1;
}
fprintf(file, "Learn C Programming with LearnX!\\n");
fputs("This is a sample line.\\n", file);
printf("Data written to file successfully.\\n");
fclose(file);
return 0;
}
Writing files is crucial for saving logs, reports, configuration files, and persistent application data.
fflush()Reading files retrieves stored data. Functions like fscanf(), fgets(), and fread() are used depending on the data format.
fscanf() for formatted inputfgets() for reading lines safelyfread() for binary dataNULL and EOF to handle end of file or errors
#include <stdio.h>
int main() {
char line[100];
FILE *file = fopen("data.txt", "r");
if(file == NULL) {
printf("Unable to open file.\\n");
return 1;
}
while(fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
return 0;
}
Reading files is critical for configuration loading, log analysis, data import, and report generation.
NULLfgets() instead of gets()Structures in C allow grouping of different data types under a single name. They help organize complex data logically.
struct keyword. operator
#include <stdio.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
struct Student s1 = {"Alice", 20, 88.5};
printf("Name: %s\\nAge: %d\\nMarks: %.2f\\n", s1.name, s1.age, s1.marks);
return 0;
}
Structures are used to represent entities in databases, employee records, or any grouped data in applications.
This challenge reinforces understanding of structures by manipulating multiple instances and performing calculations.
#include <stdio.h>
struct Student {
char name[50];
float marks;
};
int main() {
struct Student s1 = {"Alice", 85.0};
struct Student s2 = {"Bob", 90.0};
float avg = (s1.marks + s2.marks)/2;
printf("Average Marks: %.2f\\n", avg);
return 0;
}
Structures can contain other structures as members. This is called nesting and is useful for modeling hierarchical data.
outer.inner.member
#include <stdio.h>
struct Address {
char city[50];
int zip;
};
struct Student {
char name[50];
struct Address addr;
};
int main() {
struct Student s = {"Alice", {"New York", 10001}};
printf("Name: %s\\nCity: %s\\nZip: %d\\n", s.name, s.addr.city, s.addr.zip);
return 0;
}
Structures can be accessed using pointers, which is more efficient for large structures and dynamic memory usage.
-> with pointers
#include <stdio.h>
struct Student {
char name[50];
int age;
};
int main() {
struct Student s = {"Alice", 20};
struct Student *ptr = &s;
printf("Name: %s\\nAge: %d\\n", ptr->name, ptr->age);
return 0;
}
Unions are similar to structures but share the same memory for all members. Only one member can hold a value at a time.
union keyword
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("Integer: %d\\n", d.i);
d.f = 220.5;
printf("Float: %.2f\\n", d.f);
return 0;
}
The typedef keyword creates an alias for existing data types, making code easier to read and maintain.
#include <stdio.h>
typedef struct {
char name[50];
int age;
} Student;
int main() {
Student s = {"Alice", 20};
printf("Name: %s\\nAge: %d\\n", s.name, s.age);
return 0;
}
Struct padding is added by the compiler to align members for faster access. Awareness of padding is important for memory optimization.
pragma pack or careful ordering of members
#include <stdio.h>
struct PackedStudent {
char a;
int b;
};
int main() {
printf("Size of struct: %zu bytes\\n", sizeof(struct PackedStudent));
return 0;
}
Enumerations (enums) allow defining a set of named integer constants. They improve code readability and maintainability for related values.
enum keyword to define constants
#include <stdio.h>
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main() {
enum Days today = Wednesday;
printf("Day number: %d\\n", today); // 3
return 0;
}
Enums are used for state machines, menu options, error codes, or any set of related constants in programs.
C provides dynamic memory allocation functions for efficient memory usage, especially when the program size or data is not known at compile time.
malloc() to allocate memorycalloc() for zero-initialized memoryrealloc() to resize memory blocksfree() to release allocated memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *arr = (int*)malloc(n * sizeof(int));
if(arr == NULL) {
printf("Memory allocation failed.\\n");
return 1;
}
for(int i=0; i<n; i++) {
arr[i] = i * 10;
printf("%d ", arr[i]);
}
free(arr);
return 0;
}
Dynamic memory is essential in applications like data structures (linked lists, trees), large arrays, and when handling user input of unknown size.
NULLfree()free() for every malloc()/calloc()/realloc()Error handling is crucial in C programming to ensure programs behave predictably under unexpected situations.
#include <stdio.h>
int main() {
int x = 5, y = 0;
if(y == 0) {
printf("Error: Division by zero!\\n");
} else {
printf("Result: %d\\n", x/y);
}
return 0;
}
Essential for financial calculations, file operations, and network applications where incorrect operations can crash programs.
Practice identifying and fixing errors in the following code snippet.
#include <stdio.h>
int main() {
int numbers[5] = {1,2,3,4,5};
for(int i=0; i<6; i++) { // Index out of bounds
printf("%d\\n", numbers[i]);
}
return 0;
}
Debugging involves finding and fixing errors in your code. Common techniques include using print statements, debuggers, and analyzing program flow.
printf() for step-by-step inspectionThe NULL pointer represents a pointer that does not point to any valid memory. Always check pointers before dereferencing.
stdio.h and stdlib.h
#include <stdio.h>
int main() {
int *ptr = NULL;
if(ptr != NULL) {
*ptr = 10;
} else {
printf("Pointer is NULL, cannot dereference.\\n");
}
return 0;
}
Proper error handling prevents crashes and ensures programs can recover from failures. Use checks, return codes, and messages consistently.
fopen() or malloc()errno to detect system errorsValidate user input to avoid unexpected behavior. Check ranges, types, and limits for safety.
scanf() return value to confirm successful input
#include <stdio.h>
int main() {
int age;
printf("Enter age: ");
if(scanf("%d", &age) != 1) {
printf("Invalid input!\\n");
return 1;
}
if(age < 0 || age > 120) {
printf("Age out of range!\\n");
} else {
printf("Valid age: %d\\n", age);
}
return 0;
}
The time.h library provides functions to handle date and time in C programs, useful for timestamps, logging, or scheduling tasks.
time() – get current time in seconds since epochlocaltime() – convert time to local calendar formatstrftime() – format time as a string
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *t = localtime(&now);
printf("Current Date: %02d/%02d/%d\\n", t->tm_mday, t->tm_mon + 1, t->tm_year + 1900);
printf("Current Time: %02d:%02d:%02d\\n", t->tm_hour, t->tm_min, t->tm_sec);
return 0;
}
The rand() function generates pseudo-random numbers. Seed with srand() to vary the sequence each run.
rand() for pseudo-random numberssrand(time(NULL))
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for(int i=0; i<5; i++) {
printf("%d ", rand() % 100); // Random number between 0-99
}
return 0;
}
Macros allow defining constants or inline code with #define. They are preprocessor directives evaluated before compilation.
#include <stdio.h>
#define PI 3.14159
#define SQUARE(x) ((x)*(x))
int main() {
printf("PI: %.2f\\n", PI);
printf("Square of 5: %d\\n", SQUARE(5));
return 0;
}
Organizing code with functions, headers, and modular files improves readability, maintainability, and debugging efficiency.
Storage classes define the scope, lifetime, and visibility of variables in C.
auto – default local variableregister – suggest storing variable in CPU registerstatic – preserves value between function callsextern – declares variable defined in another fileBitwise operators allow manipulation of individual bits in integers, essential for low-level programming and embedded systems.
#include <stdio.h>
int main() {
unsigned int a = 5, b = 9; // 0101 and 1001
printf("a & b = %d\\n", a & b);
printf("a | b = %d\\n", a | b);
printf("a ^ b = %d\\n", a ^ b);
printf("~a = %d\\n", ~a);
return 0;
}
Fixed-width integers from <stdint.h> provide precise control over integer sizes for portability and embedded systems.
int8_t, uint16_t, int32_t, uint64_t
#include <stdio.h>
#include <stdint.h>
int main() {
int8_t small = 127;
uint32_t large = 100000;
printf("Small: %d, Large: %u\\n", small, large);
return 0;
}
This section contains mini-projects that combine multiple C concepts, helping you practice real-world programming skills.
#include <stdio.h>
#include <stdlib.h>
struct Student {
int id;
char name[50];
};
int main() {
FILE *fptr = fopen("students.txt", "w");
if(fptr == NULL) { printf("Error opening file\\n"); return 1; }
struct Student s1 = {1, "Alice"};
struct Student s2 = {2, "Bob"};
fprintf(fptr, "%d %s\\n", s1.id, s1.name);
fprintf(fptr, "%d %s\\n", s2.id, s2.name);
fclose(fptr);
printf("Students saved successfully!\\n");
return 0;
}
This section serves as a quick reference for keywords, standard libraries, and common functions used in C programming.
Practical examples demonstrating key C concepts in real-life scenarios.
#include <stdio.h>
int main() {
char op;
double num1, num2;
printf("Enter operation (+,-,*,/): ");
scanf("%c", &op);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch(op) {
case '+': printf("Result: %.2lf\\n", num1 + num2); break;
case '-': printf("Result: %.2lf\\n", num1 - num2); break;
case '*': printf("Result: %.2lf\\n", num1 * num2); break;
case '/':
if(num2 != 0) printf("Result: %.2lf\\n", num1 / num2);
else printf("Error: Division by zero\\n");
break;
default: printf("Invalid operator\\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct Account {
int id;
double balance;
};
int main() {
struct Account acc = {1001, 5000.0};
double deposit, withdraw;
printf("Deposit amount: "); scanf("%lf", &deposit);
acc.balance += deposit;
printf("Withdraw amount: "); scanf("%lf", &withdraw);
if(withdraw <= acc.balance) acc.balance -= withdraw;
else printf("Insufficient balance\\n");
printf("Current Balance: %.2lf\\n", acc.balance);
return 0;
}