Create Your First C Program in LabEx

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to write and run your first C program in the LabEx VM. You will start with a simple "Hello, World!" program, then enhance the output with multiple print statements, personalize the output using variables, explore string manipulation in C, and finally, learn how to compile and debug C programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/comments("`Comments`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/BasicsGroup -.-> c/variables("`Variables`") subgraph Lab Skills c/output -.-> lab-438241{{"`Create Your First C Program in LabEx`"}} c/comments -.-> lab-438241{{"`Create Your First C Program in LabEx`"}} c/if_else -.-> lab-438241{{"`Create Your First C Program in LabEx`"}} c/strings -.-> lab-438241{{"`Create Your First C Program in LabEx`"}} c/variables -.-> lab-438241{{"`Create Your First C Program in LabEx`"}} end

Write and Run Your First C Program

In this step, you'll write and run your very first C program in the LabEx VM. We'll guide you through creating a simple "Hello, World!" program that will introduce you to the basic structure of C programming.

Open the WebIDE

  1. Click on the "WebIDE" Tab (Default) in the LabEx interface to open the VS Code-like environment.
  2. In the left sidebar file explorer, right-click and select "New File".
  3. Name the file hello.c. The .c extension indicates this is a C source code file.
WebIDE interface screenshot

If you want to learn more about the WebIDE, check out the WebIDE Guide.

Write Your First C Program

Copy and paste the following code into your hello.c file:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Let's break down this code:

  • #include <stdio.h>: Includes the standard input/output library
  • int main() { ... }: The main function where program execution begins
  • printf("Hello, World!\n");: Prints text to the screen
  • \n: Moves to a new line after printing
  • return 0;: Indicates successful program completion

Compile and Run the Program

Open the terminal in your WebIDE and execute these commands:

gcc hello.c -o hello
./hello
Terminal running C program

Example output:

Hello, World!

Command Explanation

  • gcc hello.c -o hello: Compiles the C source code into an executable named hello
  • ./hello: Runs the compiled program

Enhance Output with Multiple Print Statements

In this step, you'll learn how to enhance your C program by adding multiple print statements. This will help you understand how to display more complex output and use multiple lines of text in your programs.

Modify Your Existing Program

  1. Open the hello.c file in the WebIDE that you created in the previous step.
  2. Replace the contents of the file with the following code:
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    printf("Welcome to C programming!\n");
    printf("This is your first multi-line program.\n");
    return 0;
}

Code Explanation

  • We've added two more printf statements
  • Each printf ends with \n to create a new line
  • Semicolons (;) mark the end of each instruction

Compile and Run the Updated Program

Open the terminal in your WebIDE and execute these commands:

gcc hello.c -o hello
./hello

Example output:

Hello, World!
Welcome to C programming!
This is your first multi-line program.

Key Observations

  • Each printf statement prints on a separate line
  • The \n ensures line breaks between outputs
  • You can add as many printf statements as needed

Troubleshooting Tips:

  • Ensure each line ends with \n
  • Check that each printf statement ends with a semicolon
  • Verify you've saved the file before compiling

Personalize Output Using Variables

In this step, you'll learn how to use variables in C to create more dynamic and personalized output. Variables allow you to store and manipulate data within your program.

Create a New C Program with Variables

  1. Open the WebIDE and create a new file named greeting.c. Or, you can type touch greeting.c in the terminal to create the file.
  2. Enter the following code into the greeting.c file:
#include <stdio.h>

int main() {
    char name[] = "LabEx";
    printf("Hello, %s!\n", name);
    printf("Welcome to C programming, %s!\n", name);
    return 0;
}

Code Explanation

  • char name[] = "LabEx";: Creates a character array (string) variable named name
  • %s is a format specifier that tells printf to insert a string
  • , name after the format string specifies which variable to insert

Compile and Run the Program

Open the terminal in your WebIDE and execute these commands:

gcc greeting.c -o greeting
./greeting

Example output:

Hello, LabEx!
Welcome to C programming, LabEx!

Experimenting with Variables

Try changing the name variable to your own name:

char name[] = "Your Name";

Recompile and run the program to see the personalized output.

Troubleshooting Tips:

  • Ensure the variable is defined before using it in printf
  • Check that you've saved the file before compiling
  • Verify the variable name is spelled correctly

Explore String Manipulation in C

