Introduction to C Language for Beginners

Dear students, it’s time for you to prepare some content suitable for teaching new freshmen. I have simplified some of the content here, hoping it will be helpful to everyone. Please correct any mistakes.

What is C Language?

C language is a general-purpose, procedural programming language. It was designed and developed by Dennis Ritchie at Bell Labs in 1972 to port and develop the UNIX operating system.

C language is a widely used computer language, as popular as Java programming language, both of which are extensively used among modern software programmers.

The current latest C language standard is C18, with previous standards including C17, C11, C99, etc.

How to Learn C Language?

There’s no shortcut; you must write code. There’s no easy way to learn programming.

Is There a Quick Way to Learn Programming?

Definitely not. Learning programming is a tedious and often frustrating process, sitting alone in front of a computer screen typing code. If you only have one person around, it can be very lonely. The overall environment is crucial during the learning process; you need to continuously communicate with others about programming issues and help solve others’ problems. Learning without thinking is labor lost; thinking without learning is perilous.

During my university years, my dorm mates were all eager learners. A few of us would study code together, type code, and occasionally go out for a drink—it was quite a pleasant life.

While learning programming, we often had disagreements over some issues, but overall, we were still learning. The atmosphere of learning is very important; if your roommate plays games loudly until dawn, you might need to join some technical communication communities or groups for discussions. Even as a beginner, just participating in discussions can elevate your skills.

We also had classmates from different majors learning programming together, mainly for communication. When encountering problems, don’t try to solve them in isolation.

Are There Key Principles for Learning Programming?

Yes, firstly, you need to know what programming is, what it does, and why you want to learn it. During your programming studies, math and English are essential; math is crucial. Without good mathematical logic, learning code will be difficult. If your English is poor, understanding code and debugging will also be challenging. However, there are exceptions where someone might excel in math but struggle with English, yet can still write code. They might only understand programming keywords and can read English reports or task documents but struggle in English exams.

When learning programming, you must have your own insights and thoughts. Many students like to directly follow tutorials; they might understand the concepts but struggle to write code. This is ineffective. Learning programming in English isn’t scary; in my view, before you start coding, you need to understand what program execution is, the three basic structures, how to design program logic, and then understand concepts like functions, arrays, pointers, and data structures. If you learn object-oriented programming, you must compare it with structures to find similarities and differences.

By this point, you should have your own programming ideas. When faced with programming, think not about how to write the code but about what the logic is and how to design that logic through code.

Programming is about turning mathematical problems into code for processing; if you can convert mathematical formulas into code to solve problems, you are already a budding programmer.

Understanding what programming is—program execution flow—three basic structures—program logic—arrays, functions, pointers—structures—data structures

If you can integrate these concepts, you are already advanced. What you lack is practical experience, using real projects to validate what you have learned. Practice makes perfect; fight many battles to avoid defeat.

Finally, I wish everyone perseverance on the path to becoming a programmer, growing bolder and more ambitious.

What to Use for Writing C Language?

To do a good job, one must first sharpen their tools. Before learning a programming language, you must learn to use programming software. There are many programming software options for C language; here are a few I would like to introduce:

【Aha C】

I used Aha C compiler when I started learning C language, and my introductory book was also “Aha C Language.” This is a children’s programming book, although I was already 20 at the time, it did not affect my enthusiasm for learning.

Introduction to C Language for Beginners

This is the startup interface of the Aha C language compiler.

Introduction to C Language for Beginners

The interface is quite simple and clean. It does not require creating a new project; you can just start coding directly. I also recommend beginners to purchase a copy of “Aha C Language” for a true “zero-based” introduction.

Aha C compiler is suitable for those who have had little contact with computers. For beginners, this is a good starting point. The installation process is very straightforward, so I won’t go into details; just download it and double-click to install.

【VC++6.0】

