Thursday, 29 November 2018

How to Learn C Programming With This Beginner Project

learn-c

Learning to program is a cumulative experience. Alongside learning the syntax of your chosen language, you must also learn the general principles that all programming languages use.

Understanding and learning C programming can be daunting, but there are a few basic ideas worth familiarizing yourself with when starting. A simple project is a great way to learn the fundamentals of C.

So where should you start? By saying hello!

1. Hello, World!

The first part of almost every coding course is the hello world program. Going over it in detail highlights some of the ways C differs from other languages. To begin with, open up a text editor or IDE of your choice, and enter this code:

#include <stdio.h>
/* this is a Hello World script in C */
int main(void)
{
  printf("Hello, World! \n");
  return 0;
}

This short piece of code prints to the console before ending the program. Save it somewhere easy to remember as hello.c. Now you need to compile and build your file.

Making It Run

Usually, you won’t need to install any additional software on your computer to run C scripts. Open up a terminal window (or command prompt if you are running Windows) and navigate to the directory you saved your script in.

The way you compile and run your file varies from system to system:

  • Windows Users: Make your file executable by typing cl hello.c and pressing enter. This will create hello.exe in the same folder, which you can run by typing hello.
  • Linux and macOS users: Type gcc -o hello hello.c and press enter to make it executable, and run it by typing ./hello.

Whichever method you use, running your script should show you this:

Output showing the results of a Hello World! sketch in C

If it didn’t work on Windows, make sure you run the command prompt in administrator mode. For macOS, you may need to install Xcode from the App store and follow these steps from StackOverflow.

Now, let’s look at the program line by line to see how it works, and improve it!

Under the Hood: Understanding the C Language

Preprocessors

The script you just created starts with the inclusion of a library.

#include <stdio.h>

The first line in the script is called a preprocessor. This is carried out before the rest of the script is compiled. In this case, it tells the script to use the stdio.h library. There are a huge number of preprocessors available for different tasks.

Stdio.h takes care of getting input from the program’s user, and outputting information back to them.

/* this is a Hello World script in C */

This next line is a comment. The slash and star tell the compiler to ignore everything between it and the closing star and slash. While this may seem pointless, being able to leave yourself and others clear notes about what your code does is an essential habit to get into.

The Main Function

int main(void)

Every C program must have a main function. Main is a function which returns an integer, denoted by int. The brackets after main are for its arguments, though in this case, it takes none, which is why you use the void keyword.

You write the code to be carried out between two curly braces.

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

Inside the function, you call the printf() function. Just like main(), printf is a function. The difference is, printf is a function in the stdio library you included at the start.

Printf prints anything in the brackets, between the quotation marks, to the console. The \n is an escape sequence called newline, telling the compiler to skip to the next line in the console before continuing.

Note that these lines end in semicolons, which the compiler uses to split one task from the next. Pay close attention to these semicolons—missing them out is the number one cause of things not going right!

Finally, the function returns with the number 0, ending the program. The main() function must always return an integer, and return = 0; signals to the computer that the process was successful.

Understanding each step of this script is a great start in learning both C syntax, and how the language works.

2. Creating Your Own C Functions

You can create your own custom functions in C. Instead of printing Hello World in the main function, create a new function to do it for you.

void print_for_me()
{
  printf("Hello, World! \n");
}

Let’s break this down.

void is a keyword meaning the following function will not return anything.

print_for_me() is the name of the function, and the empty brackets show it does not require arguments to work. An argument is any piece of information to pass on to a function to make it work—later you will be adding an argument of your own to change the output! Note: This is not the same as the main() function above which used void. That function cannot take arguments, while this one can (but in this case, doesn’t have to).

The code block should be familiar to you—it’s just the print statement from the original main function.

Now, you can call this function from your main function.

int main(void)
{
  print_for_me();
  print_for_me();
  return 0;
}

You can see here a benefit of using your own function. Rather than typing printf(“Hello, World! \n”) each time, you can call the function twice.

Right now this might not seem so important, but if your print_for_me function contained a lot of lines of code, being able to call it so easily is a great time saver!

Hello world outputting twice through multiple function calls

This is a fundamental idea of programming you will come across throughout your education. Write your own function once, rather than write the same big chunks of code over and over.

3. Using Function Prototypes in C

Prototypes are one of the major ways beginner C differs from other languages. In short, a prototype is a like a preview of a function defined later. If you write the print_for_me() function after the main function, you may get a warning when compiling:

Composite Image showing code with no prototype and the warning the c compiler gives

The warning message is telling you that the compiler ran into the print_for_me function before it was declared, so it couldn’t be sure that it would work correctly when the program runs.

The code would still work, but the warning can be avoided altogether by using a prototype.

#include <stdio.h>

void print_for_me();

int main(void)
{
  print_for_me();
  print_for_me();
  return 0;
}

void print_for_me()
{
  printf("Hello, World! \n");
}

By looking at the full program you can see the prototype for print_for_me() exists at the start of the program, but contains nothing. The prototype function shows the compiler how the function should look, and whether it requires arguments or not.

This means that when you call it in the main function, the compiler knows if it is being called correctly and can throw a warning or error if it is needed. This may be something that seems strange now, but knowing about them now will help in future.

Hello world outputting twice through multiple function calls

This program still works without a prototype, but they are good practice to use. The output still looks the same for now, lets change it to make it more personal!

4. Passing Arguments to C Functions

Changing the Script

For this final step, you will ask for the user’s name, and record their input. Then you’ll use it in the function you created before. In C, words are not known as strings like in other programming languages.

Instead, they are an array of single characters. The symbol for an array is [] and the keyword is char. Begin by updating your prototype function at the start of your script:

#include <stdio.h>

void print_for_me(char name[]);

Now, the compiler will know that the function later in the script takes an array of characters called name. So far, this character doesn’t exist. Update your main function to create it, and use it to store the user input:

int main(void)
{
  char name[20];
  printf("Enter name: ");
  scanf("%s", name);

  print_for_me(name);
  print_for_me("Everyone!");
  return 0;
}

The first line in main creates a character array with 20 possible spaces called name. Next, the user is prompted to enter their name using printf. The next line uses a new function called scanf which takes the next word the user types.

The “%s” tells the function that it should store the data as a string, and call it name.

Modifying the Function

Now when you call print_for_me, you can include name in the brackets. On the next line, you will see you can also pass other characters as long as they are between quotation marks. Both times, what is in the brackets gets passed to the print_for_me function.

Modify that now to use the new information you are giving it:

void print_for_me(char name[])
{
  printf("Hello, ");
  puts(name);
}

Here you can see that the brackets have been updated just like the prototype at the start of the script. Inside, you still print hello using printf. A new function here is puts. This is a more advanced version of printf.

Anything put in the brackets will be printed to the console, and a newline (the \n you used earlier) gets added automatically.

Save and compile your code the same way you did earlier—note that you can name the program something different if you do not want to overwrite your earlier program. I named mine hello2:

The finished program in C

As you should see, the program takes the input and uses it in the function, before sending the preset greeting of “Everyone!” again giving two separate outputs to the same function.

The ABCs of C Programming

This program is simple, but some of the concepts in it are not. More advanced C code must be written very well to prevent crashes. This is why many think it is an excellent language to learn first as it instills good habits into new programmers.

Others think learning C++ is a better idea, as it builds on C while retaining its lower system control. One thing is sure: languages like Python are much more beginner friendly. For an old language, C is still used everywhere, but Python may be the language of the future!

Read the full article: How to Learn C Programming With This Beginner Project



from MakeUseOf https://ift.tt/2Rm04cR
via IFTTT

No comments:

Post a Comment