Getting started with C: Basics of C language

The old-school C language, which was developed in 1972, still shapes a large part of the digital world. Any time that you use a computer, digital camera, or washing machine, you see C in action. This is because C has features of both an assembly language, which is closer to the hardware, and high-level languages such as Java and Python. If you want to find out more about the features and structure that makes C so cool for all generations of programmers, then read on!

Features of C

1. Fast and efficient – C is closer to machine code, which makes it faster. Although other languages such as Java have automated memory management and garbage collection, it has come at the cost of the processing speed. These tasks are handled manually by a C programmer. So, optimized code in C can execute really fast.

2. Procedural language – C solves a problem by breaking it down into subroutines, called functions. Thereafter, it follows an algorithmic approach, where the statements run sequentially. This approach makes the code more organised. 

3. Built-in functions in libraries – C has a huge number of built-in functions in its libraries which makes it easier to code.

4. Portable source code – Once a program is written in C, the source code can run similarly on different machines with almost no modification. However, C programmers need to be cautious and avoid errors that can make the code non-portable.

C programming tools

To get started with programming in C, you will need the following tools and software:

1. Editor – You will first and foremost need a text editor where you can write your code. You can use an inbuilt one such as Notepad to start with or use other commonly used editors such as Vim, Visual Studio Code, Code: :Blocks, and Atom. Regardless of the editor you use, you need to save your source code with .c extension before compiling it. 

2. Preprocessor – Before the actual compilation begins, a preprocessor includes the header files in the code.

3. Compiler – A compiler checks your source code for any errors and converts it into assembly code. While choosing a compiler, make sure that it is as updated as the version of C that you are using.

4. Assembler – An assembler converts the assembly code into object code, which is a combination of binary 0s and 1s. 

5. Linker – The object code is linked with libraries that are necessary to run the application by a linker.

6. IDE – If you want to write and run your program in a graphical user interface, then you can use an Integrated Development Environment (IDE). An IDE consists of an editor, preprocessor, compiler,. assembler , and linker. So, it’s a one stop shop for writing, compiling, and executing programs. For example, Eclipse is a free IDE that you can use for C programming. 

Fundamentals of C language

The building blocks of C language consists of tokens. Anything that you write in C except white space is a token. This includes variables, data types, literals, reserved keywords, functions, punctuation, etc.

Variables, data types, and literals

A variable is the name given to a memory location to store data. You can store different types of data in a variable by using different data types. For example, char is a data type that is used to store single characters such as alphabets, special characters, and single-digit numbers.

char iLoveIcecream = ‘Y’;

Data types in C can be divided into 3 categories:

1. Primary data types – char, int, long,float, double.

2. Derived data types – array, pointer, and string.

3. User-defined data types – structure, union, and enum.

Primary data types store integers and decimal values. They are of 5 types:

i. char – It stores single characters and occupies 1 byte of memory. A series of characters is called a string. This is stored by using char variable name[]. You need to specify the number of characters within the square brackets. For example:

char favouriteIcecream[25] = “Chocolate chip cookie”;

So, this string can only be 25 characters long including the spaces. “Chocolate chip cookie” is a literal, which is a constant value that does not change during the execution of the program.

ii. int – This data type is used to store positive and negative numbers from -3210 to 2768. Depending on the operating system you use, it can take up 2 to 4 bytes. For example:

int orders = 4;

iii. long – It is used to store long integers from -2143648 to 4276878 and occupies 4 to 8 bytes.

iv. float – It stores negative and positive decimal numbers and uses 4 bytes of memory. For example:

float weight = 30.5;

v. double – It stores large decimal numbers that can contain 6 – 15 numbers after the decimal point. It occupies 8 bytes.

Now that we know how to store values, let’s find out how to print them. To print a character, you need to use the “%c” format specifier.

printf (“%c”, iLoveIcecream);

To print string, integer, long, float, and double, you can use “%s”, “%d”, “%ld”, “%f”, and “%ld” format specifiers. For example:

printf (“%s”, favouriteIcecream);

printf (“%d”, orders);

printf (“%f”, weight);

