Monday, February 25, 2013

C progrram

1.
Array : Dynamic

/* A dynamically-allocated 1-D array */

#include <stdio.h>

int main (void)
{

    double* array; /* declare a pointer only */
    int i, size;

    /* ask user for size of array */
    printf ("How large do you want your array? ");
    scanf ("%d", &size);

    /* allocate the array in the heap */
    array = (double *) calloc (size, sizeof(double));

    /* printing the array for verification
    surprise! a dynamic array is
    automatically initialized with zeros! */
    for (i = 0; i < size; ++i)
        printf ("%6.2lf", array[i]);

    /* freeing the memory allocation */
    free (array);

    return (0);
}


2.
Array : Search

/* THE BASIC SEARCH ALGORITHM FOR A 1-D ARRAY */

#include <stdio.h>

int
search (int arraytosearch[], int valuetosearch, int size)
{
    int i, found;

    /* initialize found at -1, if value not found, stays at -1 */
    found = -1;

    /* search until found or until end of array */
    i = 0;
    while (found<0 && i<size)
    {
        if (arraytosearch[i] == valuetosearch)
            found = i; /* I have found it! */
        else
            i = i + 1;
    }
    return (found);
}


int
main (void)
{
   
    int x[] = {12,67,56,60,88,34,123};
    int value = 60;
    int pos, i;

    pos = search (x, value, 7);

    if (pos >= 0)
        printf ("%d was found at position %d.\n", value, pos);
    else
        printf ("%d was not found in the array.\n", value);


    return (0);
}

Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments

60 was found at position 3.


3.
Array : Adding Two Arrays

/* Problem: Add the corresponding values from two arrays
of the same size. */
#include <stdio.h>

/* the function that adds the two arrays a1 and a2. it "returns" a3 back */
void
addarrays (int a1[], int a2[], int a3[], int n)
{
    int i;

    /* do the adding of every corresponding cells */
    for (i=0; i<n; ++i)
        a3[i] = a1[i] + a2[i];
}

int
main (void)
{
    int x[] = {1,2,3,4}, i;
    int y[] = {10,20,30,40};
    int z[4];

    /* call the function */
    addarrays (x, y, z, 4);

    /* print a report */
    for (i=0; i<4; ++i)
        printf ("%3d", x[i]);

    printf ("\n + \n");

    for (i=0; i<4; ++i)
        printf ("%3d", y[i]);

    printf ("\n-------------\n");

    for (i=0; i<4; ++i)
        printf ("%3d", z[i]);

    return (0);
}



4.
Array : Filling Partially

/* Problem: This program partially fills an array from a file
until the end of file (EOF).
We get the actual number of data read  */
#include <stdio.h>

int
array_from_file (double a[], int size)
{
        int i;
        FILE* in;

        in = fopen ("data_array.dat", "r");
       
        i=0; /* the first cell */

        /* filling the array cell by cell */
        /* until it is full or until the EOF */
        while (i < 100 && fscanf (in, "%lf", &a[i]) != EOF)
        {
               i=i+1;
        }

        fclose (in);

        /* the actual number of values in the array */
        return (i);      
}


int
main (void)
{
        double array[100];
        int actual_size, i;

        actual_size = array_from_file (array, 100);

        for (i=0; i < actual_size; ++i)
               printf ("%3.1lf ", array[i]);

        printf ("\nThe array contains %d values ", actual_size);
        printf ("for a capacity of 100 cells.\n");

        return (0);
}



5


Array : With Pointer

/* Problem: This programs fills an array with a value
submitted by the user. */
#include <stdio.h>

/* array parameter can be expressed as a pointer */
/* *list is the same thing as list[] */
void
fill_array (int *list, int n, int in_value)
{
    int i;
    for (i=0; i<n; ++i)
        list[i] = in_value;
}

int
main (void)
{

         int x[100];
         int i;

    /* &x[0] is the address of the x[0] */
    /* which is the same thing as x */
        fill_array (&x[0], 100, 5);


    /* printing the array for verification */
    for (i=0; i<100; ++i)
        printf ("%d  ", x[i]);

    return (0);
}


6.

Array : Filling from a file

#include <stdio.h>

int
main (void)
{
    int numbers[10], i;
    FILE *input;

    input = fopen("numbers.txt", "r");
   
    /* reading file - filling array */
    for (i=0; i<10; ++i)
        fscanf(input, "%d", &numbers[i]);
       

    /* printing the content of array */
    printf("The numbers read are: ");
    for (i=0; i<10; ++i)
        printf("%4d", numbers[i]);

    printf ("\n");

    fclose (input);

    return (0);
}


7.

Array : Meand & Standard Deviations

/* This program computes the meand and standard deviations of
the values inside an array */
#include <stdio.h>
#include <math.h>
#define MAX 5

int
main (void)
{

    double mean, sd, sum, sumsq;
    double x[] = {10.0, 15.0, 20.0, 10.0, 30.0};
    int i;

    sum = 0;
    sumsq = 0;

    /* computing the sum and sum of squares */
    for (i=0; i<MAX; ++i)
    {
        sum = sum + x[i];
        sumsq = sumsq + x[i] * x[i];
    }


    /* computing mean and standard deviation */
    mean = sum / MAX;
    sd = sqrt(sumsq / MAX - mean * mean);


    /* printing report */
    printf ("The mean is %lf. \n", mean);
    printf ("The standard deviation is %lf. \n", sd);
   
    return (0);
}


8.

Array: using a function