This was once a legendary tool. I used this compiler in my programming class when I first entered college; it was very practical, but as C language evolved, this compiler gradually fell behind. It is more complex to use than Aha C but is closer to project requirements, requiring you to create new projects and source files each time—quite cumbersome.

Since VC++6.0 is quite old, if you’re interested, you can refer to the following tutorial for download. Doraemon’s Portal:

*http://xinzhi.wenda.so.com/a/1541512838207957

The overall interface looks like this.

Introduction to C Language for Beginners

(PS: Excluding functionality, the color and English made me quite uncomfortable as a beginner QAQ~)

【DEV C++】

This is also at a similar level as VC++, with moderate difficulty. Its functionality is stronger than VC++6.0, making it quite suitable for the current version of C language. Installation tutorial: Doraemon’s Portal:

*https://blog.csdn.net/weixin_38451800/article/details/86367291

The interface looks like this.

Introduction to C Language for Beginners

【VC++2010】

I participated in the computer level exam in my second semester of freshman year, signing up for the second-level C language exam. At that time, the school taught VC++6.0, and I was confident before the exam. However, I suddenly found out that the programming questions used VC++2010, which made me panic. Fortunately, I had played around with Visual Studio before, so I barely passed. One of the most profound lessons I learned from learning programming is to remain humble and patient.

VC++2010 installation: Doraemon’s Portal:

*https://www.cnblogs.com/Mrt-02/archive/2011/07/24/2115617.html

Here’s a picture of it.

Introduction to C Language for Beginners

【Visual Studio】

Visual Studio, abbreviated as VS, has different names depending on the version. I currently use Visual Studio 2019, abbreviated as VS2019. This is a magical tool that most programmers use for coding. VS can not only write C language; as long as your environment is set up correctly, it can run C++, Java, Python, C#, etc. However, installing all of these can take up a lot of space. The first time I installed VS, I installed everything, which took about 60GB on my C drive, which was quite a hassle. After installation, completely uninstalling VS can be troublesome, so everyone should think carefully before proceeding.

You can download Visual Studio from the official website.

【Lastly】

For the programming software mentioned here, you can choose based on your situation. The installation packages involved can be downloaded by yourself or from the resources section of our official website. We will also synchronize the accompanying installation videos soon. Our C language course involves explaining using the Aha C compiler; regardless of the compiler you use, what you need to master in programming is the logic and thinking behind it.

The path is diverse, but they all lead to the same destination. Programming thoughts are interconnected; the difference lies in the code you write and the software you use. Let’s strive together.

My First C Language Program

#include <stdio.h> // Include stdio.h file#include <stdlib.h> // Include stdlib.h fileint main(){    printf("Hello World!\n");   // Display Hello World! on screen and newline        system("pause");    // Wait for any key to continue    return 0;}

This is the code we need to write.

Introduction to C Language for Beginners

We input the code and click the run button; it will prompt you to save the code first, then show a message indicating successful compilation (provided your code has no errors), and then we click the “OK” button that pops up to see the execution effect.

Introduction to C Language for Beginners

The black display below shows the effect of the program execution, displaying Hello World! on the screen, and then prompting to press any key to continue, after which pressing any key will close the program.

【Program Structure】

The first line of the program, #include, is a preprocessor directive that tells the C compiler to include the stdio.h file before actual compilation.

The next line, #include, is another preprocessor directive that tells the C compiler to include the stdlib.h file before actual compilation.

The next line, int main() is the main function where the program starts executing.

The next line printf(…) is another function available in C that will display the message “Hello, World!” on the screen.

The next line system(“pause”) is a Windows system command that waits for input, prompting to press any key to continue.

The next line return 0; terminates the main() function and returns the value 0.

Any program execution starts from main, executing statements in order from top to bottom (sequential structure).

【Framework】

This is the framework format for C language, so all C language code is formatted like this. Faced with a real-world problem, we solve it by writing code to let the computer help us; this is programming!

X and Y’s World—Variables and Constants