Functions 

A set of code that performs a particular task is called a function in C. There are a number of predefined functions in C such as:

1. main() function: As you might infer from the name, it is the main function and you cannot skip it! This is the starting point for your program. So, when you press run, the code starts executing sequentially from the main function. 

2. printf() function: printf() is used to print an output. This function will print the statements in the same line unless you add a new line character (\n). For example:

printf() without new line character

 

printf() with new line character

3. puts() function: It prints the string and appends a new line character in the end, which takes the cursor to the next line. 

puts() function

Curly braces

A set of statements in C are contained within curly braces. In the above example, the body of the main() function is written inside curly braces.

Operators

Symbols that are used to perform mathematical or logical operations on operands such as variables and literals are called operators. There are different types of operators in C:

1. Arithmetic operators – These are used to perform arithmetic operations such as addition (+), subtraction (-), multiplication (*), division (/), and finding remainder (%). Equations are solved from left to right where multiplication (*), division (/), and modulus (%) are given a higher precedence than addition (+) and subtraction (-).

2. Relational operators – These are used to find out whether a condition is true or false. In C, a true condition is represented by 1 and a false condition is represented by 0. For example:

int a =1;

int b =2;

int c = b>a; 

The ‘c’ will store 1 because ‘b’ is greater than ‘a’ is true.

Other relational operators include greater than or equal to (>=), less than (<), less than or equal to (<=), equal to (==), and not equal to (!=).

3. Logical operators 

i. Logical AND (&&) – It returns 1 if both conditions are true, otherwise it returns 0. For example:

int a = 1;

int b = 4;

int c = 5;

int result = a>b && c>b;

When we run the program, 0 will be assigned to ‘result’ because a is not greater b.

ii. Logical OR (||) – It returns 1 even if one condition is true. Let’s take the same example as above:

int a = 1;

int b = 4;

int c = 5;

int result = a>b || c>b;

When we run the program, 1 will be assigned to ‘result’ because c>b is true.

iii. Logical NOT(!) – It is used to reverse a condition. For example:

int a = 5;

int b = 4;

int r = !(a>b);

The result of a>b is 0. The NOT operator will reverse this and assign 1 to ‘r’.

4. Assignment operators – The simplest assignment operator is ‘=’ which assigns the value from right to left.

int year = 2020;

Other assignment operators such as +-=, -=, *=, /=, and %= can be used to avoid repetition. For example:

int a = a+b;

This statement can also be written as:

int a +=b;

5. Increment and decrement operators – They are used to increase or decrease the value of the variable by 1. This operation can be performed by postfix operators or prefix operators.

In the case of postfix operators, the variable value is first used and then increased or decreased by 1. For example:

int books = 5;

int newBooks = books++;

When this line is executed, the value of newBooks will be 5, and the value of books will increase by 1 and become 6.

While using the prefix operators, the variable value is first increased or decreased by 1 and then used. For example:

int chocolates = 4;

int chocolatesLeft = –chocolates;

On executing this line, the value of chocolates will reduce by 1 and become 3. This value is assigned to chocolatesLeft.

Conditional statements

These are used when the programmer needs to run different statements depending on a condition. For example, the if-else statement.

if (age>=18) 

printf (“You can vote”); //This will be printed if the age is greater than or equal to 18

else

printf ( “You can’t vote”); //This will be printed if the age is less than 18

Other conditional statements include ternary operator, if-else-if ladder, and switch.

The ternary operator uses the following format:

condition? expression 1: expression 2 

If the condition is true, then the first expression will be returned. Otherwise, the second expression is returned. The returned value can be stored in a variable. For example:

int discount = (bill>=500)? 100: 0;

If the bill is greater than or equal to 500, then the discount is 100, else it is 0.

The else-if ladder can be used when we have a number of conditions. For example, let’s write code for checking whether a number is even or odd.

if (number ==1) // if the number is 1

puts (“1 is a special number”);

else if (number!=0 && number%2==0) // if the number is divisible by 2

puts (“This is an even number);

else if (number!=0 && (number%2)!=0) // if the number is not divisible by 2

