Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

C Programming Tutorial for Beginners

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

C is a powerful and vеrsatilе programming languagе, useful in developing systеm softwarе and gamеs and еtc. It allows direct access to hardwarе and mеmory, making it ideal for performing critical tasks. C is a foundational programming language for more complex languages like C++, Java, еtc.

 

In this C programming tutorial, you will learn about the history and fеaturеs of C, how to sеt up your development environment and write your first “Hеllo World” program. Wе will also covеr kеy topics likе variablеs, data typеs, control statеmеnts, functions, arrays, pointеrs, еtc. By the еnd of this tutorial, you will have a solid background in understanding a C program.

History of C Programming Language

Dennis Ritchie at Bell Labs developed the C programming language in the early 1970s. This language was an improvement over the B language, which was based on an earlier language called BCPL. This flexibility allowed data handling and enabled efficient manipulation of hardware resources.

 

C quickly became popular since its code could easily be moved to different machines. It was ideal for writing operating systems, including UNIX, among other major systems implemented using C at its inception. With time, various standards, such as ANSI-C and ISO-C, have helped maintain its consistent implementation across platforms.

 

However, C now influences much more than where it started off. Nevertheless, today, it remains one of the basic languages for the computer science education industry, which still uses it for system programming, embedded systems, high-performance applications, etc.

Why to Learn C Programming Language?

Learning C programming offers numerous benefits:

 

  • It helps in learning basic programming concepts such as algorithms, data structures, and memory allocation.
  • Most importantly, it allows direct manipulation of hardware. Hence, it is perfect for system-level programming, including embedded systems.
  • Knowing C helps in learning modern languages like C++, Java, and Python.
  • There is a wide application of it in various areas like embedded systems, etc.

Features of C Programming Language

C is known for its unique features that make it a popular choice among programmers:

 

  • Portable: C codes can run on different machines virtually without modification.
  • Flexible: It supports both high-level and low-level programming languages, hence ideal for various types of projects
  • Rich Library: Contains a standard library with numerous built-in functions for different purposes.
  • Modular: Permit division of code into functions so that they might be reused and maintained easily.
  • Structured language: Enables developers to write efficient and manageable programs by facilitating clear and logical code organisation.
  • Pointers: They have powerful features for memory management, including manipulation.
  • Extensible: New features or functions can be added as required.

Basics of C

This section covers how to configure the development environment for compiling and executing C codes on your machine, writing the first C program, and the code compilation process.

Setup for C Development Environment

The first thing you need to do before you can start programming in C is to set up a development environment.

 

  • Install a Compiler: Download and install a compiler like GCC (GNU Compiler Collection) or Clang. These compilers convert C code into machine language that your computer can execute.
  • Select an IDE or Text Editor: Use Integrated development environments such as Code::Blocks, Eclipse, or Visual Studio or use text editors like VS Code, Sublime Text, etc., where you will write your code.
  • Set Up the Compiler: Adjust your IDE or text editor to make use of the installed compiler. This may involve setting up paths as well as other environment variables.
  • Write and Compile Code: Create a new C file, write some code in it and then compile it to check for errors and create an executable file.

C Hello World Program

Let’s start with a simple “Hello World” program in C.

 

Code:

 

The first line of code imports the ‘studio.h’ header file. When you run the code, it will start execution of the code from the main() method. The printf() function is defined in the ‘stdio.h’ header file, which is used to print the string in the output console.

 

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

 

Output:

Hello World

 

Compiling a C Program: Behind the Scenes

Several operations are performed behind the scenes when you compile a C program.

 

  • Firstly, the preprocessor handles directives that begin with #, such as #include and #define. It processes these commands before actual compilation begins.
  • After that, the assembler converts assembly language code into machine code specific to the given target processor.
  • The next step includes the assembler converting assembly-level language into machine-level language and creating an object file (.o or .obj).
  • Finally, the linker joins the object file with other object files and libraries, resolving references and making an executable file possible.

Comments in ‘C’