/* Problem: This program asks the user for a value and fills all
100 cells of an array with that value */
#include <stdio.h>

/* no size in array parameter */
/* just a pointer to array in main */
void
fill_array (int list[], int n, int in_value)
{
    int i;
    for (i=0; i<n; ++i)
        list[i] = in_value;
}

int
main (void)
{

    int x[100], i, value;

    /* initializing the array with a user value */
    /* the 2nd argument must be the size of the array */
    printf ("Enter a value: ");
    scanf ("%d", &value);
        fill_array (x, 100, value);


    /* printing the array for verification */
    for (i=0; i<100; ++i)
        printf ("%d  ", x[i]);

    return (0);
}



9.

Array : Initializing & Printing an Array

/* Problem: This program initializes an array with all cells
filled with 0.0 */
#include <stdio.h>

int main (void)
{

    double x[100];
    int i;

    /* initializing the array with 0.0 */
    for (i=0; i<100; ++i)
        x[i] = 0.0;


    /* printing the array for verification */
    for (i=0; i<100; ++i)
        printf ("%5.1lf", x[i]);

    return (0);
}


10.

Switch Case Example for Simple Arithmetic Operations

   
The source code illustrating the use Switch Case Example for Simple Arithmetic Operations - Addition, Subtraction, Multiplication and Division are given on this page.
Source Code
#include <stdio.h>


void main()
{
      int opcode;
      int a, b;
      int result;

      printf("Program for Addition, Subtraction, Multiplication and Division\n");
      printf("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: ");
      scanf("%d", &opcode);
      printf("Enter First Number:");
      scanf("%d", &a);
      printf("Enter Second Number:");
      scanf("%d", &b);

      switch(opcode)
      {
      case 1:
            result = a + b;
            printf("%d + %d = %d", a, b, result);
            break;
      case 2:
            result = a - b;
            printf("%d - %d = %d", a, b, result);
            break;
      case 3:
            result = a * b;
            printf("%d * %d = %d", a, b, result);
            break;
      case 4:
            result = a / b;
            printf("%d / %d = %d\n%d %% %d = %d", a, b, result, a, b, a % b);
            break;
      }
}
Output
Program for Addition, Subtraction, Multiplication and Division
Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 1
Enter First Number: 5
Enter Second Number: 3
5 + 3 = 8

Program for Addition, Subtraction, Multiplication and Division
Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 2
Enter First Number: 5
Enter Second Number: 3
5 - 3 = 2

Program for Addition, Subtraction, Multiplication and Division
Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 3
Enter First Number: 5
Enter Second Number: 3
5 * 3 = 15

Program for Addition, Subtraction, Multiplication and Division
Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 4
Enter First Number: 5
Enter Second Number: 3
5 / 3 = 1
5 % 3 = 2


11.

Break and Continue statements
Use of break and continue statements
   
break statement is used to come out the loop.
continue statement is used to continue the loop but skip the execution of the remaining statements in the loop.

These statements are used in any loop statements (for,do while, while) and switch case statements.

The sample code given below has infinite for loop. if i >= 60, then break statement will get executed and loop will get terminated. if (i % 2) is false meaning odd number, then the continue statement will skip the remainder of the statement. In this case, eventcount will not get incremented.

Source Code


void main()
{
    int evencount = 0, i = 0;
    for(i = 0; ; i++)
    {
        if(i >= 60)
            break; // Terminate the for loop
        if((i % 2) != 0)
            continue; // Will skip the reminder of the for loop
        evencount++;
    }
    printf(“Total Even Numbers Between 0 – 60 is: %d”, evencount);
}


12.

Build Pattern
Build Pattern of * and numbers using loops

   
This program will accept a number as input. The loops are used to build a pattern of * and numbers. There are four loops, two for displaying number and other two for displaying pattern of stars.
Source Code
#include <stdio.h>

int main()
{
    int i,j,n;
    printf("Enter a number: ");
    scanf("%d", &n);

    printf("\n");

    for(i = n; i > 1; i--)
    {
        for(j = 1; j <= i; j++)
            printf("*");
        printf("\n");
    }
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= i; j++)
            printf("*");
        printf("\n");
    }
    printf("\n");

    for(i = 1; i < n; i++)
    {
        for(j = 1; j <= i; j++)
            printf("%d",j);
        printf("\n");
    }
    for(int i = n; i >= 0; i--)
    {
        for(int j = 1; j <= i; j++)
            printf("%d",j);
        printf("\n");
    }
    printf("\n");

    return 0;
}
Output
Enter a number: 6

******
*****
****
***
**
*
**
***
****
*****
******

1
12
123
1234
12345
123456
12345
1234
123
12
1



13.


Reverse a String
Reverse a String With Out Using String Library Functions

   
I have used while loop to find out the length of the string and for loop to reverse the string. The function name is ReverseString which does the work for you.
Source Code
bool ReverseString(const char *src, char *dst, int len)
{
    const char *p = src;

    // count the length
    int count = 0;
    int i = 0, j = 0, k = 0;
    while(1)
    {
        if(p == NULL || *p == '\0' ||
            *p == '\t' || *p =='\n' || *p == '\r')
        {
            count = i;
            break;
        }
        p = p + 1;
        i = i + 1;
    }

    if(count > len)
    {
        return false; // Insufficient memory in the destination pointer
    }

    for(j = count - 1; j >= 0; j--)
    {
        dst[k++] = src[j];
    }
    dst[k] = '\0';

    return true;
}