puts (“This is an odd number);

else

puts (“Please enter another number”);

In the above-mentioned example, the program will execute sequentially. If the first statement is true, it will print the corresponding statement and skip the rest of the ladder.

return statement

At the end of every program body is a return statement, which is used to terminate the program.

Comments

You can leave comments on your program to help the reader understand it better. They also help with documenting your program. So, if you face any error in your application, you can refer to the comments. Single-line comments begin with a two forward slashes (\\) whereas multi-line comments begin with /* and end with */. For example:

/* 

This is my first C program

I am learning how to print statements 

*/

Comments are not scanned by the compiler so you don’t need to follow the C syntax while writing them. 

I know the basics of the C language. How do I write a C program now?

1. Documenting: You can begin a C program by giving details such as author name, date, and objective of the program. You can write these as multi-line comments using /* and */. Although documentation is not necessary, it is considered a good coding practice. 

2. Including links: This is used to include header files that are needed to run the program such as <stdio.h>. This file contains scanf() and printf() functions that are used to take an input from the keyboard and print the output. You can include the header file in a program by using the following syntax:

#include <stdio.h>

3. Declaring functions and variables: While declaring a function in C, you need to write its name, return type, and parameters. For example, the main() function in Java is written as:

int main(int argc, char *argv[]) { 

//function body

}

The ‘int’ is the return type, which generally means that the code needs to terminate with a return 0 statement.

Variables that are declared within each function are called local variables and they can only be used within that particular function. On the other hand, variables declared outside function(s) can be used throughout the program and are called global variables.

4. Taking user input and printing output: As mentioned before, if you want to take an input from the user and display an output, you need to include a stdio header file. This file contains scanf() and printf() functions that are used to take an input from the keyboard and print the output. For example, if you want to calculate how much a customer needs to pay, you will need an integer value. So, you can use the following format:

int orders;

scanf(“%d”, &orders);

 As you can see, “%d” is the format specifier for accepting integer values.The ‘&’ sign will assign the value to the address of ‘orders’. 

5. Executing the program: To begin with, you can run your code on online compilers or you can install a free compiler, and use the command prompt. You can also download an IDE.

Now that we know the steps involved, let’s write our first C program! 

Let’s write a C program to calculate the bill of a laptop after adding GST.

Before you begin writing the program, you will need to install a compiler and an IDE. We have installed Code::Blocks, which is an IDE and MinGW with a GNU GCC compiler. 

Once you have installed Code::Blocks, make sure that the default compiler is GNU GCC compiler. 

When the set up is complete, open Code::Blocks and click on File>Empty file. 

Next, save this file as Bill.c. Make sure you use the ‘.c’ extension. 

While writing the program, the first step should be to come up with an algorithm to solve the problem at hand. In our program where we calculate the GST, we will follow the steps mentioned below.

1. Declare three variables for MRP, GST, and bill.

2. Take MRP as input from the user.

3. Calculate 18% GST on the amount.

4. Calculate the bill by adding the MRP and GST.

5. Print the bill.

Now that we know the steps, let’s write the program.

/*
Author: Internshala
Topic: First program in C
*/

#include <stdio.h>

int main(int argc, char *argv) {

float mrp;
float gst;
float bill;

puts(“Enter MRP”);

scanf(“%f”, &mrp); //taking input

gst = (18*mrp)/100; //calculating GST as 18% of the MRP

bill = mrp+gst;

printf(“The bill is %.1f”, bill); //printing the bill

return 0;
}

Writing your first program in C language

Next, compile the file and check for any errors.

Compiling a C program in Code: :Blocks

Finally, build and run the program. You should see a window to enter your input.

Enter input in a C program

Lastly, press enter to see the output.

Print output in C

That’s it. You have written and executed your first program in C! Yay!

This was a mini guide on how to get started with programming in C. If you enjoyed writing your first C program and want to dive deeper, then check out Internshala Trainings’ Programming with C and C++. You can use coupon code BLOG10 to get a discount of 10%.

Leave a Reply

Your email address will not be published. Required fields are marked *