Your first C program in Ubuntu

C, programming language was designed by Dennis Ritchie. We have already discussed how to compile a C program in Ubuntu distribution. In this article, we would focus on how to write your first C program.

Open a text editor in terminal, we have used nano –

nano first-code.c

And, insert the following code in it –

#include <stdio.h>
/* Your first C Program */
int main(void)
     {
              char name[100];
              printf("Enter your name: ");
              scanf("%s", name);
              printf("Hello %s!\n", name);
              return 0;
}

Save and exit. We will explain the code a bit now.

Your first program explained

#include <stdio.h> – is a directive to the preprocessor. The #include directive instructs the preprocessor to open file stdio.h & include its contents. The file contains standard I/O library of C.

/* Your first C Program */ – is a comment. This is just to make sure we know what our code is all about. Anything that is inside /**/, won’t be compiled.

int main(void) – The function main() returns an integer value. And, void is to specify that the function can’t be called with an argument.

char name[100] – declared a char array (name, of size – 100)

printf() – To print the output.

scanf() – To read input from the user, %s has been used for string input followed by the variable name.

\n – for newline.

return 0 – as discussed above, the function main() returns an integer value.

C programs have directives, functions and statements.

Directives start with # symbol and don’t end with ;(semi-colon).

Functions can be of two categories – user-defined functions & library functions.

Statements are specific instructions to be executed. At the end of every statement, it is necessary to put a ;(semi-colon).

Compile your first C program

Next, we will compile our code. We can compile our code through GNU Compiler Collection (GCC). Therefore, issue the following in terminal –

gcc -o first-code first-code.c

Any error/warning, if any, would be notified at this stage. If it returns with nothing, then we are all set to run our code. Again, issue the following in terminal –

./first-code

It asks you to Enter your name and prints the desired output.

In conclusion, we have discussed how to write your first C program in Ubuntu distribution.

Similar Posts