int main()
{

    char src[] = "arif";
    char dst[32];
    ReverseString(src, dst, 32);
    printf("%s\n%s\n", src, dst );
    return 0;
}
Output


14.

Check Odd or Even Number
Loops - Read Numbers and Check Odd or Even Number

   
I have given here the code to read set of integers and display whether odd or even number.

Source Code
#include <stdio.h>

int main()
{
    printf("Program to find ODD or Even Number\n");
    while(1)
    {
        int n = 0;
        printf("\nEnter a number(-1 for Exit): ");
        scanf("%d",&n);

        if( n == -1)
            break;

        if((n % 2) == 0)
        {
            printf("%d is a EVEN number.\n", n);
        }
        else
        {
            printf("%d is a ODD number.\n", n);
        }
    }
    return 0;
}
Output
Program to find ODD or Even Number

Enter a number(-1 for Exit): 1
1 is a ODD number.

Enter a number(-1 for Exit): 2
2 is a EVEN number.

Enter a number(-1 for Exit): 3
3 is a ODD number.

Enter a number(-1 for Exit): 4
4 is a EVEN number.

Enter a number(-1 for Exit): 5
5 is a ODD number.

Enter a number(-1 for Exit): 6
6 is a EVEN number.

Enter a number(-1 for Exit): 7
7 is a ODD number.

Enter a number(-1 for Exit): -1

Press any key to continue . . .



15.

Creating Pyramid
Creating Pyramid using loops

   

I have given here a simple program withg loops to build a pyramid with *. You can replace * with any other character you like.

Source Code
#include <stdio.h>

int main()
{
    int i,j,k, n;
    printf("Enter number of rows for pyramid: ");
    scanf("%d", &n);

    printf("\n");

    for(i = 1; i <= n; i++)
    {
        for(j = 0; j < (n - i); j++)
            printf(" ");
        for(j = 1; j <= i; j++)
            printf("*");
        for(k = 1; k < i; k++)
            printf("*");
        printf("\n");
    }
    printf("\n\n");

    return 0;
}
Output
Enter number of rows pyramid: 21

                    *
                   ***
                  *****
                 *******
                *********
               ***********
              *************
             ***************
            *****************
           *******************
          *********************
         ***********************
        *************************
       ***************************
      *****************************
     *******************************
    *********************************
   ***********************************
  *************************************
 ***************************************
*****************************************



16.
ELSE IF Ladder
ELSE IF ladder

   
Here is an example for else if ladder in C Programming Language. Else if ladder means, an simple if statement occurs with in the else part of simple if else statement.
if statement evaluates the condition inside the paranthesis and if it is true, then it executes one line followed by if statement or the sequence of steps bound of { }.

if statement can be combined with else part which is explained in if else statement.

Nested if statement is explained with finding the biggest of 3 numbers example.

Else if ladder is explained with an example given below:
Source Code
#include <stdio.h>

void main()
{
   int choice;

   printf("[1] Add\n");
   printf("[2] Edit\n");
   printf("[3] Delete\n");
   printf("[4] View\n");
   printf("[5] Exit\n");

   printf("Enter your choice: ");

   scanf("%d", &choice);
 
   if(choice == 1)
      printf("Add option selected");
   else if(choice == 2)
      printf("Edit option selected");
   else if(choice == 3)
      printf("Delete option selected");
   else if(choice == 4)
      printf("View option selected");
   else if(choice == 5)
      printf("Exit option selected");
   else
      printf("Invalid option selected");

}
Output
[1] Add
[2] Edit
[3] Delete
[4] View
[5] Exit
Enter your choice: 4


View option selected


17.


Nested IF
Nested IF Statement

   
Here is an example for nested if statement in C Programming Language. Nested if means, an simple if statement occurs with in another if statement.
if statement evaluates the condition inside the paranthesis and if it is true, then it executes one line followed by if statement or the sequence of steps bound of { }.

if statement can be combined with else part which is explained in if else statement.

Nested if statement is explained with finding the biggest of 3 numbers example given below.

Source Code
#include <stdio.h>

void main()
{
   int a,b,c;
   int biggest;

   printf("Enter 1st Number: ");
   scanf("%d", &a);
   printf("Enter 2nd Number: ");
   scanf("%d", &b);
   printf("Enter 3rd Number: ");
   scanf("%d", &c);

   if(a > b)
   {
      if(a > c)
         biggest = a;
      else
         biggest = c;
   }
   else
   {
      if(b > c)
         biggest = b;
      else
         biggest = c;
   }
   printf("Biggest of 3 numbers is: %d\n", biggest);
}

Output
Enter a Number: -100
-100 is a negative number

Enter a Number: 55
55 is a positive number



18.

IF ELSE
Simple IF ELSE Statement

   
Here is an example for simple if else statement.

if statement evaluates the condition inside the paranthesis and if it is true, then it executes one line followed by if statement or the sequence of steps bound of { }.

if statement can be combined with else part. Else part will be executed when the if condition is false.


Source Code
#include <stdio.h>


void main()
{
   int x;

   printf("Enter a Number: ");
   scanf("%d", &x);

   if(x < 0)
      printf("%d is a negative number\n", x);
   else
      printf("%d is a positive number\n", x);
}

Output
Enter a Number: -100
-100 is a negative number

Enter a Number: 55
55 is a positive number


19.

IF Statement
Simple IF Statement

   

Here is an example for simple if statement.

if statement evaluates the condition inside the paranthesis and if it is true, then it executes one line followed by if statement or the sequence of steps bound of { }.
Source Code
#include <stdio.h>