We have already encountered the concept of variables and constants through equations in elementary school. In the equation Y=kX+b, Y changes with X, so we call X the independent variable and Y the dependent variable.

When faced with real-world problems, we solve them through programming. But what does it mean to solve problems through programming?

For a problem, there must be input and output. The input is the parameters needed to solve the problem, and the output is the result of processing that problem. For example, if we want to perform a lot of addition, subtraction, multiplication, and division calculations, doing it manually can be quite troublesome. If it’s a few dozen calculations, it’s manageable, but once it exceeds thousands, we need to use a calculator to solve the problem.

We can buy a calculator for calculations, or we can solve it through programming. Here, the problem we need to solve is a large number of calculations, with the input being the data to be calculated and the output being the results of those calculations.

For me currently, I might create an Excel spreadsheet, read files through programming, calculate, and save data to that spreadsheet, etc. (although Excel itself can perform addition, subtraction, multiplication, and division calculations).

In programming, we refer to these input and output elements as variables and constants.

Let’s first discuss the data types of variables and constants.

【Data Types】

Introduction to C Language for Beginners

The data types in C language are far more than these few; in this tutorial, we will progress step by step. Let’s code.

#include <stdio.h> // Import stdio.h#include <stdlib.h> // Import stdlib.hint main(){    int a = 1;  // Define variable a, initialize and assign 1    int b = 1;  // Define variable b, initialize and assign 1    int c = a + b;  // Define variable c, assign the result of a+b to c    printf("%d",c); // Print the value of variable c on the screen        system("pause");    // Wait for input    return 0;   // Return 0}

This program calculates 1+1, where we define a variable a and initialize it to 1, define a variable b and initialize it to 1, define a variable c and assign the result of a+b to c, and finally output c on the screen. a and b are our inputs, while c is our output.

This problem requires calculating the result of 1+1; we input two variables a and b, and we output a result c. This is how we solve a mathematical problem with code. I started learning programming in high school, and at that time, math problems were quite challenging, whether it was functions or calculations. But after learning programming, I could calculate even slightly complex math problems through programming. For function graph problems, many function graphs we couldn’t draw or analyze could be generated through programming by inputting a function and outputting its curve; this is programming.

Let’s do another program to calculate the circumference and area of a circle. In this problem, we need to solve the issue of calculating the circumference and area using the radius of a circle as input.

Let’s review the formulas for the circumference and area of a circle.

Circumference of a circle: l=2Πr

Area of a circle: s=Πr*r

Now let’s write the code.

#include <stdio.h>  // Import stdio.h#include <stdlib.h> // Import stdlib.hint main(){    float PI = 3.1415926;   // Define single-precision float variable PI, initialize to 3.1415926        int r = 5;  // Define integer variable r, initialize to 5    float l = 2*PI*r;   // Define single-precision float variable l, initialize to 2*PI*r    float s = PI*r*r;   // Define single-precision float variable s, initialize to PI*r*r    printf("The circumference of the circle is %f\n",l);  // Output circumference to screen    printf("The area of the circle is %f\n",s);  // Output area to screen        system("pause");    // Wait for input    return 0;   // Return 0}
Introduction to C Language for Beginners

Here’s an introduction to the problem; feel free to refer to the 1+1 problem. You are also welcome to share your insights and opinions in our QQ group.

【Left Value Right Expression Rule】

In our program, regarding variables or constants, we define them according to the “left value right expression” principle.

Left value right expression—left side is the value, right side is the expression.

In programming, our values are stored in variables, so the left side of the equals sign is the variable, used to store the result of the calculation. The calculation of data is an expression, which is on the right side of the equals sign.

int r = 5; // r is a variable, the value; 5 is the expression, a constant

float l = 2*PI*r; // l is a variable, the value; 2*PI*r is the expression, a variable expression.