Comments in ‘C’ are used to explain any piece of code so that it becomes clearer. These comments do not affect the execution of the program because they are not read by the compiler.

 

You can use below two different ways to add comments in C:

 

  • Single-Line Comments: Single-line comments start with ‘//’. Anything that occurs after // on that line is considered a comment.
  • Multi-Line Comments: This type of comment begins with ‘/*’ and ends with ‘*/’. It can extend to several lines.

 

Code:

 

In the code below, we have added the single-line and multi-line comments.

 

#include <stdio.h> int main() { // This is a single-line comment printf("Hello, World!n"); /* This is a multi-line comment */ /* printf("This code won't be executed.n"); */ return 0; }

 

Output:

Hello World

C Variables and Constants

In C, variables are used to store data that can be changed during program execution while constants hold values that do not change.

Syntax

To define a variable in the ‘C’ language, we need to mention its type, like char, float, int, etc., along with its name.

 

data_type variable_name;

 

To define constant variables, you need to use the const keyword before the data type of the variable.

 

const data_type constant_name = value;

Example

Here, we have defined the ‘age’ integer type variable and the ‘PI’ constant variable of the float data type variable.

 

You can see variable values in the output console.

 

#include <stdio.h> int main() { int age = 25;           // Variable const float PI = 3.14;  // Constant printf("Age: %dn", age); printf("PI: %.2fn", PI); return 0; }

Output

25 3.14

 

Types of Variables

  • Local Variables
  • Global Variables
  • Static Variables
  • Automatic Variables
  • External Variables

 

By understanding how to declare and use variables and constants, you can effectively manage data within your C programs.

C Data Typеs

In C, data types dеfinе thе typе of data a variablе can hold. They determine the memory size, layout, thе rangе of valuеs, and thе sеt of opеrations that can bе pеrformеd on thе data.

Typеs Of Data Typеs

  • Basic Data Typеs: Fundamеntal onеs such as int, char, float, doublе, еtc.
  • Dеrivеd Data Typеs: Thеsе are derived from fundamental types and include arrays, pointеrs, structurеs, and unions.
  • Enumеration Data Typеs: Thеsе are user-defined data typеs that consist of intеgral constants.
  • Void Data Typе: This data type represents the fact that thеrе is no typе at all. It is used in functions that do not have to have any rеturn values.

Basic Data Types

 

Data Type Size (Bytes) Range Format Specifier
int 4 -2,147,483,648 to 2,147,483,647 %d
unsigned int 4 0 to 4,294,967,295 %u
short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 1.2E-38 to 3.4E+38 %f
double 8 1.7E-308 to 1.7E+308 %lf
long double 16 3.4E-4932 to 1.1E+4932 %Lf

 

C Input and Output

When you use C, the standard library functions are used for the input and output operations. Through these functions, you can read data from a keyboard and display data on a screen.

Functions for input

  • scanf(): This is used to take formatted input from the keyboard or standard input.
  • getchar(): This reads one character at a time from the keyboard.

Functions for output

  • printf(): Prints formatted output to standard output or to console(screen).
  • putchar(): Writes one character at a time on the terminal.

Example

Below code uses ‘%d’ format specifier to take numeric input using scanf() function and store it in integer num.

 

The printf() function also uses the ‘%d’ format specifier to print the numeric value in the output console.

#include <stdio.h> int main() { int num; // Input printf("Enter an integer: "); scanf("%d", &num);             // Reading an integer // Output printf("You entered: %dn", num); return 0; }

Output

Integer Value

C Operators

Operators in C are special symbols that perform operations on variables and values. They are essential for manipulating data and variables within a program.