void main()
{
   int x;

   printf("Enter a Number: ");
   scanf("%d", &x);

   if(x < 0)
      printf("%d is a negative number\n", x);
}

Output
Enter a Number: -100
-100 is a negative number


20.

Display numbers using loops
C Programming  Loops - display numbers using for loop, while loop and do while loop

   
The main difference between for loop, while loop, and do while loop is
1.While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.

2.do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false.

3.for loop is similar to while loop except that •initialization statement, usually the counter variable initialization •a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement.

The following sample code that can display numbers explains all 3 different loops:


Source Code
#include <stdio.h>

int main()
{

    int num = 0;
    printf("Using while loop\n");
    while(1)
    {
        num = num + 1;
printf("%d\n", num);
        if(num >= 5)
            break;
    }

    printf("Using do while loop\n");

    num = 0;
    do
    {
        num = num + 1;
        printf("%d\n", num);
} while(num < 5);

    printf("Using for loop\n");

    for(num = 1; num <= 5; num++)
    {
printf("%d\n", num);  
};

    return 0;
  
}
Output
Using while loop
1
2
3
4
5
Using do while loop
1
2
3
4
5
Using for loop
1
2
3
4
5
Press any key to continue . . .


21.


Fibonacci Series
Fibonacci Series

   
The logic for Fibonacci series very simple. It starts with 0 and 1. The next subsequent term is the sum of the previous two terms.

Source Code

// Program for Fibonacci Number

#include <stdio.h>

void main()
{
      int f1 = 0, f2 = 1, f3, n;
      printf("Program for Fibonacci Series\n");
      printf("Enter the maximum number for Fibonacci Series: ");
      scanf("%d", &n);
      printf("\nPrinting Fibonacci Series from 0 - %d\n", n);
      printf("%d\n%d\n", f1, f2);
      while(1)
      {
            f3 = f1 + f2;
            if(f3 > n)
                  break;
            printf("%d\n", f3);
            f1 = f2;
            f2 = f3;
      }
}

Output

Program for Fibonacci Series
Enter the maximum number for Fibonacci Series:
Printing Fibonacci Series from 0 - 1000
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987


22.

Finding Armstrong Number
Armstrong Numbers
   
Program for finding Armstrong number of a three digits number.

The condition for Armstrong number is,
Sum of the cubes of its digits must equal to the number itself.

For example, 407 is given as input.
4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407 is an Armstrong number.


Source Code

#include <stdio.h>

int main()
{
      int i, a, b, c, d;
      printf("List of Armstrong Numbers between (100 - 999):\n");

      for(i = 100; i <= 999; i++)
      {
            a = i / 100;
            b = (i - a * 100) / 10;
            c = (i - a * 100 - b * 10);

            d = a*a*a + b*b*b + c*c*c;

            if(i == d)
            {
                  printf("%d\n", i);
            }
      } 
      return 0;
}



Output

List of Armstrong Numbers between (100 - 999):
153
370
371
407


23.

Calculating Slope of a Line
Calculating Slope of a Line Given Two End Points

   
Program for Calculating Slope of a Line Given Two End Points

It uses the following formula given points are (x1,y1) and (x2, y2)

slope = (y2 - y1) / (x2 - x1)
Source Code
#include <stdio.h>
#include <math.h>

void main()
{
    float slope;
    float x1, y1, x2, y2;
    float dx, dy;

    printf("Program to find the slope of a line given two end points\n");

    printf("Enter X1: ");
    scanf("%f", &x1);

    printf("Enter Y1: ");
    scanf("%f", &y1);

    printf("Enter X2: ");
    scanf("%f", &x2);

    printf("Enter Y2: ");
    scanf("%f", &y2);

    dx = x2 - x1;
    dy = y2 - y1;

    slope = dy / dx;
    printf("Slope of the line with end points (%.4f, %.4f) and (%.4f, %.4f) = %.4f", x1, y1, x2, y2, slope);
}
Output