Variables are left values, so they can appear on the left side of the assignment. Numeric literals are right values, so they cannot be assigned and cannot appear on the left side of the assignment.

【What is a Variable, What is a Constant?】

During program execution, data that can change is called a variable, while data that cannot change is called a constant.

Constants are often used to define fixed quantities, such as the value of Pi; variables are used for temporary storage and calculations during program execution.

【Input and Output】

In a program, interaction between humans and computers (human-computer interaction) is essential. We need to input content from the keyboard while outputting content on the screen. Here, the input and output are the interfaces for human-computer interaction.

At the beginning of our program, we include the files #include and #include.

Include means to include, and here we load the stdio.h and stdlib.h files into the current program. The definitions for int, float, printf, etc., are all within these files.

stdio, Standard Input Output, standardized input and output

stdlib, Standard Library, standard library

In C language, we use scanf to get input from the keyboard; we use printf to display output on the screen.

#include <stdio.h>#include <stdlib.h>int main(){    float PI = 3.1415926;        int r;    printf("Please enter the radius of the circle:");    scanf("%d",&r);        float l = 2*PI*r;    float s = PI*r*r;    printf("The circumference of the circle is %f\n",l);    printf("The area of the circle is %f\n",s);        system("pause");    return 0;}
Introduction to C Language for Beginners
Introduction to C Language for Beginners

Here we can input a number from the keyboard, using scanf, which will be saved to the integer variable r. In the following program, when we call r, it is the number we input, which will be used in calculations. (PS: The content about scanf and printf will be explained in detail in a later chapter.)

【Conclusion】

Informing the computer about real-life problems through code and having it process those problems to provide results is programming.

As programmers, writing code is a process of communicating and informing the computer. Here, the idea of “mathematical formulas being coded” is particularly important.

Three Basic Structures—Sequential and Selective Structures

【Sequential Structure】

In the process of program execution, the program starts from the main function and executes each line of code sequentially. This is the sequential structure.

The logic of the program is strong; it executes strictly and precisely. If the result of the program calculation deviates from your expectations, then there is an issue. Either your prediction was wrong, or your code logic is flawed.

#include <stdio.h>#include <stdlib.h>int main(){        printf("Hello World!\n");        system("pause");    return 0;}

For this program, when executed, it first loads the stdio.h and stdlib.h files, then enters the main function. The first line within the main function is printf(“Hello World!\n”);, which will output “Hello World!” on the screen and add a newline. Then it executes system(“pause”);, which waits for input and prompts to press any key to continue. This is mainly used to stop the program for easier observation of the execution effect. When debugging programs, if you want to see the effect of executing the program line by line, you can use this statement; finally, return 0; signifies the end of the program.

The sequential structure is universal across all programming languages, not just C language.

【Selective Structure】

When solving problems, we often encounter situations that require making choices based on the current situation to determine the next steps.

In programming, this is called a selective structure. There are several types of selective structures.

【Single Branch Selective Structure】

