Compile and run C programs in Termux

In this article, we will show how to Compile and run C programs in Termux. We will write a hello.c program then we will compile and run in an Anroid phone using Termux Linux emulator.

Prerequisites

Assuming you already have latest C compiler in your device installed. Just check it out using:

$ gcc --version                  clang version 13.0.1               Target: aarch64-unknown-linux-android24                               Thread model: posix                InstalledDir: /data/data/com.termux/files/usr/bin

Write a program to print out Hello world. Here is the code for printing Hello world.

#include <stdio.h>
int main(){
  printf("Hello world\n");
  return 0;
}

Compile and run

Make sure you are in the home directory otherwise it will not create an executable file. Commands are given below:

~ $ gcc hello.c -o hello           ~ $ ./hello
Hello world                        ~ $

Let’s try a something harder. Write a C program to check if the number is prime or not.

Definition

prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}

Ref: https://www.geeksforgeeks.org/c-program-to-check-whether-a-number-is-prime-or-not/

// C program to check if a
// number is prime
#include <math.h>
#include <stdio.h>
int main()
{
  int n, i, flag = 1;
  // Ask user for input
  printf("Enter a number: \n");
  // Store input number in a variable
  scanf("%d", &n);
  // Iterate from 2 to sqrt(n)
  for (i = 2; i <= sqrt(n); i++) {
    // If n is divisible by any number between
    // 2 and n/2, it is not prime
    if (n % i == 0) {
      flag = 0;
      break;
    }
  }
  if (n <= 1)
    flag = 0;
  if (flag == 1) {
    printf("%d is a prime number", n);
  }
  else {
    printf("%d is not a prime number", n);
  }
  return 0;
}

Output

~ $ gcc isprime.c -o isprime
~ $ ./isprime                      Enter a number:                    49                                 49 is not a prime number~ $ ./isprime                                 Enter a number:
47
47 is a prime number~
$

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *