Friday, July 29, 2016

C Basics - First Program in C

All your first program is going to do is print the message "Hello World" on the screen. Let us look at a simple code that would print the words "Hello World".

#include <stdio.h>

int main(int argc, char *argv[]) 
{
   
   /* my first program in C */
   printf("Hello, World! \n");
   
   return 0;
}

How C programs work is the operating system loads your program, and then runs the function named main. For the function to be totally complete it needs to return an int and take two parameters, an int for the argument count, and an array of char * strings for the arguments.

Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps.
  • Open a text editor and add the above-mentioned code.
  • Save the file as hello.c
  • Open a command prompt and go to the directory where you have saved the file.
  • Type gcc hello.c and press enter to compile your code.
If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file.

Now, type a.out to execute your program.

You will see the output "Hello World" printed on the screen.

$ gcc hello.c
$ ./a.out
Hello, World!

Let us look at a simple code that would echo your age.

#include <stdio.h>

int main(int argc, char *argv[]) 
{
   
   int age;

   printf("Enter Your age: ");
   scanf("%d",&age);
   printf("\nYour age is %d ", age);
   
   return 0;
}

Here, scanf function is used to take the input from the user. When you run this program, it waits for a user input (age) and once user enters the age, it does the print the user entered value.

printf function is used in couple of places in the above code. Whatever you give inside double quotes, it prints on the screen.



Related topics:
Intro of C   |   Overview of C   |   Features of C   |   Applications of C   |   The Setup for C   |   Source Program in C   |   Program Startup and Termination in C   |   Program Structure in C   |   Must Know Terms in C

List of topics: C Programming

No comments:

Post a Comment