top

Search

C Tutorial

.

UpGrad

C Tutorial

C Tutorial

Introduction to C Programming

In an age where the digital world is rapidly evolving, one language has continuously proven its relevance and resilience - C programming. As one of the most powerful and efficient languages, C programming provides a foundation that has shaped the digital realm. Designed for systems programming with an emphasis on low-level access to memory, a simple set of keywords, and a clean style, it has become a popular language for various software development.

In this tutorial, let’s go over some of the most important concepts and ideas in the world of C programming and walk you through some C programs for different themes that you can try out on your own!

Importance of C in modern software development

In the constantly evolving landscape of software development, the importance of C programming remains paramount. Let’s navigate why C continues to be the most popular. 

  1. Performance Efficiency: C is a middle-level language that allows direct hardware manipulation due to its access to low-level infrastructure. This makes it ideal for system programming, where execution speed and minimal memory footprint are critical.

  1. Versatility and Portability: C has wide-ranging applications, from embedded systems to complex scientific computing systems, databases, and even game development. Its portability makes it a universally accepted language that can work on any platform, a significant advantage in cross-platform software development.

  1. Influence on Modern Languages: C has greatly influenced modern programming languages. Languages like C++, C#, and Objective-C are direct descendants of C, while others like Python and JavaScript have features and conventions influenced by C. 

  1. Enduring Demand in the Job Market: Despite the advent of several high-level languages, the demand for proficient C programmers remains high in the job market. 

