Simple C programs with outputs to learn C

Simple C programs with outputs to learn C

In this article I'll share with you simple C Programs which you can code to learn C Language.

·

12 min read

Ever thought of Learning a Programming Language but instead got stuck with two major Questions:

  • Which Programming Language to Learn??

  • Where and How to Learn in the best possible way??

Well, I must say there are dozens of Programming Languages to choose from and it makes a tough question even tougher, But to answer a tough question you must start learning C Language. The reason is that it's considered the mother of all Programming Languages, because all of the concepts of modern programming languages were taken from this Language only, also being a Programming language that is close to machine-level coding it gives the best and maximum performance to the developer with control over hardware.

Let us discuss some Programs that can help you to learn C Language easily by coding some real-world Programs.

Learn C Language by Coding

Let's take a look at some Programs that you can develop and focus on Learning the C language.

Hello World Program

Let's be honest, Every developer has made a Hello World Program when they're learning a new Programming Language. With a Hello World Program, you can learn how to display Messages to the console for the End User. With a Hello World Program, you can also check whether the Installation of C language is correctly done or not.

Code

#include <stdio.h>

int main(){
    printf("Hello World");
    return 0;
}
Output
Hello World

Take User Inputs

Taking User Input is the most important step in any Software, and learning to take input from the user in your very own Software Developed with C language will allow you to make your program Dynamic.

Things you'll learn from this program:

  • Variables

  • Handling User Inputs and data types

  • DataType Conversions

Code

#include<stdio.h>

int main()
{
    int numberOne, numberTwo;

    printf("Enter the Numbers : Number 1 and Number 2");

    scanf("%d%i", &numberOne, &numberTwo);
    printf("\n\nYou entered %d and %i\n\n", numberOne, numberTwo);

    return 0;
}
Output

Take Complete string as an Input

One of the main problems with scanf is that it only can take inputs until there's a Space between the String entered. That's where the gets() function get into play.

Code

#include<stdio.h>

int main()
{
    char name[50];
    printf("Enter your complete name:\n\n");

    gets(str);
    printf("\n\nWelcome to Codedamn  %s\n\n", name);
    return 0;
}
Output

Conditional Statements

If you ever thought about how can a Program know what to do if you did something particular in software, That's something handled by Conditional Statements. Conditional Statements run based on the inputs given to the program.

Conditional Statements Include two types of Statements:-

  • If-else Statements

  • Switch Statement

If-Else Statements

If else statements work based on the inputs provided, it checks whether the input matches a certain condition provided by the developer, If the condition matches with the condition provided then it'll execute a set of lines of code often named as a block of Code, else the different block of Code will execute which is under the Else Block.

Let's take a Look at the code, it'll make everything clear

Code
#include<stdio.h>

int main()
{
    int option;
    printf("Enter a Number : ");
    scanf("%d",&option);

    if(option < 100)
        printf("Entered Number is less than 100.");
    else if(option == 100)
        printf("Exactly 100");
    else
        printf("Entered Number is more than 100.");

    return 0;
}
Output

Switch Statement

Sometimes the program gets very long and slow due to multiple conditions and checking every condition can take up a long time. To tackle this kind of problem the Language Developers came up with Switch Statements to speed up the execution time and fewer lines of Code.

Code
#include<stdio.h>

int main()
{
    char marks;
    printf("Enter your Grade:\n");
    scanf("%c", &marks);

    switch(marks)
    {
        case 'A':
            printf("You have a Score of 90+ percentage");
            break;
        case 'B':
            printf("You have a score of 80+ percentage");
            break;
        case 'C':
            printf("You have a score of 70+ percentage");
            break;
        case 'D':
            printf("You have a score of 60+ percentage");
            break;
        case 'F':
            printf("Sorry but you've to work hard");
            break;
        default:
            printf("\t\tDefault Case : Invalid grade\n\n\n");
    }
    printf("Grade : %c\n",marks);
    return 0;
}
Output
Enter your Grade:
A
You have a Score of 90+ percentageGrade : A

Enter your Grade:
B
You have a Score of 80+ percentageGrade : B

Enter your Grade:
C
You have a Score of 70+ percentageGrade : C

Performing Arithmetic Operations using C Language

In Software Development, performing Artimatic Operations is a very basic task and to perform those tasks and store the output in the desired data type without the loss of Data is very crucial.

Code

#include <stdio.h>

int main() {

  char Operator;
  double numberOne, numberTwo;
  printf("Select an Operator from the given options (+, -, *, /): ");
  scanf("%c", &Operator);
  printf("Enter the two numbers to perform the operations included with a space like this -> firstNumber secondNumber : ");
  scanf("%lf %lf", &numberOne, &numberTwo);

  switch (Operator) {
    case '+':
      printf("%.1lf + %.1lf = %.1lf", numberOne, numberTwo, numberOne + numberTwo);
      break;
    case '-':
      printf("%.1lf - %.1lf = %.1lf", numberOne, numberTwo, numberOne - numberTwo);
      break;
    case '*':
      printf("%.1lf * %.1lf = %.1lf", numberOne, numberTwo, numberOne * numberTwo);
      break;
    case '/':
      printf("%.1lf / %.1lf = %.1lf", numberOne, numberTwo, numberOne / numberTwo);
      break;

    default:
      printf("It was stated that to select from the given options of Operations, and yet you did not");
  }

  return 0;
}
Output
Select an Operator from the given options (+, -, *, /): *
Enter the two numbers to perform the operations included with a space like this -> firstNumber secondNumber : 1.5 4.5
1.5 * 4.5 = 6.8

Loops in C Programming

A Loop consists of three parts which are mentioned below

  • Initialization

  • Condition

  • Update

Let's look at some of the loops in C Programming

For Loop

// Format of For loop in C language
for ( Initialization; Condition; Updating ){
    Code;
}
Code
#include<stdio.h>

int main()
{
    int i = 0;


    for(i = 0; i < 10; i++)
    {
        printf("i = %d\n", i);
     }

    printf("\nValue of i after the Loop ends : %d", i);

    return 0;
}

While Loop

While loop is the same as For loop you can consider this as an upgraded version of For loop, Just compare this syntax with for loop.

Initialization;

while( Condition ){
    Code;
    Updation;
}
Code
#include<stdio.h>

int main()
{
    int i = 0;

    printf("Print the Numbers from 0 to 9");

    while(i<10)
    {
        printf("%d\n",i);
        i++;
      }
    return 0;
}
Output

Do-while loops in C Language

The main difference between Do-while loops and While Loops is that the while loop will run once even if the condition is not satisfied due to the condition being checked at the end of the execution of Do while Loop.

Initialization;

do{
    Code;
    Updation;
}while( Condition )
Code

#include<stdio.h>

int main()
{
    int i = 10;

    do
    {
        printf("i = %d\n",i);
        i = i-1;
    }while(i > 0);

    return 0;
}
The output of Do While Loop in C Programming

Programs to Practice

Program to get the Factorial of a Number

#include<stdio.h>
void main()
{
   int num;
   long int factorial = 1;
   printf("Enter a Number to find the factorial : ");
   scanf("%d" , &num);
   int i = num;
   while(i) {
       factorial = factorial * i;
       i--;
   }
   printf("Factorial of %d is %ld", n , fact);
}
Output
Enter the number: 3
Factorial of 3 is 6

Fibonacci Series

The Fibonacci series is a series of Numbers developed from adding the previous two numbers. It requires just two numbers it can be even 0 and 1 and it'll generate Fibonacci Series up to n number.

#include<stdio.h>
#include<conio.h>

void fibonacci(int n)
{
   int a, b, c, i = 3;
   a = 0;
   b = 1;
   if(n == 1)
   printf("%d",a);

   if(n >= 2)
   printf("%d\t%d",a,b);

   while(i <= n)
   {
      c = a+b;
      printf("\t%d", c);
      a = b;
      b = c;
      i++;
   }
}

void main()
{
    int n = 0;
    clrscr();
    printf("Enter number of items to produce: ");
    scanf("%d", &n);
    fibonacci(n);
    getch();
}
The output of the Program above
Enter number of terms 6
0     1    1    2    3    5

Palindrome or not

A Palindrome number means a number written backward and still being the same.

#include<stdio.h>
#include<conio.h>

void main()
{
    int x, y, z, i = 0;
    clrscr();
    printf("Enter a number:\t");
    scanf("%d", &x);
    z = x;

   while(x > 0){
      y = x%10;
      i = (i*10)+y;
      x = x/10;
   }

   if(i == z){
      printf("It is Palindrome");
   }
   else{
      printf("It is not a Palindrome");
   }
  getch();
}
Output
Enter the number: 121
The number 121 is a palindrome

Program to reverse a String in C Language

#include <stdio.h>
int main()
{
  char str[1000], rev[1000];
  int i, j, count = 0;
  scanf("%s", str);
  printf("\nString Before Reverse: %s", str);
  //finding the length of the string
  while (str[count] != '\0')
  {
    count++;
  }
  j = count - 1;

  //reversing the string by swapping
  for (i = 0; i < count; i++)
  {
    rev[i] = str[j];
    j--;
  }

  printf("\nString After Reverse: %s", rev);
}
Output
Hello

String Before Reverse: Hello
String After Reverse: olleH

Print the Sum of N Input Numbers

#include<stdio.h>

int main()
{
    int n,sum=0,c,num;

    printf("Enter the numbers you want to add provided with a Space in between them: ");
    scanf("%d", &n);

    printf("Enter %d number of integers to add: ",n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%d", &num);
        sum += num;
    }

    printf("Sum of the Numbers entered are = %d", sum);
    return 0;
}
Output

Program to find the largest of n Numbers

#include<stdio.h>

int main()
{
    int num,i;
    float x,largest;

    printf("Enter the Number of Elements you want to search among: ");
    scanf("%d", &num);
    printf("Enter the numbers to search from\n");

    printf("Element 1: ");

    scanf("%f", &largest);

    for(i = 2; i <= num; i++)
    {
        printf("\nEnter Element %d  : ", i);
        scanf("%f", &x);
        if(largest < x)
            largest = x;
    }

    printf("\nThe largest of the %d numbers is  %f ", num, largest);
    return 0;
}
Output

Arrays

Arrays are a certain type of data structure that can help you to store multiple data within a single variable instead of creating variables for every other data that we acquire from the user.

Arrays are fixed in nature which means when you specify the length of the Array then you cannot change it during the execution of the Program until it's been modified and compiled to run again.

There are two types of Arrays

  • 1D Array also known as Linear Array

  • 2D Array also known as Matrix

Let's look at some of the Programs to practice 1D Array

C Program to Insert Elements in an Array

Inserting an Element in an Array is the first step in Developing Array Programs.

#include<stdio.h>

int main()
{
    int array[100], position, c, n, value;

    printf("\n\nEnter number of elements in array:");
    scanf("%d", &n);

    printf("\n\nEnter %d elements\n", n);
    for(c = 0; c < n; c++)
        scanf("%d", &array[c]);

    printf("\n\nEnter the location where you want to insert new element:  ");
    scanf("%d", &position);

    printf("\n\nEnter the value to insert: ");
    scanf("%d", &value);

    for(c = n-1; c >= position-1; c--)
        array[c+1] = array[c];

    array[position - 1] = value;

    printf("\n\nResultant array is: ");
    for(c = 0; c <= n; c++)
        printf("%d  ", array[c]);

    return 0;
}
Output

Program to Delete an Element from an Array

#include<stdio.h>

int main()
{

    int array[100], position, c, n;
    printf("\n\nEnter number of elements in array:");
    scanf("%d", &n);

    printf("\n\nEnter %d elements\n", n);
    for(c = 0; c < n; c++)
        scanf("%d", &array[c]);

    printf("\n\nEnter the location where you want to delete element from:  ");
    scanf("%d", &position);

    if(position >= n+1)
        printf("\n\nDeletion not possible\n\n");
    else{
        for(c = position-1; c < n-1; c++)
        array[c] = array[c+1];
    }
    printf("\n\nResultant array is: ");
    for(c = 0; c < n-1; c++)
        printf("%d  ", array[c]);

    return 0;
}
Output

Pointers

Pointer is a concept in which the program manipulates the memory of the System and produces the desired output as the developer wants. Not all of the Programming Language provides support for Pointers as it lead to memory leaks and system failure if not handled properly.

Code to Practice Pointers

#include <stdio.h>

int main()
{
    int pointerLocation = 85;
    int *p = pointerLocation;

    p = &pointerLocation;

    printf("Address of Pointer Location is: %x \n\n", &pointerLocation);

    printf("Address at which Pointer Variable is stored: %x", p);

    printf("\nThe Value which is stored at Pointer p is %d ", *p);

    return 0;
}
Output

Tough Program

After doing all these programs, let's code two programs that are more difficult than all the programs listed above.

The two programs are

  • Store the Inputs of the user in a file and then Print it to the console.

  • Write a Program to remove all duplicates from an Array of Strings.

Conclusion

In this complete article, we learned different types of programs that we can practice to learn C Programming Language a bit faster and in an efficient way. C Programming language can be a bit tough to learn but by practicing some Programs it can become easy.

Hope this article was helpful to you, to learn C Language try developing a Banking System with the use of a File System, it'll surely boost the learning of Programming in C.

All of the source code with a Playground is available on our in-browser IDE named Playground, which you can access by clicking here, you can execute the code without the hassle of setting up the IDE and other things, just open up and code.

This article was originally written back when I was starting but as a private article, I was afraid of building in Public but now Let's do this.

So my Web App which I am rebuilding is available on justaman045.vercel.app you can visit it now also but it's currently under heavy maintenance and the look and feel will change in about 2 or 3 weeks.

Promotion

Currently, I am also focused on building the Community mentioned below:

  1. Anime Community:- Instagram/otakuanime69

  2. Motivational Theme Page:- Instagram/glorymotivation7

also, I'm currently focused on building my Brand named Otaku Outfits currently it's in the approval stage on Etsy but once it is live I'll be sharing it with you all by making sure to subscribe to my Newsletter from the Newsletter tab.

Also, it'll be helpful if you can just follow this link to Medium and give me a like and follow there too.

Contact

To contact you can join my Discord Server where I intend to keep the community in one place and also serve the community
Discord Link:- https://discord.gg/ZfAKPZvT ( It's brand new and I'm okay if you help me out on setting up this ).

Thanks for Reading
Happy Hacking