Program to find the slope of a line given two end points
Enter X1: 2.5
Enter Y1: 7.5
Enter X2: 12.5
Enter Y2: 18
Slope of the line with end points (2.5, 7.5 and (12.5, 18) = 1.05
Press any key to continue . . .



24.

Finding the equation
Finding the equation of a Line Given Two End Points

   
C program for finding the equation of a Line Given Two End Points (x1,y1) and (x2, y2)
The equation for a line is Y = MX + C
Where M = Slope of a Line and C = Intercept
To Find the slope of a line
slope = (y2 - y1) / (x2 - x1)
To Find the intercept of the line, intercept = y1 - (slope) * x1
which would be same as, intercept = y2 - (slope) * x2
Source Code
#include <stdio.h>
#include <math.h>

void main()
{
    float slope, intercept;
    float x1, y1, x2, y2;
    float dx, dy;

    printf("Program to find the equation of a line given two end points\n");

    printf("Enter X1: ");
    scanf("%f", &x1);

    printf("Enter Y1: ");
    scanf("%f", &y1);

    printf("Enter X2: ");
    scanf("%f", &x2);

    printf("Enter Y2: ");
    scanf("%f", &y2);

    dx = x2 - x1;
    dy = y2 - y1;

    slope = dy / dx;
    // y = mx + c
    // intercept c = y - mx
    intercept = y1 - slope * x1; // which is same as y2 - slope * x2

    printf("Equation of the line with end points (%.2f, %.2f) and (%.2f, %.2f) : Y = %.2fX %c %.2f\n", x1, y1, x2, y2, slope, (intercept < 0) ? ' ' : '+',  intercept);
}
Output

Program to find the equation of a line given two end points
Enter X1: 2
Enter Y1: 3
Enter X2: 5
Enter Y2: 7
Equation of the line with end points (2, 3 and (5, 7) : Y = 1.33333X +0.333333
Press any key to continue . . .




25.

Distance between the two points
C program for the Distance between the two points.

It uses the following formula give points are (x1,y1) and (x2, y2)

SQRT( (x2-x1) * (x2-x1) + (y2-y1) * (y2-y1) )


Source Code
#include <stdio.h>
#include <math.h>

void main()
{
    float distance;
    int x1, y1, x2, y2;
    int dx, dy;

    printf("Program for distance between the two points\n");

    printf("Enter X1: ");
    scanf("%d", &x1);

    printf("Enter Y1: ");
    scanf("%d", &y1);

    printf("Enter X2: ");
    scanf("%d", &x2);

    printf("Enter Y2: ");
    scanf("%d", &y2);

    dx = x2 - x1;
    dy = y2 - y1;

    distance = sqrt(dx*dx + dy*dy);
    printf("%.4f", distance);
}
Output

Program for distance between the two points
Enter X1: 10
Enter Y1: 10
Enter X2: 30
Enter Y2: 30
Distance between (10, 10) and (30, 30) = SQRT(800) = 28.2843



26.

Sum of ODD Numbers
Sum of ODD Numbers in the Given Range

Source Code
#include <stdio.h>

void main()
{
    int index, begno, endno, sum = 0;
    printf("Program for sum of odd numbers in the given range");

    printf("Enter Beg. No.: ");
    scanf("%d", &begno);
    printf("Enter End. No.: ");
    scanf("%d", &endno);
    index = begno;
    if( (begno % 2) == 0) // If it even, then make it ODD
        index = begno + 1;
    for(; index <= endno; index += 2)
    {
        sum = sum + index;
    }
    printf("The sum of odd numbers between %d and %d is: %d", begno, endno, sum);
}

Output

Program for sum of odd numbers in the given range
Enter Beg. No.: 1
Enter End. No.: 100
The sum of odd numbers between 1 and 100 is: 2500


27.

Sum of EVEN Numbers
Sum of EVEN Numbers in the Given Range
Source Code
#include <stdio.h>

void main()
{
    int index, begno, endno, sum = 0;
    printf("Program for sum of even numbers in the given range\n");

    printf("Enter Beg. No.: ");
    scanf("%d", &begno);
    printf("Enter End. No.: ");
    scanf("%d", &endno);
    index = begno;
    if( (begno % 2) == 1) // If it ODD, then make it EVEN
        index = begno + 1;
    for(; index <= endno; index += 2)
    {
        sum = sum + index;
    }
    printf("The sum of even numbers between %d and %d is: %d", begno, endno, sum);
}
Output

Program for sum of even numbers in the given range
Enter Beg. No.: 1
Enter End. No.: 100
The sum of even numbers between 1 and 100 is: 2550



28.

Sum of ALL Numbers
Sum of ALL Numbers in the Given Range
Source Code
#include <stdio.h>

void main()
{
    int index, begno, endno, sum = 0;
    printf("Program for sum of all numbers in the given range\n");

    printf("Enter Beg. No.: ");
    scanf("%d", &begno);
    printf("Enter End. No.: ");
    scanf("%d", &endno);
    index = begno;

    for(; index <= endno; index ++)
        sum = sum + index;
  
    printf("The sum of even numbers between %d and %d is: %d", begno, endno, sum);
}
Output

Program for sum of all numbers in the given range
Enter Beg. No.: 1
Enter End. No.: 100
The sum of even numbers between 1 and 100 is: 5050



29.


Program for the sum of 0 to N
Program for the sum of 0 - N using the formula n (n+1) / 2.


Source Code
#include <stdio.h>

void main()
{
    int N, sum = 0;
    printf("Program for sum of all numbers from 0 - N\n");

    printf("Enter N: ");
    scanf("%d", &N);
  
    sum = N * (N+1) / 2;
  
    printf("The sum of all numbers between 0 and %d is: %d", N, sum);
}
Output

Program for sum of all numbers from 0 - N
Enter N: 100
The sum of all numbers between 0 and 100 is: 5050



30.

Math Functions (Using COSINE Function)
Write a program to show the use of Math Functions.

Hints: We often use standard mathematical functions such as cos,sin,exp,etc. We shall see now the use of a mathematical function in a program. The standard mathematical functions are defined and kept as a part of C math library.

#include<math.h>
#define PI       3.1416
#define MAX       180
main()
{
 int angle;
 float x,y;
 angle = 0;
 printf("        Angle        Cos(angle)\n\n");

 while (angle <= MAX)
 {
   x = (PI / MAX) * angle;
   y = cos(x);
   printf("%15d  %13.4f\n", angle,y);
   angle = angle + 10;
  }
}


Output:

        Angle        Cos(angle)
               0         1.0000
              10         0.9848
              20         0.9397
              --            ----
              --            ----
              180       -1.0000



31.


Use of Subroutines
Write a program to show the use of subroutines

Hints: We have used only printf function that has been provided for us by the C system. The program below uses a user-defined function. A function defined by the user is equivalent to subroutine in FORTRAN or Subprogram in Basic.

main()
{
 int a,b,c;
 a=5;
 b=10;
 c=mul(a,b);
 printf("Multiplication of  %d and %d is %d", a,b,c);
 }

mul(x,y)
int p,x,y;
{
  p =x*y;
  return (p);
 }


32.

Interest Calculation
 Write a program which calculates the value of money at the end of each year of investment.

Hints:Assuming an interest rate of 11 percent and prints the year and the corresponding amount, in two columns. The output is shown in Fig.1.5 for a period of 10 years with an initial investment of 5000.00. The program uses the following formula:
value at end of year = Value at start of year (1+ interest rate)

#define PERIOD 10
#define PRINCIPAL 5000.00

main()

{
 int year;
 float amount,value,inrate;

 amount=PRINCIPAL;
 inrate = 0.11;
 year=0;

 while(year<=PERIOD)
   {
     printf("%2d        %8.2f\n",year,amount);
     value = amount+inrate*amount;
     year = year+1;
     amount = value;
   }

}


Output:

0        5000.00
1        5550.00
2        6160.50
-
-
-
-
-
-
-
10        14197.11




33.

Adding Two Numbers
Write a program which performs addition on two numbers and display the result.

main()
{
  int number;
  float amount;
  number=100;
  amount =30.75 +  75.35;
  printf("%d\n", number);
  printf("%5.2f",amount);
}


Output:
100

106.10



34.

Sum the Series
Write a C program to Calculate the below Series. The Value of x and n must take from input terminal.

 1.    Sum = x + x2 + x3 +…. +  xn

 2.   Sum = x + 2x + 3x +…. +  nx

 3.   Sum=x1 + x1/2 + x1/3  + ….  +  x1/n



#include

main()
{
int x, n, I, sum=0, y;

scanf("%d %d", &x, &n);
y=x;
for(I=1;I<=n;I++)
{
if(I==1)
{
printf("\n%d+", x);
}
else if(I==n)
{
printf("%d^%d = ", x, n);
}
else
{
printf("%d^%d+", x, I);
}
sum+=y;
y=y*x;
}
printf("%d", sum);

getch();
return 0;
}

                                                                                                                                                                 

#include

main()
{
int x, n, I, sum=0;

scanf("%d %d", &x, &n);
for(I=1;I<=n;I++)
{
if(I==1)
{
printf("\n%d+", x);
}
else if(I==n)
{
printf("%dx%d = ", n, x);
}
else
{
printf("%dx%d+", I, x);
}
sum+=I*x;
}
printf("%d", sum);

getch();
return 0;
}

                                                                                                                                                                 

#include

main()
{
int x, n, I;
float sum=0;

scanf("%d %d", &x, &n);
for(I=1;I<=n;I++)
{
if(I==1)
{
printf("\n%d+", x);
}
else if(I==n)
{
printf("%d^(1/%d) = ", x, n);
}
else
{
printf("%d^(1/%d)+", x, I);
}
sum+=pow(x, (1.0/I));
}
printf("%.2f", sum);

getch();
return 0;
}


35.

Perfect Number
1. Write a C program to Print 1st 30 Perfect numbers starting from 0

main()
{
long  i, sum=0, j, count=0;
for(j=1; ;j++)
{
for(i=1; i<=j/2 ; i++)
{
if( j%i = =0)
{
sum += i;
}
}
if(j = =sum)
{
printf("%d ", j);
count + + ;
}
if(count = =30)
{
break;
}
sum=0;
}

getch();
return 0;
}
Posted 26th August 2012 by JavaScriptFlavour
3
View comments


36.

Reverse an Integer Number
1. Write a C program to reverse an Integer number. After print the output, make the sum of all digits.

Sample Input:

Enter Number: 571

Output:

After Reverse: 175

Sum of all Digits: 13

Source:                                                                                                                                                           

main()
{
int num, i, sum=0;
scanf("%d", &num);
printf("After Reverse: ");
while(num!= 0)
{
  i = num%10;
  num /=10;
  sum += i;
  printf("%d", i);
}
printf("\n\nSum of all Digits: %d", sum);

getch();
return 0;
}



37.

Palindrom
1. Write a C program to check a Given Number, Whether  is it Palindrome or Not ?

Sample Input:

Enter Number: 123

Output:

It is not Palindrome


Sample Input:

Enter Number: 121

Output:

It is  Palindrome


2. Write a C program to Check a String, Whether is it Palindrome or Not ?

Sample Input:

Enter String: madam

Output:

It is  Palindrome

Sample Input:

Enter String: asian

Output:

It is not Palindrome


1.                                                                                                                                                               

main()
{
int num, i, rev=0, temp;
printf("Enter Number: ");
scanf("%d", &num);
temp=num;
while(temp!=0)
{
  i = temp%10;
  rev = rev*10+i ;
  temp /= 10;
}
if(num = =rev)
  {
    printf("It is a Palindrome.\n");
  }
    else
  {
    printf("It is not a Palindrome.\n");
  }

getch();
return 0;
}


38.


Manipulate Series
1. Write a C program to print a Series of Integer Numbers,which is divisible by 3 from a given set of limits.

Sample Input:

Start_value: 1
End_value: 10

Sample Output:

3, 6, 9

2. Write a C program to print a Series of Odd Numbers and Even Numbers. After Print Make an Average of all Printed Odd Numbers and Even Numbers.

Sample Output:

The Even Numbers are: 2, 4, 6, 8, 10
The Odd Numbers are: 1, 3, 5, 7, 9

The Average of Even Numbers: 6


1.                                                                                                                                                                 


main()
{
int start, end, i ;

printf("Start_Value: ");
scanf("%d", &start);
printf("End_Value: ");
scanf("%d", &end);
printf("\n\n");
for(i=start ; i <= end ; i++)
{
if(i%3 = = 0)
printf("%d, ", i );
}

getch();
return 0;
}

2.                                                                                                                                                                 
main()
{
int i,sumeven=0, sumodd=0, even=0, odd=0;
float aveeven, aveodd;
printf("The Even Numbers are: ");
for(i=1;i<=15;i++)
{
if(i%2==0)
{
printf("%d, ",i);
sumeven+=i;
even++;
}
}
printf("\n\nThe Odd Numbers are: ");
for(i=1;i<=15;i++)
{
if(i%2!=0)
{
printf("%d, ",i);
sumodd+=i;
odd++;
}
}
aveeven=(float)(sumeven)/even;
aveodd=(float)(sumodd)/odd;
printf("\n\nThe Average of Even Numbers: %.2f", aveeven);
printf("\n\nThe Average of Odd Numbers: %.2f", aveodd);

getch();
return 0;
}

39.

Strange Number
1.Write a C program to Print the Strange Numbers Between 1 and 100000.

main()
{
int a, b, c, n, temp, J;

printf("The Strange Numbers are:\n\t\t");
for(a=1;a<=100000;a++)
{
c=1;
for(b=2;b<=a/2;b++)
{
if(a%b==0)
{
c=0;
break;
}
}
if(c==1)
{
temp=a;
while(temp>0) //starting the loop for extract the number
{
J=temp%10;
n=1;
for(b=2;b<=J/2;b++) //loop for checking the digit whether is it prime or not.
{
if(J%b = =0)
{
n=0;
break;  //skip the 'for loop'
}
}
if((n= =0)||(J= =0))
{
n=0;
break; //skip the 'while loop'
}
temp /=10;
}  //loop for extract finish
if(n= =1)
{
printf("\t%d", a);
}
}
}

getch();
return 0;


40.


Prime Number Manipulation
1. Write a C program to calculate the SUM and COUNT of Primes from a given range of numbers. Formatting required for the Input and Output statements.

Sample Input:

Range Start From: 1
End of Range: 10

Sample Output:

The Sum of Primes is: 11
Total Primes: 5

2. Write a C Program to Print all the Prime Numbers between 1 and 100.

Sample Output:

1,  2,  3,  5,  7,  11,  13,  . . . . etc


1.                                                                                                                                                                

main()
{
int a, b, c, n=0, start, end, sum=0;
printf("Range Start From: ");
scanf("%d", &start);
printf("End of Range: ");
scanf("%d", &end);

for(a=start;a<=end;a++)
{
c=1;
for(b=2;b<=a/2;b++)
{
if(a%b==0)
{
c=0;
break;
}
}
if(c==1)
{
sum+=a;
n++;
}
}
printf("The Sum of Primes is: %d\nTotal primes: %d", sum, n);
getch();
return 0;
}

2.                                                                                                                                                                 

main()
{
int a, b, c;

for(a=1;a<=100;a++)
{
c=1;
for(b=2;b<=a/2;b++)
{
if(a%b==0)
{
c=0;
break;
}
}
if(c==1)
{
printf("%d\t", a);
}
}
getch();
}


41.


Arithmatic Operation
Write and run a program that reads a six digit integer and prints the sum of its six digits. Use the quotient operator(/) and the remainder operator(%) to extract the digit from the integer. For example, if N is the integer 876543 then n/1000%10 is its thousands digit 6.

Posted 25th July 2012 by JavaScriptFlavour
6
View comments

    Md. Mahfuzur RahmanJuly 25, 2012 at 11:09 PM

    #include
    main()
    {
    int i, j, n=100000, sum=0;
    while(scanf("%d", &i)==1)
    {
    while(i>0)
    {
    j=i/n;
    i=i%n;
    n=n/10;
    sum+=j;
    }
    printf("%d\n", sum);
    sum=0;
    n=100000;
    }
    return 0;
    }



42.


Conditional Expression
Write and run a program that reads two integers and then uses the conditional expression operator to print either "Multiple" or "Not" according to whether one of the integers is a multiple of the other.
Posted 25th July 2012 by JavaScriptFlavour
2
View comments

    Md. Mahfuzur RahmanJuly 25, 2012 at 11:11 PM

    #include

    main()
    {
    int a, b;
    while(scanf("%d %d", &a, &b)==2)
    {
    if(a%b==0||b%a==0)
    {
    printf("Multiple\n");
    }
    else
    {
    printf("Not\n");
    }
    }
    return 0;
    }
    Reply
43.



Comparison Operator
Write and run a program that reads the users age and then prints "You are a Child" if the age < 18, " You are an adult." if 18<=age<65, and "You are a senior citizen." if age >=65.
Posted 25th July 2012 by JavaScriptFlavour
4
View comments

    sourav mahmudJuly 25, 2012 at 9:19 AM

    #include
    #include
    main()
    {
    int age;
    printf("enter your age: ");
    scanf("%d",&age);
    if(age<18)
    printf("you are child");
    else if(18<=age<=65)
    printf("you are adult");
    else if(age>65)
    printf("you are senior citizen");
    getch();


44.

Array programming
Write a C Program to fill up an Integer Array. The length of the array must take from the terminal. After fill up the array do the following operations.
i)                    Print the array with label formatting.
ii)                   Count the number of values inside the array.
iii)                 Count the number of odd values.
iv)                 Count the number of even values.
v)                  Sum all the odd values.
vi)                 Sum all the even values.
vii)               Calculate the average.
viii)              Find the largest value.
ix)                 Find the smallest value.
Posted 24th July 2012 by JavaScriptFlavour
5
View comments

    Md. Mahfuzur RahmanJuly 25, 2012 at 1:43 AM

    This comment has been removed by the author.
    Reply
    Md. Mahfuzur RahmanJuly 25, 2012 at 11:37 PM

    I have written a code of this program. The code is too long. This frame is unable to show the code at a time.
    Reply
    A.K.M AshrafuzzamanJuly 26, 2012 at 8:35 AM

    you can write main body as accepted as here...
    Reply
    A.K.M AshrafuzzamanAugust 5, 2012 at 12:53 PM

    #include
    main()
    {
    int i, a[10],value,count=0,sum1=0,sum2=0,max=0,min=32678;
    float avg=0,sum=0;
    printf("Enter your enteger value:\n");
    for(i=0;i<10;i++)
    {
    scanf("%d",&value);
    a[i]=value;
    printf("[%d]=%d\n",i,a[i]);
    }
    for(i=0;i<10;i++)
    {
    count+=a[i];
    }
    printf("\n Sum inside array number:%d",count);
    for(i=0;i<10;i++)
    {
    if(a[i]%2==0)
    {
    printf("\n\n Even numberis:%d",a[i]);
    }
    }
    for(i=0;i<10;i++)
    {
    if(a[i]%2!=0)
    {
    printf("\n\n Odd numberis:%d",a[i]);
    }
    }
    for(i=0;i<10;i++)
    {
    if(a[i]%2==0)
    {
    sum1+=a[i];
    }
    }
    printf("\n Sum of even number:%d",sum1);
    for(i=0;i<10;i++)
    {
    if(a[i]%2!=0)
    {
    sum2+=a[i];
    }
    }
    printf("\n sum of Odd number:%d",sum2);
    for(i=0;i<10;i++)
    {
    sum+=a[i];
    }
    avg=sum/10;
    printf("\n avg=%.2f",avg);
    for(i=0;i<10;i++)
    {
    if(a[i]>max)
    {
    max=a[i];
    }
    }
    printf("\nLargest value:%d",max);
    for(i=0;i<10;i++)
    {
    if(a[i]<min)
    {
    min=a[i];
    }
    }
    printf("\nsmallest value:%d",min);
    getch();
    Reply


45.

Write a C program to find the Simple Interest. Take input for principle amount, rate of interest and time from terminal

Write a C program to find the Simple Interest. Take input for Principle Amount, Rate of Interest and Time from terminal.

Simple Interest is the money paid by the borrower to the lender, based on the Principle Amount, Interest Rate and the Time Period.

Simple Interest is calculated by, SI= P * T * R / 100 formula.

Where, P is the Principle Amount.
T is the Time Period.
R is the Interest Rate.
Definition of 'Simple Interest' from WEB
A quick method of calculating the interest charge on a loan. Simple interest is determined by multiplying the interest rate by the principal by the number of periods.
Simple Interest = P x I x N


Where:

P is the loan amount
I is the interest rate
N is the duration of the loan, using number of periods
Explanation of 'Simple Interest'
Simple interest is called simple because it ignores the effects of compounding. The interest charge is always based on the original principal, so interest on interest is not included.  This method may be used to find the interest charge for short-term loans, where ignoring compounding is less of an issue.
Posted 17th July 2012 by JavaScriptFlavour
11
View comments

    MAHADI HASANJuly 17, 2012 at 3:31 AM

    #include
    #include
    void main()
    {
    int p,t;
    float r;
    float SI;
    printf("\nEnter the Principle Amount, Terms, Rate of Interest :");
    scanf("%d%d%f",&p,&t,&r);
    printf("\nThe Simple Interest for the Principle \nAmount %d for %d Years with an Interest of %0.2f",p,t,r);
    SI=((p * t * r) / 100);
    printf("\n is %5.0f.",SI);

    getch();
    }
    By Mahadi.
    Reply


46.


Write a program performing as calculator which allows all Arithmetic Operators

1. Write a program performing as calculator which allows all Arithmetic Operators. Few Input and Output sample are given below:
          
Sample Input: 1 + 4
            Sample Output: 5

            Sample Input: 8 % 2
            Sample Output: 0

            Sample Input: 6 / 2
            Sample Output: 3

            Sample Input: 5 / 2
            Sample Output: 2.5

Posted 26th June 2012 by JavaScriptFlavour
28
View comments

    WRONG BUZZJuly 15, 2012 at 8:48 AM

    #include
    #include
    main()
    {
    int a,b,z,x,w,h;
    char c;
    float y,m=0.0;

    printf("\nWelcome To My Calculator\n");
    AB:
    printf("\nenter to calculate (Ex:2+2)\n");
    scanf("%d%c%d",&a,&c,&b);
    z=(a+b);
    x=(a*b);
    w=(a-b);
    h=(a%b);
    y=(a/b);
    m=y;
    switch(c)
    {
    case '+' : printf("%d+%d=%d",a,b,z);
    break;
    case '-' : printf("%d-%d=%d",a,b,w);
    break;
    case '*' : printf("%d*%d=%d",a,b,x);
    break;
    case '/' : printf("%d/%d=%2.3f",a,b,m);
    break ;
    case '%' : printf("%d %d=%d",a,b,h);
    break ;
    default : printf("error syntax");
    break ;
    }
    goto AB;
    getch();
    }
    By Mahadi.
    Reply
    return 0;
    }