Introduction to C Language | Lesson 1: A Beginner’s Guide to C Programming from First Program to Detailed Variable Operations
📚 This article is designed for beginners in C programming, guiding you from scratch to master the fundamentals of C language through detailed code examples and comments!
1.🚀 Why Choose C Language?
C language is known as the “mother of programming languages”. Mastering C is as important as practicing basic skills in martial arts. It not only helps you understand the underlying workings of computers but also serves as a solid foundation for learning other programming languages. Whether you aspire to develop games, work on embedded systems, or engage in system programming, C language is an essential skill!
2.💡 The First C Program: Hello World
(1) The Classic Hello World
#include <stdio.h> // Include standard input-output library
int main() // Main function, entry point of the program
{
printf("Hello micu\n"); // Output text and newline
return 0; // Return 0 indicates normal program termination
}
Program Structure Analysis:
- •
<span>#include <stdio.h></span>: This is a preprocessor directive that tells the compiler to include the standard input-output library - •
<span>int main()</span>: The main function, every C program must have exactly one main function - •
<span>{}</span>: Marks the beginning and end of the function body - •
<span>printf()</span>: A formatted output function used to display content on the screen - •
<span>\n</span>: An escape character that indicates a newline - •
<span>return 0</span>: The function return value, 0 usually indicates successful execution of the program
(2) Tips for Using Comments
#include <stdio.h>
int main()
{
printf("Hello micu\n"); // Single line comment: output greeting
// printf("Hello may\n"); // This line is commented out and will not execute
/*
* Multi-line comment:
* Can write long explanatory text
* Used to explain complex code logic
*/
printf("Hello micu \n Hello may"); // Output: Hello micu \n Hello may
return 0;
}
Best Practices for Comments:
- • Use single-line comments to explain the purpose of single lines of code
- • Use multi-line comments to explain complex algorithms or business logic
- • Comments should be concise and clear, avoiding obvious explanations
3.🏗️ Variables: Data Containers in Programs
(1) Detailed Explanation of Basic Data Types
Integer (int)
int age = 25; // Stores an integer, usually occupies 4 bytes
int temperature = -10; // Can store negative numbers
int count = 0; // Initialized to 0
Float (float)
float height = 175.5f; // Stores decimal numbers, f suffix indicates float type
float weight = 65.8f; // Precision is about 6-7 significant digits
float pi = 3.14159f; // Commonly used in scientific calculations
Double (double)
double precise_pi = 3.141592653589793; // Higher precision decimal
double distance = 384400.0; // Distance from Earth to Moon (in kilometers)
(2) Variable Naming Rules and Best Practices
#include <stdio.h>
int main()
{
// ✅ Correct variable names
int student_age; // Use underscores to separate words
float totalScore; // Camel case naming
int count1, count2; // Can include numbers
char _temp; // Can start with an underscore
// ❌ Incorrect variable name examples (these will cause compilation errors)
// int 2count; // Cannot start with a number
// int int; // Cannot use keywords
// int student-age; // Cannot use hyphens
// int student age; // Cannot include spaces
// 💡 Recommended naming styles
int studentAge = 20; // Camel case (recommended)
float average_score = 85.5f; // Underscore naming style
return 0;
}
Naming Suggestions:
- • Use meaningful variable names, such as
<span>studentAge</span>instead of<span>sa</span> - • Maintain consistency in naming style
- • Constants are usually written in uppercase letters, such as
<span>MAX_SIZE</span>
(3) Variable Declaration and Initialization
#include <stdio.h>
int global_var = 100; // Global variable, visible throughout the program
int main()
{
// Declare and initialize (recommended way)
int local_var = 50;
float grade = 88.5f;
// Declare first, then assign
int number;
number = 42;
// Declare multiple variables at once
int x = 1, y = 2, z = 3;
// Modify variable value
local_var = 60; // Originally 50, now changed to 60
printf("Global variable: %d\n", global_var); // Output: 100
printf("Local variable: %d\n", local_var); // Output: 60
printf("Grade: %.1f\n", grade); // Output: 88.5
return 0;
}
4.🔢 Detailed Explanation of Arithmetic Operators
(1) Basic Operator Practice
#include <stdio.h>
int main()
{
int a = 17, b = 5; // Define two integers
float x = 17.0f, y = 5.0f; // Define two floats
// Integer operations
printf("=== Integer Operations ===\n");
printf("%d + %d = %d\n", a, b, a + b); // 17 + 5 = 22
printf("%d - %d = %d\n", a, b, a - b); // 17 - 5 = 12
printf("%d * %d = %d\n", a, b, a * b); // 17 * 5 = 85
printf("%d / %d = %d\n", a, b, a / b); // 17 / 5 = 3 (integer division)
printf("%d %% %d = %d\n", a, b, a % b); // 17 % 5 = 2 (modulus)
// Floating-point operations
printf("\n=== Floating-point Operations ===\n");
printf("%.1f + %.1f = %.1f\n", x, y, x + y); // 17.0 + 5.0 = 22.0
printf("%.1f / %.1f = %.2f\n", x, y, x / y); // 17.0 / 5.0 = 3.40
// Notes on mixed operations
printf("\n=== Mixed Operations ===\n");
printf("Integer division: %d / %d = %d\n", 7, 3, 7/3); // Result: 2
printf("Floating-point division: %.1f / %.1f = %.2f\n", 7.0f, 3.0f, 7.0f/3.0f); // Result: 2.33
return 0;
}
(2) Operator Precedence
#include <stdio.h>
int main()
{
int result;
// Demonstration of operator precedence
result = 2 + 3 * 4; // Calculate multiplication first: 2 + 12 = 14
printf("2 + 3 * 4 = %d\n", result);
result = (2 + 3) * 4; // Parentheses take precedence: 5 * 4 = 20
printf("(2 + 3) * 4 = %d\n", result);
result = 10 / 3 * 2; // Left to right: 10/3=3, 3*2=6
printf("10 / 3 * 2 = %d\n", result);
return 0;
}
Memory Aid for Precedence: Parentheses first, multiplication and division next, addition and subtraction last, same level from left to right.
5.📝 Detailed Explanation of Input and Output
(1) printf: Powerful Formatted Output
#include <stdio.h>
int main()
{
int age = 20;
float height = 175.8f;
char grade = 'A';
// Basic formatted output
printf("Age: %d years\n", age); // %d: integer
printf("Height: %f cm\n", height); // %f: float
printf("Grade: %c\n", grade); // %c: character
// Control output format
printf("Height: %.1f cm\n", height); // Keep 1 decimal: 175.8
printf("Height: %8.2f cm\n", height); // Total width 8, 2 decimal: 175.80
printf("Age: %5d years\n", age); // Total width 5, right aligned: 20
printf("Age: %-5d years\n", age); // Total width 5, left aligned:20
// Output multiple variables simultaneously
printf("Name: Xiao Ming, Age: %d, Height: %.1f\n", age, height);
return 0;
}
(2) scanf: Getting User Input
#include <stdio.h>
int main()
{
int age;
float weight;
char initial;
// Input single variable
printf("Please enter your age:");
scanf("%d", &age); // Note: the variable must be preceded by & symbol
printf("Please enter your weight (kg):");
scanf("%f", &weight);
printf("Please enter the initial of your name:");
scanf(" %c", &initial); // Note: there is a space before %c to skip newline
// Input multiple variables simultaneously
printf("Please enter height and age (separated by space):");
float height;
int new_age;
scanf("%f %d", &height, &new_age);
// Output results
printf("\n=== Your Information ===\n");
printf("Age: %d years\n", age);
printf("Weight: %.1f kg\n", weight);
printf("Initial of Name: %c\n", initial);
printf("Height: %.1f cm, Age: %d years\n", height, new_age);
return 0;
}
Key Points for Using scanf:
- • The address-of operator & must be added before the variable
- • Use spaces, newlines, or tabs to separate multiple values
- • Adding a space before character input can skip preceding whitespace characters
6.🎯 Comprehensive Practical Project
(1) Project 1: Smart Calculator
#include <stdio.h>
int main()
{
float num1, num2, result;
char operator;
printf("=== Simple Calculator ===\n");
printf("Please enter the first number:");
scanf("%f", &num1);
printf("Please enter the operator (+, -, *, /):");
scanf(" %c", &operator); // Note the space
printf("Please enter the second number:");
scanf("%f", &num2);
// Calculate based on the operator
switch(operator)
{
case '+':
result = num1 + num2;
printf("%.2f + %.2f = %.2f\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2f - %.2f = %.2f\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2f * %.2f = %.2f\n", num1, num2, result);
break;
case '/':
if(num2 != 0) // Check for division by zero error
{
result = num1 / num2;
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
}
else
{
printf("Error: Divisor cannot be zero!\n");
}
break;
default:
printf("Error: Unsupported operator!\n");
}
return 0;
}
(2) Project 2: BMI Health Index Calculator
#include <stdio.h>
int main()
{
float weight, height, bmi;
printf("=== BMI Health Index Calculator ===\n");
printf("Please enter your weight (kg):");
scanf("%f", &weight);
printf("Please enter your height (m):");
scanf("%f", &height);
// Calculate BMI: weight(kg) / height(m)²
the bmi = weight / (height * height);
printf("\n=== Calculation Result ===\n");
printf("Your BMI index is: %.2f\n", bmi);
// Health status judgment
printf("Health Status:");
if(bmi < 18.5)
printf("Underweight\n");
else if(bmi < 24.0)
printf("Normal\n");
else if(bmi < 28.0)
printf("Overweight\n");
else
printf("Obese\n");
printf("\n💡 Health Tips:\n");
printf("- Normal BMI range: 18.5 - 23.9\n");
printf("- It is recommended to maintain a balanced diet and moderate exercise\n");
return 0;
}
7.🔧 Preprocessor Directives: #define Macro Definitions
(1) Basic Macro Definitions
#include <stdio.h>
// Define mathematical constants
#define PI 3.14159f
#define E 2.71828f
// Define program constants
#define MAX_STUDENTS 100
#define PASSING_GRADE 60
// Define string constants
#define SCHOOL_NAME "Tsinghua University"
#define VERSION "v1.0"
int main()
{
float radius = 5.0f;
float area, circumference;
// Use macro-defined constants
area = PI * radius * radius;
circumference = 2 * PI * radius;
printf("=== Circle Calculator %s ===\n", VERSION);
printf("School: %s\n", SCHOOL_NAME);
printf("Radius: %.1f\n", radius);
printf("Area: %.2f\n", area);
printf("Circumference: %.2f\n", circumference);
printf("Max Students: %d\n", MAX_STUDENTS);
printf("Passing Grade: %d\n", PASSING_GRADE);
return 0;
}
(2) Function-like Macro Definitions
#include <stdio.h>
// Define function-like macros
#define SQUARE(x) ((x) * (x)) // Calculate square
#define MAX(a,b) ((a) > (b) ? (a) : (b)) // Find maximum
#define MIN(a,b) ((a) < (b) ? (a) : (b)) // Find minimum
#define ABS(x) ((x) < 0 ? -(x) : (x)) // Find absolute value
int main()
{
int num1 = 5, num2 = -3;
float x = 2.5f;
printf("=== Macro Function Demonstration ===\n");
printf("%d squared = %d\n", num1, SQUARE(num1));
printf("%.1f squared = %.2f\n", x, SQUARE(x));
printf("Maximum of %d and %d = %d\n", num1, num2, MAX(num1, num2));
printf("Absolute value of %d = %d\n", num2, ABS(num2));
return 0;
}
Advantages of Macro Definitions:
- • Improves code readability
- • Facilitates maintenance and modification
- • Text replacement at compile time, high efficiency
8.🏆 Ultimate Challenge: Multifunctional Geometry Calculator
#include <stdio.h>
// Define mathematical constants
#define PI 3.14159f
// Define functional macros
#define SQUARE(x) ((x) * (x))
#define CUBE(x) ((x) * (x) * (x))
int main()
{
int choice;
float length, width, height, radius;
float area, volume, perimeter;
printf("=== 🎯 Multifunctional Geometry Calculator ===\n");
printf("1. Rectangle Area and Perimeter\n");
printf("2. Cuboid Volume\n");
printf("3. Circle Area and Circumference\n");
printf("4. Sphere Volume\n");
printf("Please select a function (1-4):");
scanf("%d", &choice);
switch(choice)
{
case 1: // Rectangle calculation
printf("\n=== Rectangle Calculation ===\n");
printf("Please enter length:");
scanf("%f", &length);
printf("Please enter width:");
scanf("%f", &width);
area = length * width;
perimeter = 2 * (length + width);
printf("Rectangle Area: %.2f\n", area);
printf("Rectangle Perimeter: %.2f\n", perimeter);
break;
case 2: // Cuboid calculation
printf("\n=== Cuboid Calculation ===\n");
printf("Please enter length:");
scanf("%f", &length);
printf("Please enter width:");
scanf("%f", &width);
printf("Please enter height:");
scanf("%f", &height);
volume = length * width * height;
printf("Cuboid Volume: %.2f\n", volume);
break;
case 3: // Circle calculation
printf("\n=== Circle Calculation ===\n");
printf("Please enter radius:");
scanf("%f", &radius);
area = PI * SQUARE(radius); // Use macro function
perimeter = 2 * PI * radius;
printf("Circle Area: %.2f\n", area);
printf("Circle Circumference: %.2f\n", perimeter);
break;
case 4: // Sphere calculation
printf("\n=== Sphere Calculation ===\n");
printf("Please enter radius:");
scanf("%f", &radius);
volume = (4.0f / 3.0f) * PI * CUBE(radius); // V = 4/3 * π * r³
printf("Sphere Volume: %.2f\n", volume);
break;
default:
printf("❌ Invalid choice! Please enter a number between 1-4.\n");
}
printf("\nThank you for using the Geometry Calculator!👋\n");
return 0;
}
9.📚 Extended Knowledge Points
(1) Storage Classes of Variables
#include <stdio.h>
// Global variable (external storage)
int global_count = 0;
int main()
{
// Local variable (automatic storage)
int local_var = 10;
// Static local variable (retains value)
static int static_var = 0;
static_var++;
printf("Global Variable: %d\n", global_count);
printf("Local Variable: %d\n", local_var);
printf("Static Variable: %d\n", static_var);
return 0;
}
(2) Common Programming Errors and Solutions
#include <stdio.h>
int main()
{
int num;
// ❌ Common Error 1: Forgetting to initialize a variable
// printf("%d\n", num); // May output garbage value
// ✅ Correct Approach: Initialize the variable
num = 0; // Or initialize during declaration: int num = 0;
printf("Value after initialization: %d\n", num);
// ❌ Common Error 2: Loss of precision in integer division
int a = 7, b = 3;
printf("Integer Division: %d / %d = %d\n", a, b, a/b); // Output: 2
// ✅ Correct Approach: Use floating-point numbers
printf("Floating-point Division: %d / %d = %.2f\n", a, b, (float)a/b); // Output: 2.33
return 0;
}
10.📝 Summary of This Lesson
(1) Core Knowledge Points
- 1. Program Structure: Header file inclusion, main function, statement composition
- 2. Data Types: int, float, double, char
- 3. Variables: Declaration, initialization, naming rules
- 4. Operators: Arithmetic operators, precedence
- 5. Input and Output: printf formatted output, scanf formatted input
- 6. Preprocessing: Usage of #define macro definitions
(2) Developing Good Programming Habits
- • Give variables meaningful names
- • Add comments promptly
- • Keep code indentation neat
- • Initialize variables to avoid garbage values
- • Check the validity of inputs
(3) Practical Suggestions
- 1. Practice Hands-On: Type out each example yourself
- 2. Experiment: Try modifying parameters to see what happens
- 3. Think Critically: Understand the purpose and principles of each line of code
- 4. Practice Regularly: Complete exercises to reinforce knowledge points
11.🎯 Next Lesson Preview
In the next lesson, we will learn Lesson 2: Detailed Explanation of Expressions and Selection Statements, understanding how to give programs logical judgment and decision-making capabilities. After mastering various expressions and if-else selection statements, your programs will become smarter and more practical!
If this tutorial has helped you, don’t forget to like, bookmark, and share!
If you have any questions, feel free to discuss in the comments section, and let’s improve together!