Lab - Getting User Input in C

Lab Overview

In this lab, we will modify our first program and add the ability to get some user input. We will use the C function scanf() to accomplish this. We will also demonstrate how the print the contents of a variable using the printf function.

The general steps we will be following to get our first program running are:

Step 1 - Create the Hello World Program

First clear out and existing code inthe Jdoodle editor by selecting all the code and then press the delete key on your computer.

Once the editor has opened, paste in the following code:

#include <stdio.h>

int main() {

   // printf() displays the string inside quotation
   printf("Hello, World!\n");
   return 0;
}

Step 2 - Compile and Run the Program

When the code is in the editor, execute the program by clicking the
Execute button underneath the coder editor in the Jdoodle Window.

You should see the following output:

Hello,World!

Step 3 - Add the Code to Input the Name

Make the following changes to the code so the program prompts the user to enter their name and then prints it out.

#include <stdio.h>

int main() {
  // 1 create a string
  char myName[30];

  // 2 prompt for user
  printf("Please enter your name: ");

  // 3 read in the name
  scanf("%s", myName);

  // 4 printf() displays the string inside quotation
  printf("!\n");
  printf("Hello, World, my name is %s", myName);
  printf("!\n");

  return 0;
}

Notes the code we added is the following:

Step 4 Rerun the Program

Once you have this code in the Jdoodle editor, run the program by clicking the Execute button. Enter your name in the Stdin Inputs area so the program can pick up the input.

You should see the following output.

Please enter your name: !
Hello, World, my name is Eric!

Summary

We have added some code to our our first example to allows the user to enter their name in the program and the program will add that content to the output. This example shows a simple example of how to add a character variable to the program and how to use scanf() to print out the contents of that variable.

This lab runs on containers, so as soon as you quit your changes will be lost. You can save your C program by copying and pasting from the Jdoodle editor if you would like to save this program to your computer.

File: labc02.md
© Copyright 2023 Destin Learning