In this step, you'll learn basic string manipulation techniques in C, including string concatenation and using string-related functions from the standard library.

Create a String Manipulation Program

  1. Open the WebIDE and create a new file named strings.c.
  2. Enter the following code:
#include <stdio.h>
#include <string.h>

int main() {
    char first_name[] = "Lab";
    char last_name[] = "Ex";
    char full_name[20];

    // Concatenate strings
    strcpy(full_name, first_name);
    strcat(full_name, " ");
    strcat(full_name, last_name);

    // Print string length and concatenated name
    printf("First name length: %lu\n", strlen(first_name));
    printf("Last name length: %lu\n", strlen(last_name));
    printf("Full name: %s\n", full_name);

    return 0;
}

Code Explanation

  • #include <string.h>: Includes string manipulation functions
  • strcpy(): Copies a string to another
  • strcat(): Concatenates (joins) two strings
  • strlen(): Returns the length of a string
  • %lu: Format specifier for unsigned long (used with string length)

Compile and Run the Program

Open the terminal in your WebIDE and execute these commands:

gcc strings.c -o strings
./strings

Example output:

First name length: 3
Last name length: 2
Full name: Lab Ex

String Manipulation Techniques

Key string operations demonstrated:

  • Creating character arrays
  • Copying strings with strcpy()
  • Joining strings with strcat()
  • Finding string length with strlen()

Troubleshooting Tips:

  • Ensure you have enough space in the destination string
  • Always include <string.h> for string functions
  • Be careful with string buffer sizes to prevent overflow

Compile and Debug C Programs

In this step, you'll learn essential compilation and debugging techniques for C programs, including understanding compiler warnings, using compilation flags, and basic debugging strategies.

Create a Program with Intentional Errors

  1. Open the WebIDE and create a new file named debug.c.
  2. Enter the following code with some intentional errors:
#include <stdio.h>

int main() {
    int x = 10;
    int y = 0;

    // Intentional division by zero
    int result = x / y;

    printf("Result: %d\n", result);

    // Unused variable
    int z = 5;

    return 0;
}

Compile with Warnings

Compile the program with additional warning flags:

gcc -Wall -Wextra debug.c -o debug

Compilation Flags Explanation

  • -Wall: Enables most warning messages
  • -Wextra: Enables even more detailed warnings

Example compiler output:

debug.c: In function ‘main’:
debug.c:13:9: warning: unused variable ‘z’ [-Wunused-variable]
   13 |     int z = 5;
      |         ^

Use GDB for Debugging

Compile with debugging symbols:

gcc -g debug.c -o debug

Start debugging:

gdb ./debug

GDB Commands:

  • run: Start the program
  • break main: Set a breakpoint at the main function
  • print x: Print the value of variable x
  • next: Execute next line
  • quit: Exit GDB
(gdb) run
Starting program: /home/labex/project/debug
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGFPE, Arithmetic exception.
0x0000555555555167 in main () at debug.c:8
8           int result = x / y;
(gdb) print x
$1 = 10
(gdb) break main
Breakpoint 1 at 0x555555555155: file debug.c, line 4.
(gdb) next

Program terminated with signal SIGFPE, Arithmetic exception.
The program no longer exists.
(gdb) quit

GDB shows a division by zero error at line 8. The program crashes due to an arithmetic exception.

Fix the Program

Modify debug.c to handle division safely:

#include <stdio.h>

int main() {
    int x = 10;
    int y = 2;  // Change from 0 to a non-zero value

    if (y != 0) {
        int result = x / y;
        printf("Result: %d\n", result);
    } else {
        printf("Error: Division by zero!\n");
    }

    return 0;
}

Recompile and run:

gcc -Wall -Wextra debug.c -o debug
./debug

Output:

Result: 5

Troubleshooting Tips:

  • Always compile with -Wall -Wextra
  • Pay attention to compiler warnings
  • Use GDB for complex debugging scenarios
  • Add error checking for potential runtime issues

Summary

In this lab, you learned how to write and run your first C program, enhance the output with multiple print statements, personalize the output using variables, explore string manipulation in C, and compile and debug C programs. You gained hands-on experience with the basic structure of C programming, including including libraries, defining the main function, using printf() to display output, and compiling and running the program. You also explored more advanced concepts like using multiple print statements and working with variables and strings.

Other C Tutorials you may like