Types of Operators

  • Arithmetic Operators: Perform basic arithmetic operations.
    • + (Addition)
    • – (Subtraction)
    • * (Multiplication)
    • / (Division)
    • % (Modulus)
  • Relational Operators: Compare two values.
    • == (Equal to)
    • != (Not equal to)
    • > (Greater than)
    • < (Less than)
    • >= (Greater than or equal to)
    • <= (Less than or equal to)
  • Logical Operators: Combine or invert logical values.
    • && (Logical AND)
    • || (Logical OR)
    • ! (Logical NOT)
  • Assignment Operators: Assign values to variables.
    • = (Assignment)
    • += (Add and assign)
    • -= (Subtract and assign)
    • *= (Multiply and assign)
    • /= (Divide and assign)
    • %= (Modulus and assign)
  • Increment and Decrement Operators: Add or subtract 1 from the variable value.
    • ++ (Increment)
    • — (Decrement)
  • Bitwise Operators: Perform bit-level operations.
    • & (AND)
    • | (OR)
    • ^ (XOR)
    • ~ (NOT)
    • << (Left shift)
    • >> (Right shift)

Example

In the code below, we use the ‘+’ operator to perform the addition operation and use the ‘++’ operator to perform the increment operation.

 

#include <stdio.h> int main() { int m = 10, n = 5; int result; // Arithmetic Operators result = m + n; printf("m + n = %dn", result); // Increment Operators m++; printf("m after m++ is %dn", m); return 0; }

Output

15 16

C Control Statements Decision-Making

Control statements are decision-making statements that decide whether to execute a set of code or not. They allow users to execute some parts of their codes only when certain conditions are met.

Decision-Making Statements

  • if-else: It enables you to run a block of codes if the condition is true. If false, another block will be executed after this statement.

Example:

In the code below, the integer variable num is declared and initialised with 10. The ‘if’ statement checks whether the value of ‘num’ is greater than 0, and it is. So, it will execute the code of ‘if-blocks’.

 

#include <stdio.h> int main() { int num = 10; if (num > 0) { printf("The number is positive.n"); } else { printf("The number is not positive.n"); } return 0; }

 

Output:

The number is positive.

 

  • switch: The switch statement is used to execute one block of code from multiple options based on the value of a variable.

Loop Statements

  • for loop: The for loop executes the specified code multiple times based on the loop variable initialization and loop termination condition.

 

Example:

In this code, we execute the for loop 5 times and print 0 to 4 values.

#include <stdio.h> int main() { int i; for (i = 0; i < 5; i++) { printf("Value of i: %dn", i); } return 0; }

Output:

0 1 2 3 4
  • while loop: It executes the specified code block until the condition becomes flase.

Syntax

while (condition) {

// Code to be executed

}

 

  • do-while loop: The do-while loop executes the block of code first and then checks whether the condition is valid.

Syntax

do {

// Code to be executed

} while (condition);

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

C Functions

A function in C is a collection of statements grouped together because they perform a specific task. Functions make your program more modular, which improves its organisation.

Types Of Function

  • Library Functions: These functions are predefined by language developers, which we may use directly, such as printf(), scanf(), etc.
  • User-defined functions: These are those types of functions that coders write themselves.

 

Example:

‘int add(int a, int b);’ declares a function named add that takes two integer parameters and returns an integer.

 

‘sum = add(num1, num2);’ calls the add function with num1 and num2 as arguments and stores the result in sum.

 

‘int add(int a, int b) { return a + b; }’ defines the add function that returns the sum of a and b.

#include <stdio.h> // Function declaration int add(int a, int b); int main() { int num1 = 5, num2 = 10, sum; // Function call sum = add(num1, num2); printf("Sum: %dn", sum); return 0; } // Function definition int add(int a, int b) { return a + b; }

Output:

15

C Arrays & Strings

Arrays and strings are important data structures in C that help us manage collections of data.

Arrays

An array is a collection of variables of the same type stored in contiguous memory locations. Mainly, it is used when we need to store multiple values in a single variable.

Example

In this example, we use a for loop to iterate through each element of the array and print it out.

#include <stdio.h> int main() { int numbers[5] = {1, 2, 3, 4, 5};  // Array declaration and initialization for (int i = 0; i < 5; i++) { printf("Element %d: %dn", i, numbers[i]); } return 0; }

Output:

