C Programming

C Programming Examples on Linux for Beginners

C programming language is one of the good choices for learning computer programming for the beginners. The basic programming logic can be learned easily by using C language as a first language.  Java is considered as first programming language by some people, but I think, it is better to learn structured or procedural programming using C language before learning any object-oriented programming. The basic C programming on Linux is shown in this article by using different examples for the beginners.

pre-requisites

You will require a code editor and essential packages to execute C programs. The necessary packages are installed by default on most of the Linux distribution. You can run the following command to check the necessary package is installed or not. The command will display the installed version of gcc.

$ gcc --version

Example-1: Write and run your first C program

Write the following code using any text editor and save the file with the extension ‘.c’. The header file, stdio.h contains all necessary functions for standard input and output. Any source code of C program starts compilation from the main() method. printf() function is used here to print output in the terminal.

#include <stdio.h>
void main()
{
  printf("Learning C\n");
}

Run the following command to compile and execute the code. The source file name is first.c and executable filename is first_program here.

$ gcc first.c -o first_prpgram
$ ./first_program
Learning C

Example-2: Read user input

scanf() function is used in C to read input from the user which is under stdio.h. C language is a strongly typed language and it supports different data types. Integer and char data type are used in this example. A character array of 100 characters is declared by name variable and an integer is declared by age variable. After taking two inputs from the user the formatted values will be printed by prinf() function.

#include <stdio.h>
void main()
{
  char name[100];
  int age;
  printf("Enter your name: ");
  scanf("%s",name);
  printf("Enter your age: ");
  scanf("%d",&age);
  printf("Hello, %s,You are %d years old\n", name, age);
}
linuxhint@hint1:~/code$ gcc 2.c -o 2
linuxhint@hint1:~/code$ ./2
Enter your name: Doug
Enter your age: 77
Hello, Doug,You are 77 years old

Example-3: Read command-line arguments

argc and argv variables are used as parameters in main() method to read command-line argument values. argc is used to read the total number of arguments and argv is used to read the argument values as an array. How to print total number of command-line arguments and first three argument values are shown in this example.

#include <stdio.h>
void main(int argc,char* argv[]){
  printf("Total number of arguments = %d\n",argc);
  printf("Argument No. 1 = %s\n",argv[0]);
  printf("Argument No. 2 = %s\n",argv[1]);
  printf("Argument No. 3 = %s\n",argv[2]);
}
linuxhint@hint1:~/code$ ./3 hello world
Total number of arguments = 3
Argument No. 1 = ./3
Argument No. 2 = hello
Argument No. 3 = world

Example-4: Compare string using conditional statements

strcmp() function is used in C language to compare two strings. If two strings are equal then it returns 0. If the first string is larger than the second string then it returns 1. If the first string is less than the second string then it returns -1. In this example, two numeric values and a string value will be taken as input from the user. If the string value is add then it will print the summation of two numbers. If the string value is sub then it will print the subtraction of two numbers. If both if conditions return false then it will print 0.

#include <stdio.h>
#include <string.h>
void main(){
  int n1, n2, result;
  char operator[10];
  printf("Enter first number: ");
  scanf("%d",&n1);

  printf("Enter second number: ");
  scanf("%d",&n2);

  printf("Enter operation name (add or sub): ");
  scanf("%s",operator);

  if(strcmp(operator,"add") == 0)
    result = n1 + n2;
  else if(strcmp(operator,"sub") == 0)
    result = n1 - n2;
  else
    result=0;

  printf("The result is : %d\n",result);
}
linuxhint@hint1:~/code$ gcc 4.c -o 4
linuxhint@hint1:~/code$ ./4
Enter first number: 33
Enter second number: 22
Enter operation name (add or sub): add
The result is : 55

Example-5: Iterate a list of string using while loop

Strings are stored in array’s of char data types in C. Each char can hold one character and together they form a string signified by the 0 or NULL character terminating the string. In this example we declare an array of strings in the data type array of constant char pointers (const char*). Each element in the array is a point to a string literal declared in the program. Note: these are string literals and can not be changed.

In our flowers array we terminated the array with a NULL value to allow for easy looping in the array and termination of the loop condition when NULL is reached. Below we will declare the array of flower strings and then simply loop through the positions in the array and print the strings. Ensuring to increment the counter i in the loop to move to the next position.

#include <stdio.h>
void main()
{
  const char* flowers[] =
    {"Rose", "Poppy", "Lily", "Tulip", "Marigold", NULL};

  int i = 0;
  while (flowers[i]){
    printf("%s\n",flowers[i]);
    ++i;
  }
}
linuxhint@hint1:~/code$ ./5
Rose
Poppy
Lily
Tulip
Marigold

Example-6: Find even numbers from a list using while loop

In this example we create an array of integers. We find the size of the array declared via the initializer list by checking the sizeof memory allocated to the array divided by the size of each integer element which is the total number of elements and store that in the SZ variable.

Now we can loop through the elements in the array with a for loop from 0 to the SZ and do a test of whether each number is a EVEN number. This test uses modulus operator (%) and if the result of modulus 2 equals 0 then the number must be an even number mathematically, and we print it.

#include <stdio.h>
void main(){
  int numbers[] = { 21, 78, 62, 90, 55, 10, 85, 45, 11, 2 };
  int SZ = sizeof(numbers) / sizeof(int);

  printf("The even numbers from the list are:\n");
  for (int i =0; i < SZ; i++) {

    if((numbers[i] % 2) == 0)
      printf("EVEN: %d\n", numbers[i]);
  }
}
linuxhint@hint1:~/code$ gcc 6.c -o 6
linuxhint@hint1:~/code$ ./6
The even numbers from the list are:
EVEN: 78
EVEN: 62
EVEN: 90
EVEN: 10
EVEN: 2

Example-7: Find out the area of a rectangle using a function

Each function in C contains return type, function name and the parameters. Parameter-less function can also be declared in C. If any function user defined function is declared in the source code then the prototype of that function must be declared before the function is used. In this example, area() function is declared to calculate the area of any rectangle that contains two parameters to get the height and width values of the rectangle. main() function will read the height and width value from the user and call area() function to calculate and print the area.

#include <stdio.h>
int area(int h, int w)
{
  int area = h * w;
  return area;
}

void main()
{
  int height, width;

  printf("Enter the height of the rectangle: ");
  scanf("%d", &height);

  printf("Enter the width of the rectangle: ");
  scanf("%d", &width);

  printf("The area of the rectangle = %d\n",area(height,width));
}
linuxhint@hint1:~/code$ gcc 7.c -o 7
linuxhint@hint1:~/code$ ./7
Enter the height of the rectangle: 10
Enter the width of the rectangle: 8
The area of the rectangle = 80

Try yourself:

  • Write a C program to take a number from zero to 10 and print the string value of the number
  • Write a C program to a string on command line and print the country code for the country specified in a string
  • Write a C Program with your own defined function to calculate a conversion from USD to INR currency at today’s current rate

Conclusion:

The most basic parts of programming are described here using simple examples to start programming with C language. The declarations of different variables, conditional statements, loop and function in C are shown in this article.

About the author

Linux Wolfman

Linux Wolfman is interested in Operating Systems, File Systems, Databases and Analytics and always watching for new technologies and trends. Reach me by tweeting to @linuxhint and ask for the Wolfman.