Posts

Showing posts from February, 2013

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); }

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.

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); }

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);

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); }

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); }

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); }

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); }

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); }

Switch Case

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 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++;     }     prin

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)

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

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 numbe

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                     *                    ***                   *****