if (condition) {  // execution body}

Let’s look at an example program.

#include <stdio.h>#include <stdlib.h>int main(){    int a;    scanf("%d",&a);        if (a < 10)    {        printf("The number you entered is less than 10\n");    }        system("pause");    return 0;}
Introduction to C Language for Beginners

Here, I entered 5, and through scanf, I assigned 5 to a, so now a=5. Next, we enter the if statement where the condition is a<10. Since a=5, this condition is true, so the content within the curly braces printf(“The number you entered is less than 10\n”); gets executed. What if I entered a number greater than 10? Then the condition would not be met and nothing would be executed.

【Double Branch Selective Structure】

if (condition) {  // execution body 1} else {  // execution body 2}

Let’s look at an example program.

#include <stdio.h>#include <stdlib.h>int main(){    int a;    scanf("%d",&a);        if (a < 10)    {        printf("The number you entered is less than 10!\n");    } else {        printf("The number you entered is greater than 10!\n");    }        system("pause");    return 0;}
Introduction to C Language for Beginners

If the condition is true, one content is executed; if the condition is false, another content is executed. This is the double branch selective structure. You can visualize the logic yourself.

【Multiple Branch Selective Structure】

if (condition1) {  // execution body 1} else if (condition2) {  // execution body 2} else if (condition3) {  // execution body 3} else {  // execution body 4}

Let’s look at an example program.

#include <stdio.h>#include <stdlib.h>int main(){    int a;    scanf("%d",&a);        if (a < 10)    {        printf("The number you entered is less than 10!\n");    } else if (a > 10)    {        printf("The number you entered is greater than 10!\n");    } else {        printf("The number you entered is equal to 10!\n");    }        system("pause");    return 0;}
Introduction to C Language for Beginners

The condition is true, it executes one content; if the condition is false, it executes another content. This is the multiple branch selective structure, and the logic here can be understood by yourself. You are also welcome to discuss in our QQ group.

【Switch Case Selective Structure】

If there are few options to choose from, we can handle it with if-else. But what if there are dozens or hundreds of options? That would be very cumbersome!

In this case, we use the switch…case…default structure.

switch (condition) {  case option1: execution body 1; break; case option2: execution body 2; break; case option3: execution body 3; break; case option4: execution body 4; break; ... default: default execution body;}
printf("hello world!");

Let’s look at an example code.

#include <stdio.h>#include <stdlib.h>int main(){    int a;    printf("Input integer number: ");    scanf("%d",&a);    switch(a)    {        case 1:            printf("Monday\n");            break;        case 2:            printf("Tuesday\n");            break;        case 3:            printf("Wednesday\n");            break;        case 4:            printf("Thursday\n");            break;        case 5:            printf("Friday\n");            break;        case 6:            printf("Saturday\n");            break;        case 7:            printf("Sunday\n");            break;        default: printf("error\n");    }    system("pause");    return 0;}
Introduction to C Language for Beginners

We input a number from the keyboard and store it in variable a, using switch…case to determine the value of a and execute the corresponding statement; the last default executes if none of the cases are met.

When none of the cases fit the switch, don't worry, you still have a default.   When everyone loves you, don't worry, you still have me.                                                           ————Neighbor Wang

【Conclusion】

The three basic structures are the core components of any programming language. We will discuss break in detail later, so stay tuned!

Three Basic Structures—Loop Structures

Why let machines do tasks we can complete ourselves?

Because robots can tirelessly and tirelessly perform boring, repetitive, and dangerous work.

The execution of a program starts from the main function and executes from top to bottom; when encountering conditions, we let it determine and execute a choice; for repetitive tasks, we need to use loops.

There are four types of loop structures. We will demonstrate using the sum from 1 to 99 as an example.

【For Loop】

for (initialization; condition; update) {  // execution body;}
#include <stdio.h>#include <stdlib.h>int main(){    int i;  // Define integer variable i    int sum = 0;    // Define integer variable sum to store the accumulated sum        // For loop to implement accumulation    for (i = 0; i < 100; i++)    {        sum = sum + i;  // Add the value of i to sum    }        printf("Sum = %d\n",sum);   // Output the accumulated result        system("pause");    return 0;}
Introduction to C Language for Beginners

In this example code, we initialize i=0, check if i is less than 100, and after executing the statement, we increment the value of i by 1; in the execution body, we execute sum = sum + i, which adds the value of i to sum. Note that the left value and right value of sum are entirely different.

【While Loop】

initialization; while (condition) {    // execution body    // update}
#include <stdio.h>#include <stdlib.h>int main(){    int i;    int sum = 0;        i = 0;  // initialization    while (i < 100)    // condition    {        sum = sum + i;  // execution body        i++;    // update    }        printf("sum = %d\n",sum);        system("pause");    return 0;}
Introduction to C Language for Beginners

This is a while loop implementation of the sum from 1 to 99. The logic here can be understood by yourself; you can also discuss it in our group.

【Do…While Loop】

initialization do {  execution body; update;} while (condition);
#include <stdio.h>#include <stdlib.h>int main(){    int i;    int sum = 0;        i = 0;    do    {        sum = sum + i;        i++;    } while (i < 100);        printf("sum = %d\n",sum);        system("pause");    return 0;}
printf("hello world!");
Introduction to C Language for Beginners

This is the structure of the do…while loop, implementing the sum from 0 to 99; you can refer to the previous content.

【Similarities and Differences Between Three Loops and the “Railing Problem”】

The for loop, also known as the “counting loop,” allows us to specify how many times to execute the loop.

The while loop, also known as the “conditional loop,” executes the loop content as long as the condition is met; otherwise, it does not execute.

The three basic structures of the program—sequential structure, selective structure, and loop structure—start with the sequential structure. For both loops, initialization is executed first, then the condition is checked, and if the condition is met, the related statements are executed, followed by the update to modify the condition variable. The logic of the two loops is the same, but they differ in syntax and usage.

The do…while loop first executes the initialization, then the required statements, then updates the condition variable, and finally checks the condition.

That is, for and while loops check the condition first and then execute; while do…while loops execute first and then check. What’s the issue here?

When I was in school, I often had to go to the courier station to pick up packages, and each time I would queue up. When it came to my turn, they would first ask if I was xxx, and only then would they give me the package. However, one time, they handed me the package before asking if I was xxx, and I wasn’t; this created an error. In the real world, the courier can take back the wrong package, but in programming, this is a bug!

Understanding the difference between first checking and then executing, versus first executing and then checking, is crucial.

Let’s also discuss the “railing problem.” We like to start counting from 1, but in programming, counting starts from 0.

In the for loop (i=0; i<100; i++), the loop executes 100 times, from 0 to 99, which can confuse beginners. I recommend reading “Programming Pearls,” which explains these details thoroughly.

【Infinite Loop—Goto】

I hesitated for a long time but decided to discuss the infinite loop issue, which I do not recommend experimenting with.

A: execute statement goto A
#include <stdio.h>#include <stdlib.h>int main(){    A: printf("Hello World!\n");        goto A;        system("pause");    return 0;}
Introduction to C Language for Beginners

This loop jumps to the execution point and executes it. The goto loop is an execution construct; we experimented with it in class, using goto to create threads continuously, which eventually caused the computer to crash (in just a few seconds). Understanding goto is enough; do not use it, as using it can lead to needing to reinstall the system; if you encounter issues, you can seek technical support in our QQ group (QAQ).

【Break and Continue】

Break means to break, smash, or shatter.

Continue means to continue.

When we encounter a result in the loop and want to exit the loop early, we can directly use the break statement. For example:

#include <stdio.h>#include <stdlib.h>int main(){    int i;    for(i = 0; i < 10; i++) // loop    {        printf("i = %d\n",i);        if(i == 5)  // if i equals 5        {            break;  // exit the loop early        }    }        system("pause");    return 0;}
printf("hello world!");
Introduction to C Language for Beginners

In this case, the loop only executed 5 times before being broken.

When we want to skip a certain execution and continue the loop, we can use continue. For example:

#include <stdio.h>#include <stdlib.h>int main(){    int i;    for(i = 0; i < 10; i++)    {        if(i == 5)        {            continue;        }        printf("i = %d\n",i);    }        system("pause");    return 0;}
Introduction to C Language for Beginners

When i equals 5, I directly continue to the next iteration of the loop.

In high school during physical education class, when the teacher asked us to run ten laps for warm-up, when I reached the fifth lap, a classmate told me the homeroom teacher was looking for me, so I had to break the loop of running laps. Sometimes the teacher counts the laps, and if I run past without being seen, I could end up only running 9 laps, thinking I was done (QAQ).

Leave a Comment