Element 0: 1 Element 1: 2 Element 2: 3 Element 3: 4 Element 4: 5

 

Strings

A string in C is an array of characters terminated by a null character (‘0’). Strings are used to store text.

 

Example:

 

In the code below, we have declared a string with 6 characters, including the null character at the end.

 

#include <stdio.h> int main() { char greeting[6] = "Hello";  // String declaration and initialization printf("Greeting: %sn", greeting); return 0; }

Output:

Greeting: Hello

 

Array and String Operations

 

Arrays and strings support various operations, including:

  • Accessing Elements: Use the index to access individual elements (array[index]).
  • Modifying Elements: Assign new values to specific elements (array[index] = value).
  • String Functions: C provides standard library functions for string manipulation, such as strlen(), strcpy(), and strcmp().

C Pointers

Pointers are similar to the variables, but rather than storing values, it stores the memory address of the variable. They are a powerful feature in C, enabling dynamic memory allocation, efficient array handling, and the creation of complex data structures like linked lists and trees.

 

Example:

In the code below, the ‘ptr’ pointer stores the memory address of the ‘num’ variable.

#include <stdio.h> int main() { int num = 10; int *ptr;         // Pointer declaration ptr = &num;       // Pointer initialization printf("Value of num: %dn", num); printf("Address of num: %pn", &num); printf("Pointer ptr points to: %pn", ptr); printf("Value pointed to by ptr: %dn", *ptr); return 0; }

 

Output:

Value of num: 10 Address of num: 0x7ffc40c59554 Pointer ptr points to: 0x7ffc40c59554 Value pointed to by ptr: 10

C Structures

Structures in C allow you to group different data types together into a single unit. They are used to represent a record or a complex data type that consists of multiple fields.

 

Example:

To define a structure, use the struct keyword followed by the structure name and the definition of its members.

 

You can use the variable name followed by a dot followed by a structure name to access any variable’s value.

#include <stdio.h> // Structure declaration struct Student { int id; char name[50]; float marks; }; int main() { // Structure variable initialization struct Student student1 = {1, "John Doe", 85.5}; // Accessing structure members printf("Student ID: %dn", student1.id); printf("Student Name: %sn", student1.name); printf("Student Marks: %.2fn", student1.marks); return 0; }

Output:

Student ID: 1 Student Name: John Doe Student Marks: 85.50

C Storage Classes

Storage classes in C define the scope, visibility, and lifetime of variables and functions. They help control how and where variables are stored, their default values, and their accessibility throughout the program.

 

Here, we have covered different types of storage classes.

  • Automatic (auto): Local variables declared within a function are automatic by default.
  • Register: Similar to automatic variables but suggest to the compiler to store them in a register for quicker access. Ideal for frequently accessed variables.
  • Static: Variables retain their value between function calls and are not re-initialized.
  • External (extern): Used to declare variables that are defined in other files or outside the current scope. Facilitates sharing variables across multiple files.

C Memory Management

Memory management in C is crucial for efficient program execution. It involves the allocation and deallocation of memory during the program’s runtime.

Dynamic Memory Allocation

Dynamic memory allocation allows you to allocate memory at runtime using four standard library functions:

  1. malloc(): It allocates a specified number of bytes and returns a pointer to the first byte.
  2. calloc(): Allocates memory for an array of elements, initialises all bytes to zero, and returns a pointer to the first byte.
  3. realloc(): Adjusts the size of the previously allocated memory block.
  4. free(): Deallocates previously allocated memory, making it available for future use.

C Preprocessor

The C preprocessor processes your source code before compilation, performing text substitution and file inclusion to make the code easier to manage.

 

Here, we have covered some C preprocessor directives.

 

  • #include: Includes the contents of a specified file into the program.
  • #define: Defines macros or constants.
  • #undef: Undefines a previously defined macro.
  • #ifdef / #ifndef: Checks if a macro is defined or not for conditional compilation.
  • #if / #else / #elif / #endif: Evaluates conditions for complex conditional compilation.
  • #error: Generates an error message during compilation.
  • #pragma: Provides special instructions to the compiler.

