Beginner’s Guide to Writing Your First C Language Program

Source | Asynchronous | Book Giveaway at the End

1

Calculator: The First Practical Program
On the journey of learning C programming, after understanding the basic concepts and mastering the fundamental syntax, students must be eager to develop a meaningful practical program.
Implementing a calculator in programming is a good choice. It has moderate difficulty, the knowledge required covers the key points of C language, and it has practical utility, making it a suitable hands-on project for C language beginners.
Before proceeding to the next exercise, students should check if they have mastered the following knowledge:

· Data Types: Integer, character, floating-point, enumeration, array, structure, and pointers, etc.;

· Basic Statements: Sequential, loop, branch, jump, etc.;

· Arithmetic Operations: Addition, subtraction, multiplication, division, etc.;

· Input and Output Handling: Formatted input and output of strings, achieving command-line interaction.

If you have mastered the above knowledge points, then we can understand what functions the calculator program has.
Everyone has used a handheld calculator, which has a window to display the input numbers and calculation results, along with several keys containing numbers and operators. We input numbers and operators through the keys to complete calculations.
Using the handheld calculator as a reference, we can design the program as a command-line interaction, receiving keyboard input of numbers and operators, and displaying the results on the screen after calculation. This requires considering how to evaluate arithmetic expressions, validate data, and ensure user-friendly interaction.
Let’s start coding a calculator program.

2

Handwritten Calculator
Before we start writing code, we need to determine the specific functions of the calculator. Jumping straight into the details of the code can lead to realizing that the difficulty is greater than expected. For example, mixed operations in arithmetic require judging the precedence of operators, which is not easy for beginners to implement.
Hence, we can follow the principle of minimum viable product, planning to start with simple implementations while ensuring that the core functions are complete. After completing one version, we can increase complexity and iterate forward.
This ensures that each step yields a usable program and gradually builds confidence. For the first version of the calculator program, we plan the following core functions:

· Only implement arithmetic operations between two numbers;

· The input sequence is [first number] [operator] [second number];

· Use switch-case statements to handle calculation logic;

· Validate invalid numbers and symbols.

According to the above functional planning, students can refer to the following first version of the program:

#include
#include
int main(int argc, char *argv[]) {
double num1, num2, result; // Declare variables
char op;
printf(“Please enter the first number:”);
scanf(“%lf”, &num1);
printf(“Please enter the operator:”);
scanf(” %c”, &op);
printf(“Please enter the second number:”);
scanf(“%lf”, &num2);
switch(op) { // Perform corresponding calculations based on the operator
case ‘+’:
result = num1 + num2;
break;
case ‘-‘:
result = num1 – num2;
break;
case ‘*’:
result = num1 * num2;
break;
case ‘/’:
if(num2 == 0) { // Handle division by zero
printf(“Error: Division by zero\n”);
exit(1);
}
result = num1 / num2;
break;
default: // Handle invalid operators
printf(“Error: %c is an invalid operator\n”, op);
exit(1);
}
printf(“%.2f %c %.2f = %.2f\n”, num1, op, num2, result);
return 0;
}

Scroll up to see the complete code
Reviewing the above code, we define the variables to be calculated as double type, and store the operator as a character type using char. Then we use switch-case statements to identify and process the operator.
We can use the gcc tool in the Linux environment to compile, debug, and test the example code.
Normal operation example:
Beginner's Guide to Writing Your First C Language Program
Error operation example where & is identified as an invalid character:
Beginner's Guide to Writing Your First C Language Program

Error operation example where division by zero is identified:

Beginner's Guide to Writing Your First C Language Program
Thus, a simple calculator program that can perform arithmetic operations between two numbers has been developed. Students will certainly find that this program has many areas for optimization, for example, what happens when the input is not a number but a string? Can the interaction be made more user-friendly?
All areas for improvement are open for students to explore actively. Next, we will challenge a more difficult function, which is how to implement the calculation of complex expressions.

3

Further: Calculation of Complex Expressions
A practical calculator should be able to perform mixed arithmetic operations on multiple numbers based on operator precedence, and also support the handling of parentheses’ precedence.
This requires introducing a data structure—stack, which is characterized by “last in, first out”, allowing only push and pop operations at the top of the stack. We need to create two stacks: one for operands and one for operators. For simplicity, the stack can be implemented using an array.
Once we have the stack, we need to parse the expression, completing the entire expression’s calculation through the push and pop operations of operators and operands. Based on the precedence of operators and parentheses, we traverse the expression from left to right. Below is a pseudocode representation of the evaluation rules:

#define STACK_SIZE 128 double eval_expr(char* expr) { // Define operator stack and operand stack char op_stack[STACK_SIZE]; double num_stack[STACK_SIZE]; For each token in expr: If token is an operand: Parse token as operand and push onto num_stack If token is an operator: While op_stack is not empty and the top operator’s precedence >= token’s precedence: Pop the top operator from op_stack, pop two operands from num_stack to perform the operation, and push the result onto num_stack Push token onto op_stack While op_stack is not empty: Pop the top operator from op_stack, pop two operands from num_stack to perform the operation, and push the result onto num_stack return the top element of num_stack; }

Scroll up to see the complete code

To better understand, let’s observe a mixed operation example: “3 * 4 + (2 – 1) / 5 ^ 2”.

// After pushing “3 * 4” onto the stack, the data in the stack is as follows num_stack = [3, 4]; op_stack = [*]; // When encountering the + sign, its precedence is lower than *, pause pushing, calculate 3 * 4 first, then push the result 12 onto the stack num_stack = [12]; op_stack = [+]; // After pushing “(2-1” onto the stack, the data is as follows num_stack = [12, 2, 1]; op_stack = [+, (, -]; // When encountering the right parenthesis, stop pushing, match the left parenthesis, and pop data from the stack to calculate num_stack = [12, 1]; op_stack = [+]; // After pushing “/5^2” onto the stack, the data is as follows num_stack = [12, 1, 5, 2]; op_stack = [+, /, ^]; // Next, pop the data to calculate, obtaining the result num_stack = [12.04]; op_stack=[];

Scroll up to see the complete code
Students can add functionality based on the complete example completed earlier, rewriting the pseudocode into specific functional implementations. This functionality is more complex, requiring patience, attention to detail, and consideration of error handling and exceptional situations.
Through this topic, students learned how to use C language to build a simple calculator and mastered the basic techniques for handling user input, expression parsing, and evaluation. They can also further expand the calculator’s functionality or engage in other interesting projects to continue developing and challenging themselves.
For those with higher aspirations, a systematic study of “C Primer Plus 6th Edition” is recommended, which contains richer and more detailed C language knowledge, enabling you to implement any desired functionality.
Beginner's Guide to Writing Your First C Language Program

Click below to purchase the book, limited-time discount50% off

4

Understand “C Primer Plus (6th Edition),
Write More Practical Programs for Yourself
“C Primer Plus (6th Edition)” is a classic C language textbook aimed at beginners, authored by Stephen Prata, who teaches astronomy, physics, and programming courses at Marin College in Kentfield, California, and has won widespread acclaim for his unique teaching style.
The book uses clear and easy-to-understand language and practical examples to help students quickly get started with C language programming and understand the basics of computer science. The book has the following main features:
· First, the book starts with the basic concepts of C language, gradually guiding students to master basic knowledge such as syntax, data types, operators, and flow control;
· Second, the explanations and examples in the book are very clear, avoiding excessive jargon and complex syntax. The author uses relatable examples and practical programming problems to help students better understand abstract concepts;

· Finally, the book also provides a wealth of exercises and programming challenges, allowing students to reinforce their knowledge through practice, quickly understand and apply what they have learned, and build a foundational understanding of C language programming.

Beginner's Guide to Writing Your First C Language Program
“C Primer Plus (6th Edition)” organizes content in a chapter-by-chapter manner, making the learning process more systematic and orderly. Each chapter has clearly defined goals and themes, helping students gradually master the core points of C language programming.
Moreover, the book’s content updates are timely, covering some new features and programming techniques of the C99 and C11 standards. The author also introduces the application of C language in practical projects, helping students understand and master commonly used techniques and experiences in real programming.
From the following reader reviews, we can see the weight of this classic book.
Beginner's Guide to Writing Your First C Language Program
To summarize, “C Primer Plus (6th Edition)” helps readers quickly grasp the fundamentals of C language programming through concise language, rich examples, and practical projects.
Students, do you want to write truly valuable programs in C language? Open “C Primer Plus (6th Edition)”; it’s all inside.
Beginner's Guide to Writing Your First C Language Program

Click below to purchase the book, limited-time discount50% off

—END—
Beginner's Guide to Writing Your First C Language Program

Share Your Fun Stories While Writing Programs

Participate in the interaction in the comment area, and click to view and share the activity to your friends circle. We will select 1 reader to receive an e-book version, deadline October 31.

Beginner's Guide to Writing Your First C Language Program

Leave a Comment