Basics of C Programming for Beginners — Introduction(Part-I )
Overview
This tutorial is meant for beginners. You get an overview of the basic concepts of the C programming language
Much of the inspiration for this tutorial comes from online resources.
Table of Contents
- Introduction of programming languages
- Introduction of C
- Advantages of C Language
- C Basic Commands:
- Simple C program(Hello World program)
- Steps to execute C program
- How C source code gets transformed into binary code
- Debugging and testing
- Errors in C
- Conclusion
1. Introduction of programming languages
Programmers, often known as developers, use programming languages as a way of communication with computers. It is a series of instructions used to carry out a certain task written in any language (C, C++, Java, Python, etc.).
Two types of programming languages
- Low Level Languages
- High Level Languages
1. Low Level Languages:
Low level languages are used to write programs that relate to the specific architecture and hardware of a particular type of computer.
They are closer to the native language of a computer (binary), making them harder for programmers to understand.
Low Level Languages are used to developing code for specialist hardware
Examples of low level language:
— Machine Code (machine level language) : In machine level language, computer only understand digital numbers i.e. in the form of 0 and 1. So, instruction given to the computer is in the form binary digit
Disadvantage
a. difficult to implement
b. difficult to understand
c. machine dependent (not portable)
— Assembly Language : Modified version of machine level language
This language contains few recognizable human words but plenty of mnemonic code. word like ADD, SUM, MOV etc.
Still Used for developing code for specialist hardware, such as device drivers. Translator used here is assembler to translate into machine level
Advantage
a. Easy to understand
2. High level language:
When we think about computer programmers, we are probably thinking about people who write programming which is in high-level programming languages. High level languages are written in a form that is close to our human language
- These languages are machine independent, means it is portable
- High level languages are not understood by the machine. So it need to translate by the translator into machine level
- Examples include: C, C++, Java, Pascal, Python, Visual Basic.
Advantages
Easier to modify as it uses English like statements
Easier/faster to write code as it uses English like statements
Easier to debug during development due to English like statements
Portable code — not designed to run on just one type of machine
2. Introduction of C
- C is mid-level programming language (C is considered as a middle-level language because it supports the feature of both low-level and high-level languages)
- C is procedural language (A procedure is known as a function, method, routine, subroutine, etc. A procedural language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.) - C as a structured programming language (Structure means to break a program into parts or blocks so that it may be easy to understand.)
- Developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Lab in 1972
- C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows
- The UNIX OS was totally written in C
Advantages of C Language :
- Simple: easy to learn , offer structural approach to solve problems
- Portable: C programs can be written on one platform and can be executed in the same way on another operating system. C is a machine-independent language.
- Structured programming language: C provides different functions that enable us to break the code into small parts, that is why C programs are easy to understand and modify. Functions also offer
code reusability. - Fast and Efficient: The compilation and execution time of the C language is also fast.
C Basic Commands:
- #include <stdio.h> : It is a preprocessor command which consists of a standard input output header file(stdio.h) before compiling a C program.
- int main() : The main function from where execution of any C program starts.
- { : Indicates the beginning of the main function.
- /*_some_comments_*/ : Any content inside “/* */” will not be used for compilation and execution.
- printf: The output is printed to the console screen using this C
- Getch(): This function is being used to wait for the user’s input.
- return : This C function returns 0 after terminating the C programme or main function.
- } : The function or method block is closed with these curly braces.
- Scanf: The user data is taken from the usual console terminal window using this C function.
- // : These are called single line comments,
Simple C program(Hello World program)
#include <stdio.h>
int main (void)
{
printf("\n Hello World \n");
return 0;
}
- Make sure that you save the file you created with a `.c` extension, or it won’t be a valid C file.
- Header Files in C :
- Header files are external libraries.
- By adding header files to your code, you get additional functionality that you can use in your programs without having to write the code from scratch.
- #include is a preprocessor command that tells the C compiler to include a file.
- The stdio.h header file stands for standard input-output.It contains function definitions for input and output operations, such as functions for gathering user data and printing data to the console
Specifically, it provides functions such as printf() and scanf(). - What is the main() function in C:
- “ int main(void) { …} ’’ is the main function and starting point of every C program.
- It is the first thing that is called when the program is executed.
The int keyword in “int main(void) { .. }” indicates the return value of the main() function.
- void keyword inside the main() function indicates that the function receives no arguments. This is optional, you can also write ‘int main()’ instead of ‘int main(void)’
- Anything inside the curly braces, {}, is considered the body of the function - What Are Comments :
- In C programming, comments are lines of text that get ignored by the compiler.
- Writing comments is a way to provide additional information and describe the logic, purpose, and functionality of your code.
- Comments are also helpful for debugging and troubleshooting.
- Single-line comments :
- Here is the syntax for creating a single-line comment in
“// I am a single-line comment”
- Any text written after the forward slashes and on the same line gets ignored by the compiler.
- Multi-line comments
- As the name suggests, they span multiple lines.
- Multi-line comments start with a forward slash, /, followed by an asterisk, *, and end with an asterisk, followed by a forward slash.
- Here is the syntax for creating a multi-line comment in C:
/* This is
a multi-line
comment
*/
- Comments are also helpful for debugging and troubleshooting. - What is the printf() function in C:
- Inside the function’s body, the line printf(“Hello, World!\n”); prints the text Hello, World! to the console (this text is also known as a string). - What is semicolon ‘;’ in C :
- The semicolon, ;, terminates the statement. All statements need to end with a semicolon in C, as it identifies the end of the statement.
- You can think of a semicolon similar to how a full stop/period ends a sentence.
Steps to execute C program
- Step 1: Creating a C Source File: We need to first create a C program using an editor (TextEditor, eclipse, Visual Studio, Notepad etc) and save the file as filename.c
- Step 2: Compiling using GCC compiler :We use the following command in the terminal for compiling our filename.c source file
“$ gcc filename.c –o filename”
The option -o is used to specify the output file name. If we do not use this option, then an output file with the name a.out is generated. - Step 3: Executing the program
After compilation executable is generated and we run the generated executable using the below command.
“$ ./filename”
How C source code gets transformed into binary code
- Any code you write in the C programming language is called source code.
- Your computer doesn’t understand any of the C statements you have written,so this source code needs to be translated into a different format(Machine code) that the computer can understand
- The compiler will read the program and translate it into machine language-code (also referred to as object code). and make your program suitable for execution.
- The C program goes through the following phases during compilation:
1. Preprocess
2. Compiler
3. Assembler
4. Linker
1. Preprocess:
- This is the first phase through which source code is passed.
- In a C system, a preprocessor program executes automatically before the compiler’s translation phase begins.
- The C preprocessor obeys special commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation.
- The preprocessor scans through the source code to find preprocessor directives, which are any lines that start with a # symbol, such as #include , Macros.
— This phase includes:
— Removal of Comments
— Expansion of Macros
— Expansion of the included files.
— Conditional compilation
— For example, when the preprocessor finds the line #include , the #include tells the preprocessor to include all the code from the stdio.h header file.
— So, it replaces the #include line with the actual contents of the stdio.h file.
— The output of this phase is a modified version of the source code.
2. Compiler
- The next step is to compile sourcecode and produce an; intermediate compiled output file This file is in assembly-level instructions.
- If there are any errors, compilation will fail, and you will need to fix the errors to continue.
3. Assembling
- The next step is the assembly phase, where the assembler converts the generated assembly code statements into machine code instructions.
- The output of this phase is an object file, which contains the machine code instructions.
4. Linking
- The next phase is called linking. C programs typically contain references to functions defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers
working on a particular project.
- Linker does some extra work also, it adds some extra code to our program which is required when the program starts and ends. For example, there is a code that is required for setting up the
environment like passing command line arguments.
Debugging and testing
- We want to test and debug our program to ensure it is working correctly.
- For a simple program like this, we might manually run it and verify that the output is correct.
- For more complex programs, we might use debugging tools like gdb or automated testing frameworks to help identify and fix issues.
Errors in C
An error in the C programming language is a problem that can occur in a program and prevent it from compiling or from working as expected
If an error appears in a program, the program can do one of the following three things:
— The code will not compile,
— The program will stop working during execution,
— The program will generate incorrect output.
There are five different types of errors in C.
— Syntax Error
— Run Time Error
— Logical Error
— Semantic Error
— Linker Error
- Syntax Error:
- When a programmer writes code that does not follow the C syntax rules, it leads to the creation of syntax errors.
- Syntax errors are sometimes also called compilation errors because they are always detected by the compiler. Generally, these errors can be easily identified and rectified by programmers.
a. The most commonly occurring syntax errors in C language are:
b. Missing semi-colon (;)
c. When there are typos
d. Missing keywords or variables
e. Mismatched parentheses and brackets
f. Incorrect data types used for operations in a program, etc.
g. Using undeclared variables
Example Of Syntax Error In C
1.
#include <stdio.h>
void main() {
var = 5; // we did not declare the data type of variable
printf("The variable is: %d", var);
}
output:
error: 'var' undeclared (first use in this function)
2.
#include <stdio.h>
void main() {
for (int i = 0;) { // incorrect syntax of the for loop
printf("Scaler Academy");
}
}
output:
error: expected expression before ')' token
3.
#include <stdio.h>
int main() {
printf("Hello Unstop") // missing semicolone ';'
return 0;
}
Output error:
6 | printf("Hello Unstop")
| ^
| ;
7 |
8 | return 0;
2. Run Time Error:
- Errors that occur during the execution (or running) of a program are called RunTime Errors
- The most common causes of these errors are- coding mistakes, memory corruption, or incorrect system configuration.
- Runtime errors can be a little tricky to identify because the compiler can not detect these errors. They can only be identified once the program is running.
- Runtime errors can occur because of various reasons. Some of the reasons are:
— Mistakes in the Code: Let us say during the execution of a while loop, the programmer forgets to enter a break statement. This will lead the program to run infinite times, hence
resulting in a run time error.
— Memory Leaks: If a programmer creates an array in the heap but forgets to delete the array’s data, the program might start leaking memory, resulting in a run time error.
— Mathematically Incorrect Operations: Dividing a number by zero, or calculating the square root of -1 will also result in a run time error.
— Undefined Variables: If a programmer forgets to define a variable in the code, the program will generate a run time error.
Examples of Run Time Error:
1.
#include <stdio.h>
int main() {
int a = 10, b = 0;
int result = a/b;
printf("Result is: %d \n";, result);
return 0;
}
Output error:
9 | printf("Result is: %d \n";, result); // Print out the value of 'result' variable
| ~ ^
| )
9 | printf("Result is: %d \n";, result); // Print out the value of 'result' variable
| ~^
| |
| int
Explanation:
The error in this code is that a division by zero is attempted, which cannot be done. This causes a run-time error that results in the program crashing
The correct code is:
#include <stdio.h>
int main() {
int a = 10, b = 0;
int result = a/b;
printf("Result is: %d \n";, result);
return 0;
}
Output:
Result is: 1
3. Logical Error :
A logical error in C is an error that occurs when a program produces an incorrect output as a result of incorrect logic or incorrect input.
Example Of Logical Error In C:
#include <stdio.h>
int main() {
int x = 25;
int y = 45;
printf("The sum of x and y : %d",x*y);
return 0;
}
Output error:
The sum of x and y: 1125
Explanation:
The error in the code is that it incorrectly calculates the sum of x and y, instead of multiplying them
The correct code is:
#include <stdio.h>
int main() {
int x = 25;
int y = 45;
printf("The sum of x and y : %d",x+y);
return 0;
}
Output error:
The sum of x and y: 70
4. Semantic Error:
— Errors that occur because the compiler is unable to understand the written code are called Semantic Errors
— A semantic error will be generated if the code makes no sense to the compiler, even though it is syntactically correct.
— Semantic errors are different from syntax errors, as syntax errors signify that the structure of a program is incorrect without considering its meaning. On the other hand, semantic
errors signify the incorrect implementation of a program by considering the meaning of the program.
— The most commonly occurring semantic errors are: use of un-initialized variables, type compatibility, and array index out of bounds.
Example Of Semantic Error In C
#include <stdio.h>
int main() {
int a, b, c;
a * b = c;
// This will generate a semantic error
return 0;
}
Output error:
SemanticError.c:6:11: error: expression is not assignable
a * b = c;
5. Linker Error :
— Linker is a program that takes the object files generated by the compiler and combines them into a single executable file.
— Linker errors are the errors encountered when the executable file of the code can not be generated even though the code gets compiled successfully.
— This error is generated when a different object file is unable to link with the main object file. We can run into a linked error if we have imported an incorrect header file in the
code, we have a wrong function declaration, etc.
Example Of Linker Error In C
#include <stdio.h>
int Main() {
int var = 10;
printf("%d", var);
return 0;
}
Output:
undefined reference to `main'
Explanation:
In the above code, as we wrote Main() instead of main(), the program generated a linker error. This happens because every file in the C language must have a main() function. As in the
above program, we did not have a main() function, the program was unable to run the code, and we got an error. This is one of the most common type of linker error.
The correct code is:
#include <stdio.h>
int Main() {
int var = 10;
printf("%d", var);
return 0;
}
Conclusion
The introduction to the C programming language has been concluded!
I hope this helped you understand some of the foundational concepts you’ll need to begin building simple C programs.
We’ll discuss about variables in the C programming language in the next section.
Next Part : Variables in C (Part-II)
Thanks for reading and happy coding!