C File Handling

File handling in C allows you to store data permanently by reading from and writing to files. This is essential for data persistence beyond program execution.

Key File Handling Functions

 

Function Description
fopen() To open a file and get a file pointer.
fclose() Closes an opened file.
fread() Reads data from a file.
fwrite() Writes data to a file.
fprintf() Writes formatted output to a file.
fscanf() Reads formatted input from a file.
fgets() Reads a string from a file.
fputs() Writes a string to a file.

 

File Opening Modes

 

The file opening modes allow you to define how you do for what purpose you want to open the file.

 

Mode Description
r Open for reading.
w Open for writing (creates a new file or truncates an existing file).
a Open for appending.
r+ Open for reading and writing.
w+ Open for reading and writing (creates a new file or truncates an existing file).
a+ Open for reading and appending.

 

Pros and Cons of C Programming Language

 

We have covered the pros and cons of C programming Language in the table below.

 

Pros Cons
C programs are fast and use minimal resources. Requires explicit handling of memory allocation and deallocation.
Provides low-level access to memory and hardware. It Can be difficult to master C due to pointers and manual memory management.
Extensive standard library for various functions. String handling requires additional code.
Understanding C helps in learning other languages like C++, Java, and Python. Easier to make mistakes such as buffer overflows and memory leaks.
Supports modular programming through functions and libraries. Basic error handling mechanisms.

 

Applications of C Language

 

C language is adaptive to numerous domains due to its efficiency, control, and portability. Below are some main use cases:

 

  • Operating Systems: Numerous operating systems such as UNIX and LINUX have coded in C because it allows low-level access to hardware, and has memory management capabilities.
  • Embedded Systems: In this regard, the C language is chosen for developing firmware for real-time operating systems (RTOS) or microcontrollers, which highlights its effectiveness.
  • System Programming: For system software like device drivers, operating system kernels, system utilities, etc., where hardware needs to be manipulated directly, you can use C.
  • Game Development: Certain parts of games like graphics rendering engines and physics calculation are done in C for better performance.
  • Compiler Development: It generates efficient machine code therefore, many compilers and interpreters for other programming languages are built on top of it.
  • Network Programming: It speedily develops network protocols, communication systems and network utilities while taking advantage of its low–level capacities.
  • Database Systems: Many database management systems (DBMS) are developed using the ‘C’ language in order to ensure that they perform well and utilise memory efficiently.
  • Scientific Computing: The speed and accuracy with which C executes programs makes it a favourite tool when running simulations or data analysis on a computer

Conclusion

Learning the C programming language is an invaluable asset for programmers or computer science students. Its efficiency, and low-level abilities in development of other languages make it an essential skill. By understanding C, you gain insight into how software interacts with hardware, which is crucial for developing high-performance applications.

 

From its historical background to practical examples, including advanced topics, this C programming tutorial has provided a comprehensive overview of C. Now, you can explore more about each concept of C programming language using the different tutorials. Regardless of whether one’s interest lies in embedded systems development, game development, or even system programming, one should learn C programming.

 

 

FAQs
Start with the basics, such as variables, data types, and control structures. Write simple programmes first, then proceed to advanced topics, such as pointers and memory management. To improve your skills, you can use online tutorials, books, and coding exercises.
Functions such as printf, which display a number, would have %d denoting an integer value.
#include <stdio.h> stands for ‘standard input output’ library, which contains functions like printf and scanf.
scanf reads formatted input from the standard input (keyboard).
A loop in C refers to a repeating structure that allows a programmer to execute code repeatedly while specified conditions remain true. Common loops are for, while, do-while loops.
brochureimg

The DevOps Playbook

Simplify deployment with Docker containers.

Streamline development with modern practices.

Enhance efficiency with automated workflows.

left dot patternright dot pattern

Programs tailored for your success

Popular

Data Science

Technology

Finance

Management

Future Tech

Upskill with expert articles
View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved