Running C or C++ program in Linux

The tutorial bellow explains simple procedure to compile, run, and execute C or C++ (CPP) programs in Ubuntu using build-in G++ compiler.

Steps to run C program in Ubuntu:

1. Go to Applications > Accessories > Terminal, to open terminal window.

2. Type the following in command line

sudo gedit first.c

3. Enter the code bellow in the editor.

/* Program first.c */
#include<stdio.h>
main() {
  printf(”Hello World.\n”);
}

4. Save the file and close to return to terminal window.

5. Firstly compile the code using the following command

cc -c first.c

That would produce an object file you may need to add to the library.

6. Then create an executable using the following command

cc -o first first.c

7. Now run this executable using the following command

./first

8. Output should show as follows

Hello World.

Steps to run C++ program in Ubuntu:

1. Go to Applications > Accessories > Terminal, to open terminal window.

2. Type the following in command line

sudo gedit first.cpp

3. Enter the code bellow in the editor.

/* Program first.cpp */
#include<iostream>
main() {
  std::cout<<"Hello World."<<std::endl;
}

4. Save the file and close to return to terminal window.

5. Now compile the code using the following command

g++ first.cpp -o second

6. Then run this executable using the following command

./second

7. Output should show as follows

Hello World.

A sample factorial program in C

/* Factorial using C */
#include<stdio.h>
int main() {
  int i,n,f=1;
  printf("\nEnter the number: ");
  scanf("%d",&n);
  for(i=1;i<=n;i++) {
    f=f*i;
  }
  printf("\nFactorial of %d is %d \n\n",n,f);
}

Output:

$ sudo gedit factorial.c
$ cc -c factorial.c
$ cc -o factorial factorial.c
$ ./factorial
Enter the number: 6
Factorial of 6 is 720

Comments

Most Popular Posts

TNEB Bill Calculator

TNEB Bill Calculator (New)

Technical Questions