Basic Programs in C for practice

Example 1: Program to print a message using printf() function.

Sample code:

#include <stdio.h>
int main()
{
  printf("This is a test message");
  return 0;
}

Output:

This is a test message

 

Example 2: Program to check whether a number is positive or negative using nested if else statement.

Sample code:

#include <stdio.h>
void main()
{
    int a; 
    printf("Enter a number: \n");
    scanf("%d", &a);
    if (a > 0)
        printf("positive number");
    else if (a < 0)
        printf("negative number");
    else
        printf("neither positive nor negative");
}

Output:

Enter a number: 5
Positive number

 

Example 3: Program to find sum of N natural numbers using for loop.

Sample code:

#include<stdio.h>
int main()
{
  int a, i, sum=0;
  printf("Enter a positive integer:");
  scanf("%d",&a)
  for(i=1;i<=a;i++)
  {
    sum = sum + i;
    }
  printf("Sum of first %d natural numbers is : %d",a,sum);
  return 0;
}

Output:

Enter a positive integer: 5
Sum of first 5 natural numbers is 15

 

Example 4: Program to display the value of a character.

Sample code:

#include<stdio.h>
int main()
{
  char a;
  printf("Enter a character:");
  scanf("%c",&a);
  printf("The value of character %c is: %d",a,a);
  return 0;
}

Output:

Enter a character: M
The value of character M is: 77

 

Example 5:  Program to check if a number is even or odd using if statement.

Sample code:

#include<stdio.h>
int main()
{
  int a;
  printf("Enter a number:");
  scanf("%d",&a);
  if(a%2==0)
  printf("%d is an even number",a);
  else
  printf("%d is an odd number",a);
  return 0;
}

Output:

Enter a number: 7
7 is an odd number