How to install C 

  1. Download the appropriate version of the GCC (GNU Compiler Collection) for your operating system from the official website (https://gcc.gnu.org/).


  1. Follow the installation instructions provided on the website for your specific operating system.

  2. After installation, open a terminal or command prompt and type "gcc --version" to verify that GCC has been installed correctly.

Setting Up a C Development Environment

  1. Installing a C compiler (such as GCC): Download and install GCC from the official website (https://gcc.gnu.org/), following the installation instructions for your operating system.

  1. Installing an Integrated Development Environment (IDE): Download and install an IDE like Code::Blocks (http://www.codeblocks.org/) or Visual Studio Code (https://code.visualstudio.com/), which supports the C programming.

  1. Creating a new C project: Open the IDE and create a new project, selecting the C programming language as the project type.

Writing Your First C Code 

  1. In your IDE, create a new C file (e.g., main.c).

  1. Type the following code into the new file:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
  1. Save the file and build the project using your IDE's build function (usually accessible through a menu or a shortcut like Ctrl+B or F9).

  2. After successfully building the project, compile and run the program using your IDE's run function (usually accessible through a menu or a shortcut like Ctrl+R or F5).


  3. The output should display "Hello, World!" in the IDE's console or a separate terminal window.

Understanding the Building Blocks: Variables, Data Types, and Operators in C

As we delve into C programming, three fundamental concepts are crucial in constructing and managing our programs: Variables, Data Types, and Operators. 

Variables in C are essentially the named memory locations used to store data within our program. Each variable in C has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable. 

Data Types in C define the type of data that a variable can hold. The primary data types in C include int for integer values, float for floating-point values, double for double precision floating point values, char for character types, and _Bool for boolean types. 

In C, operators are symbols that tell the compiler how to carry out particular logical or mathematical operations. The built-in operators in the C programming language include the following categories:

  • Arithmetic Operators

  • Relational Operators

  • Logical Operators

  • Bitwise Operators

Declaring and initialising variables:

int a = 5;
float b = 3.14;
char c = 'A';

Primitive data types in C (int, float, char, etc.):

int age; // Integer data type
float weight; // Floating-point data type
double balance; // Double-precision floating-point data type
char initial; // Character data type
_Bool is_valid; // Boolean data type

Arithmetic, logical, and bit-wise operators in C:

// Arithmetic operators
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
// Logical operators
_Bool and_result = a && b;
_Bool or_result = a || b;
_Bool not_result = !a;
/_bitwise = a & b;
int or_bit/ Bit-wise operators
int andwise = a | b;
int xor_bitwise = a ^ b;
int not_bitwise = ~a;
int left_shift = a << 1;
int right_shift = a >> 1;

Taking Charge: An Introduction to Control Statements in C

In the journey of understanding C programming, one comes across a powerful set of tools known as control statements. These statements allow us to control the flow of execution in our programs, enabling more complex and dynamic behaviour beyond linear execution. 

There are broadly two control statements in C: decision-making statements and looping statements. 

Decision-making statements execute a particular block of code based on certain conditions. The primary decision-making statements in C are if, if-else, and switch. 

Looping statements are used to repeatedly execute a code block until a certain condition is met. C provides three types of loops: for, while, and do-while. 

Stepping Beyond Basics: Introduction to Arrays and Pointers in C

Understanding arrays and pointers unlocks new possibilities in data manipulation and memory management, offering a more nuanced control over your programs. Let us explore these two concepts.

Arrays in C are data structures that can store fixed-size sequential elements of the same type. An array is used to store a collection of data, but it is often more useful to think of it as a collection of variables of the same type. 

Pointers, on the other hand, are a bit more abstract. A pointer in C is a variable that stores the address of another variable. This allows for dynamic memory allocation, efficient handling of arrays and data structures, and enables the use of certain advanced programming techniques. 

Declaring and initialising arrays:

int numbers[] = {1, 2, 3, 4, 5};
char word[] = "hello";

Array manipulation (sorting, searching, etc.):

// Sorting an array
int temp;
for (int i = 0; i < 5; i++) {
    for (int j = i + 1; j < 5; j++) {
        if (numbers[i] > numbers[j]) {
            temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }
    }
}
// Searching an array for a specific value
int target = 3;
_Bool found = 0;
for (int i = 0; i < 5; i++) {
if (numbers[i] == target) {
found = 1;
printf("Found %d at index %d.\n", target, i);
break;
}
}
if (!found) {
printf("%d not found in the array.\n", target);
}

Pointers and memory allocation in C:

int x = 10;
int *ptr = &x; // Declare a pointer and assign the address of x

printf("Address of x: %p\n", &x);
printf("Value of ptr: %p\n", ptr);
printf("Value of x: %d\n", *ptr); // Dereference the pointer to get the value of x

*ptr = 20; // Change the value of x through the pointer
printf("New value of x: %d\n", x);

Harnessing Modularity: Introduction to Functions and Scope in C

In the realm of C programming, functions and scope are two pivotal concepts that greatly enhance the structure and efficiency of your code. A function in C is a block of code that performs a specific task. By compartmentalising the code into functions, we can create reusable, easy-to-understand, and simple-to-manage modular pieces of code.

A function in C consists of a function declaration, definition, and calling:

  1. Function Declaration: The function declaration or prototype gives the compiler information about the function name, return type and parameters. 

  1. Function Definition: The function definition provides the actual body of the function. It could be considered as the combination of the function declaration and the function body.

  1. Function Calling: To use a function, we need to call or invoke it from another function (usually the main function). 

In conjunction with functions, the concept of scope is also essential. Scope refers to the visibility and lifetime of variables in a program. In C, variables can have a local scope (visible within the function they are declared in) or global scope (visible throughout the program). 

Understanding the scope helps maintain the integrity of the data and prevents potential conflicts in the program.

// Function declaration
int add(int a, int b);

int main() {
    int sum = add(3, 4);
    printf("The sum is: %d\n", sum);
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}

Organising Data: Introduction to Structs and Unions in C

Structs (Structures) in C are used to group different types of data elements (variables) under a single name, offering a way of packaging related data together. For example, a student's record might be a struct containing fields for the name (char array), age (integer), and GPA (float).

Unions in C are similar to structs in that they allow us to store different types of data elements under a single name. However, while a struct allocates separate memory for each member, a union allocates a shared memory space that is used by all its member variables, one at a time. 

Declaring and initialising structs and unions:

struct Point {
    int x;
    int y;
};

union Data {
    int i;
    float f;
    char c;
};

struct Point p1 = {3, 4};
union Data d1;

d1.i = 10;

Struct and union manipulation:

p1.x = 5;
p1.y = 6;
printf("Point coordinates: (%d, %d)\n", p1.x, p1.y);

d1.f = 3.14;
printf("Data as float: %f\n", d1.f);

Communicating with Files: Introduction to File Input/Output in C

File Input/Output operations allow our programs to store information permanently and retrieve it later. This ability to read from and write to files enables programs to interact with data in a persistent and structured manner, greatly expanding their potential use cases.

In C, we perform file operations using a collection of functions provided by the C standard library. These functions allow us to open a file (fopen), close a file (fclose), read from a file (fread, fscanf, fgets), write to a file (fwrite, fprintf, fputs), and more. 

For instance, you might write a program that maintains a log of its operations in a text file or a program that reads a large set of data from a binary file and processes it in some way.

Reading and writing to files:

FILE *file = fopen("example.txt", "w");

if (file != NULL) {
    fprintf(file, "Hello, World!\n");
    fclose(file);
} else {
    printf("Error opening file.\n");
}

file = fopen("example.txt", "r");
if (file != NULL) {
    char line[100];
    fgets(line, sizeof(line), file);
    printf("Read from file: %s", line);
    fclose(file);
} else {
    printf("Error opening file.\n");
}

Creating, opening, and closing files in C:

```c
FILE *file = fopen("newfile.txt", "w"); // Creates a new file or opens an existing one
if (file != NULL) {
    // Perform file operations
    fclose(file); // Close the file after operations are complete
} else {
    printf("Error opening file.\n");
}

Dynamic Memory Allocation in C

Dynamic memory allocation allows programs to obtain memory dynamically during runtime. This ability to control memory allocation and deallocation enables the creation of intricate and flexible data structures and helps in optimising the performance and efficiency of C programs.

C offers several functions for dynamic memory management, including malloc(), calloc(), realloc(), and free(). These functions allow you to allocate memory blocks (malloc and calloc), adjust the size of allocated blocks (realloc), and free up memory when it is no longer needed (free).

For example, when working with data structures that grow and shrink during the execution of a program, such as linked lists, trees, and graphs, dynamic memory allocation becomes an invaluable tool.

Allocating and deallocating memory dynamically:

int *arr = (int *)malloc(5 * sizeof(int));

if (arr != NULL) {
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
    printf("%d\n", arr[i]);
}

free(arr); // Deallocate the memory when no longer needed
} else {
printf("Memory allocation failed.\n");
}

Using malloc(), calloc(), and realloc() functions:

// malloc: allocate memory without initialising it
int *arr1 = (int *)malloc(5 * sizeof(int));

// calloc: allocate memory and initialise it to zero
int *arr2 = (int *)calloc(5, sizeof(int));

// realloc: resize an allocated memory block
int *arr3 = (int *)realloc(arr2, 10 * sizeof(int));

if (arr3 != NULL) {
    arr2 = arr3;
} else {
    printf("Memory reallocation failed.\n");
}

Introduction to C Standard Library Functions

C Standard Library is a collection of header files, each containing a set of functions, macros, and types to be used in our programs. These predefined functions provide a wealth of pre-packaged functionality that can assist us in performing a range of common tasks, from mathematical operations and string manipulation to file handling and memory allocation.

Here are descriptions of some of the most commonly used standard library functions:

  1. printf and scanf: From stdio.h, printf is used for output, and scanf is used for input.

  2. strlen: From string.h, strlen returns the length of a string.

  3. strcpy and strcat: Also from string.h, strcpy copies one string to another, and strcat concatenates two strings.

  4. malloc and free: From stdlib.h, malloc is used to dynamically allocate memory, and free is used to deallocate that memory.

  5. sqrt and pow: From math.h, sqrt computes the square root of a number, and pow raises a number to the power of another.

  6. qsort: From stdlib.h, qsort sorts an array of elements.

Conclusion

In this tutorial, we have covered the basics of C programming, including variables, data types, operators, control statements, arrays, pointers, functions, structs, unions, file I/O, dynamic memory allocation, and standard library functions. With this foundation, you are well-equipped to begin exploring more advanced topics and further develop your skills in C programming!

Further resources for learning C programming:

  1. "C Programming Absolute Beginner's Guide (3rd Edition)" by Greg Perry and Dean Miller

  2. "C Programming for the Absolute Beginner, Second Edition" by Michael Vine

  3. "C Programming Language" by Brian W. Kernighan and Dennis M. Ritchie

  4. Official C language standard documentation (https://www.iso.org/standard/74528.html)

  5. Pursue upGrad’s Master of Science in Computer Science powered by Liverpool John Moores University

FAQs

1. Is C still relevant in modern programming?

Yes, C remains relevant and widely used, particularly for system programming, embedded systems, and hardware programming.

2. What are the main differences between C and C++?

C++ is an extension of C that introduces object-oriented programming features, such as classes, objects, and inheritance. C++ also includes additional libraries and features, such as the Standard Template Library (STL).

3. Can I use C to develop web applications or mobile apps?

While it is possible to use C for web and mobile app development, other languages and frameworks (such as JavaScript, Python, or Java) are generally better suited for these tasks due to their higher-level abstractions and specialised libraries.

Leave a Reply

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