Wednesday 13 February 2013

How to make a digital clock using C

The following code creates a digital clock using a 1 sec. delay. <time.h> provides various functions to delay the time.
Source Code:
#include <stdio.h>
#include <time.h>
#include <windows.h>
COORD coord = {0, 0};
void gotoxy (int x, int y)
{
    coord.X = x; coord.Y = y; // X and Y coordinates
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}
void showClock(int x_1, int x_2, int x_3,int y){
    long i = 0;                      /* Loop counter              */
    clock_t now = 0;                 /* Holds initial clock time  */
    int interval = 1;                /* Seconds interval for o/p  */
    int elapsed = 0;
    int min=0,MIN=0,hrs=0,sec=0;
    int d=0,f=0;
    now = clock();
    /* Get current clock time    */
    for(i = 0L ;  ; i++){
        elapsed = (clock()-now)/CLOCKS_PER_SEC;
        if(elapsed>=interval){
            interval += 1;
            if(elapsed%60==0){
                min=elapsed/60;
                d=60*min;
                if(min%60==0){
                    hrs=min/60;
                    f=60*hrs;
                }
            }
            sec=elapsed-d;
            MIN=min-f;
            if(hrs<10){
                gotoxy(x_1,y);printf("0%d",hrs);
            }else{
                gotoxy(x_1,y);printf(":%d",hrs);
            }
            if(min<10){
                gotoxy(x_2,y);printf(":0%d",MIN);
            }else{
                gotoxy(x_2,y);printf(":%2d",MIN);
            }
            if(sec<10){
                gotoxy(x_3,y);printf(":0%d",sec);
            }else{
                gotoxy(x_3,y);printf(":%2d",sec);
            }
        }
    }
}
int main()
{
    showClock(2,4,7,4);
 return 0;
}

Output:

clock

How to disable the close button of console using C

The code for making the close button  disabled is given below. It disables the close button and hence user cannot close console. But one can close console using Task Manager.
#define _WIN32_WINNT 0x0500
#include <stdio.h>
#include <windows.h>
int main(int argc, _TCHAR* argv[])
{
    HWND h;
    HMENU sm;
    int i, j, c;
    LPTSTR buf;
    // get the handle to the console
    h = GetConsoleWindow();
    // get handle to the System Menu
    sm = GetSystemMenu(h, 0);
    // how many items are there?
    c = GetMenuItemCount(sm);
    j = -1;
    buf = (TCHAR*) malloc (256 *sizeof(TCHAR));
    for (i=0; i<c; i++) {
        // find the one we want
        GetMenuString(sm, i, buf, 255, MF_BYPOSITION);
        if (!strcmp(buf, "&Close")) {
            j = i;
            break;
        }
    }
    // if found, remove that menu item
    if (j >= 0)
        RemoveMenu(sm, j, MF_BYPOSITION);
    return 0;
}

How to resize the console window using C

The code for resizing the console window is given below
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
HANDLE wHnd;    // Handle to write to the console.
HANDLE rHnd;    // Handle to read from the console.
int main(int argc, char* argv[]) {
    // Set up the handles for reading/writing:
    wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
    rHnd = GetStdHandle(STD_INPUT_HANDLE);
    // Change the window title:
    SetConsoleTitle("Advanced C tutorial - programming-technique.blogspot.com");
    // Set up the required window size:
    SMALL_RECT windowSize = {0, 0, 50, 10};
    SetConsoleWindowInfo(wHnd, 1, &windowSize);
    // Change the console window size:
        // Create a COORD to hold the buffer size:
    COORD bufferSize = {10, 10};
    SetConsoleScreenBufferSize(wHnd, bufferSize);
    // Exit
    return 0;
}

How to move console from one position to another using C

<windows.h> provides a function MoveWindow() to move the console from one position to another. It requires 6 parameters. The source code is given below.
#include<windows.h>
#include<stdio.h>
HWND WINAPI GetConsoleWindowNT()
{
    // declare function pointer type
    typedef HWND WINAPI (*GetConsoleWindowT)(void);
    // declare one such function pointer
    GetConsoleWindowT GetConsoleWindow;
    // get a handle on kernel32.dll
    HMODULE hK32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));
    // assign procedure address to function pointer\
    GetConsoleWindow = (GetConsoleWindowT)GetProcAddress(hK32Lib,TEXT("GetConsoleWindow"));
    // check if the function pointer is valid
    // since the function is undocumented
    if ( GetConsoleWindow == NULL ) {
         return NULL;
    }    // call the undocumented function\
    return GetConsoleWindow();
}
int main(){
    CONSOLE_SCREEN_BUFFER_INFO SBInfo;
    HWND hWnd = GetConsoleWindowNT();
    SetConsoleTitle("Programming-technique- Tutorial");
    MoveWindow(hWnd,950,500,400,200,TRUE);
    printf("Hello Every One\nThis is small window ");
    getch();
    return 0;
}

How to do Multithreading using C/C++

Multithreading is necessary for those programs which need to run two or more processes within a single program simultaneously. For example: when you play a game( say Mario)  in a computer, then you see two or more enemies are moving at the same time  or in case of Football game two or more than two players are moving at the same time. This phenomena is called Multithreading. In multithreading total time for a program is divided into small fraction of time, and at one fraction of time only one process runs. But the switching  time between one process to another is so small that our eyes cannot detect the difference between processes. This can be illustrated with the analogous of Tube Light. Suppose the frequency of voltage is 50Hz. Then a tube light which operates by an Alternating Current, lights on 50 times and lights off 50 times in a second. But we see it as if it is continuously glowing. In the similar way, a single process runs in a single time but we see as if all processes are running at the same time.
Honestly speaking C and C++ do not support multithreading themselves so far ( Note: C++0x is releasing soon which supports Multithreading) . But we can use  windows.h with C and C++ program which has functions for Multithreading. So for Linux user this tutorial won’t help you.  Lets discuss how to do a multithreading in windows with C and C++.
First of all you have to include windows.h in your program by writing #include<windows.h> at the beginning of the program. Then you declare the handles to handle the threading.
HANDLE hThread1;
HANDLE hThread2;

Declare the handles as many as your threading. I have two process so I declare two handles. To begin the threading, we have function as given below
hThread1 = (HANDLE) _beginthread(func1, 0, 0);
hThread2 = (HANDLE) _beginthread(func2, 0, 0);

_beginthread requires three arguments. First argument is function which you want to thread. The two other arguments are generally 0. So both functions func1 and func2 are executed at a single time.

If threading completes then thread can be ended by using function _endthread().

The complete source code for a example of threading and its source code is given below:

Source Code:
#include<stdio.h>
#include<conio.h>
#include<windows.h>
void massage1(int *param){
    int i = 0;
    while(1){
        printf("\nFrom function 1 i = %d", i);
        Sleep(1000);
        i++;
    }
    _endthread();
}
void massage2(int *param){
    int j = 0;
    while(1){
        printf("\nFrom function 2 j = %d", j);
        Sleep(1000);
        j++;
    }
    _endthread();
}
int main(){
    HANDLE handle1;
    HANDLE handle2;
    printf("Press any key to begin and end thread");
    getch();
    printf("\nThreading Begins");
    handle1 =  (HANDLE) _beginthread(massage1,0,0);
    handle2 =  (HANDLE) _beginthread(massage2,0,0);
    getch();
    printf("\nThreading Ends");
    return 0;
}

Output:

thread

Numerical method : Solution of ordinary differential equation using RK4 method in C

Algorithm:
  1. Start
  2. Declare and Initialize necessary variable likes K1, K2, K3, K4 etc.
  3. Declare and define the function that returns the functional value.
  4. Get the initial value of x, initial value of y, no. of iteration and interval from user.
  5. for i = 0 to i < n go to step 6.
  6. Do the following calculation: and go to step 7 RK_4
  7. The new values of x and y are: x = x + interval, y = y + K;
  8. print the value of x and y;
  9. stop
Flowchart:
RK_4flow


Source Code:

float func(float x, float y){
    return (y*y-x*x)/(y*y+x*x);
}
int main(){
    float K, K1, K2, K3, K4;
    float x0 , y0, x, y;
    int j, n; float i, H;
    printf("Enter initial value of x: ");
    scanf("%f", &x0);
    printf("Enter initial value of y: ");
    scanf("%f", &y0);
    printf("Enter no iteration: ");
    scanf("%d", &n);
    printf("Enter the interval: ");
    scanf("%f", &H);
    x = x0;
    y = y0;
    for(i = x+H, j = 0; j < n; i += H, j++){
        K1 = H * func(x , y);
        K2 = H * func(x+H/2, y+K1/2);
        K3 = H * func(x+H/2, y+K2/2);
        K4 = H * func(x+H, y+K3);
        K = (K1 + 2*K2 + 2*K3 + K4)/6;
        x = i;
        y = y + K;
        printf("At  x = %.2f, y = %.4f ", x, y);
        printf("\n");
    }
    return 0;
}

Output

RK4

Numerical Methods: Solution of non-linear equations by using Bisection method in C

Algorithm:
  1. Declare and initialize necessary variables like up_range, mid, low_range etc.
  2. Read the range( upper and lower)  from user within which the root of the equation  is to be calculated.
  3. If root lies within the range? if yes: go to step 4. if no: go to step 2
  4. Calculate the mid value of upper and lower range, mid = (upper+lower)/2
  5. Calculate the functional value at mid i.e. func(mid).
  6. If func(mid)*func(low_range) is less than zero, then replace upper range by mid else replace lower range by mid
  7. Display the no of iteration and root
  8. if func(mid) is very small? yes: go to step 9. No: go to step 4
  9. Display the value of most closest and accurate root.
Source Code:
#include<stdio.h>
#include<math.h>
//function that returns the functional value
float func(float x){
    return (pow(x,3)+5*pow(x,2)-7);
}
int main(){
    float up_range, low_range, mid;
    int i = 0; //no of iteration
    printf("Enter the range: ");
    scanf("%f%f",&up_range,&low_range);
    while(func(up_range)*func(low_range) > 0){ //repeatadly read until the range has root
        printf("\nThis range doesnot contains any root");
        printf("\nEnter again the range: ");
        scanf("%f%f",&up_range,&low_range);
    }
    do{
        mid = (up_range + low_range) / 2;
        if(func(low_range) * func(mid) < 0){ //if signs of mid and low_range is
            up_range = mid;                  //different, replace up_range by mid
        }else{ //else raplace, low_range by mid
            low_range = mid;
        }
        i++;
        printf("\nAt iteration: %d, root = %f",i,mid);
    }while(fabs(func(mid))> 0.0001);
    printf("\nThe root of the equation is %f", mid);
    return 0;
}

Output:
bisection

Numerical Methods: Solution of non-linear equation using Newton Raphson method in C

Source Code:
///solution of non-linear  equation using Newton Raphson Method
#include<stdio.h>
#include<math.h>
float f(float x){
    return (pow(x,3) + 5*pow(x,2) -7);
}
float df(float x){
    return (3*pow(x,2) + 10*x );
}
int main(){
    float x0, x1, x2;
    int count = 0;
    printf("Enter the initial guess: ");
    scanf("%f", &x0);
    while(1){
        x1 = x0 - f(x0)/df(x0);
        count++;
        if(x0==x1){
            break;
        }
        x0 = x1;
    }
    printf("The root after %d iteration is %.3f",count, x0);
    return 0;
}

Numerical Methods: Solution of non-linear equation by using Secant method in C

Source Code:
///solution of non linear equations using secant method
#include<stdio.h>
#include<math.h>
float f(float x){
   return (pow(x,5) - 3*pow(x,3)-1);
}
int main(){
    float a, b, c;
    int count = 0;
    printf("Enter the initial value of a: ");
    scanf("%f", &a);
    printf("Enter the initial value of b: ");
    scanf("%f", &b);
    while(1){
         count++;
            c = (a*f(b)-b*f(a))/(f(b)-f(a));
         if(c==b){
            break;
         }
         if(count>=20){
            break;
         }
         a = b;
         b = c;
    }
    printf("\nThe root after %d iteration is %.7f\n",count, c);
    return 0;
}

Numerical Methods: Interpolation with unequal interval with Lagrange’s method in C

Source Code:
///Interpolation with unequal intervals with Lagrange's Formula
#include <stdio.h>
#include <math.h>
#include <windows.h>
COORD coord = {0, 0};
void gotoxy (int x, int y)
{
        coord.X = x; coord.Y = y; // X and Y coordinates
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main(){
    float ax[20], ay[20], xp, yp = 0, dr, nr;
    int no_data, i, j;
    printf("How many data? ");
    scanf("%d", &no_data);
    printf("Enter Data: ");
    for(i =0; i < no_data; i++){
        gotoxy(1,2+i); printf("X%d: ", i+1);
        scanf("%f", &ax[i]);
        gotoxy(10, 2+i);printf("Y%d: ", i+1);
        scanf("%f", &ay[i]);
    }
    printf("\nEnter value of x to find corresponding y ");
    scanf("%f", &xp);
    for(i = 0; i < no_data; i++){
        dr = 1;
        nr = 1;
        for(j = 0; j<no_data; j++){
            if(i!=j){
                nr *= xp - ax[j];
                dr *= ax[i] - ax[j];
            }
        }
        yp += nr/dr*ay[i];
    }
    printf("\nrequired value of y is: %f", yp);
    return 0;
}

Numerical Methods:Fitting the curve of the form y = a + bx using least square method in C

///Curve fitting of a straight line of the form y = a + bx
#include<stdio.h>
#include<math.h>
int main(){
    int ax[20], ay[20], i, n;
    int sum_x = 0, sum_xy = 0, sum_x2 = 0, sum_y = 0 ;
    float a , b;
    printf("Enter no of records: ");
    scanf("%d", &n);
    printf("Enter Data: ");
    printf("\nX       Y\n");
    for(i = 0; i < n; i++){
        scanf("%d%d", &ax[i], &ay[i]);
    }
    for(i = 0; i < n; i++){
        sum_x += ax[i];
        sum_y += ay[i];
        sum_xy += ax[i] * ay[i];
        sum_x2 += pow(ax[i], 2);
    }
    b = (n*sum_xy - sum_x*sum_y)/(n*sum_x2 - pow(sum_x,2));
    a = (sum_y - b*sum_x)/n;
    printf("\na = %.3f    b = %.3f", a, b);
    printf("\nThe Equation is %.3f + %.3fX\n\n", a, b);
    return 0;
}

Numerical Methods: Solution of simultaneous algebraic equations using Gauss Elimination method in C

#include<stdio.h>
int main()
{
    double matrix[10][10],a,b, temp[10];
    int  i, j, k, n;
    printf("Enter the no of variables: ");
    scanf("%d", &n);
    printf("Enter the agumented matrix:\n");
    for(i = 0; i < n ; i++){
        for(j = 0; j < (n+1); j++){
            scanf("%lf", &matrix[i][j]);
        }
    }
    for(i = 0; i < n; i++){
       for(j = 0; j < n; j++){
           if(j>i){
                a = matrix[j][i];
                b = matrix[i][i];
                for(k = 0; k < n+1; k++){
                    matrix[j][k] = matrix[j][k] - (a/b) * matrix[i][k];
                }
            }
       }
    }
    printf("The Upper triangular matrix is: \n");
    for( i = 0; i < n; i++){
        for(j = 0; j < n+1; j++){
            printf("%.2f", matrix[i][j]);
            printf("\t");
        }
        printf("\n");
    }
    printf("\nThe required result is: ");
    for(i = n-1; i>=0; i--){
        b = matrix[i][n];
        for(j = n-1 ; j > i; j--){
            b -= temp[n-j]*matrix[i][j];
        }
        temp[n-i] = b/matrix[i][i];
        printf("\n%c => %.2f",97+i, temp[n-i]);
    }
}

Numerical Methods: Solution of simultaneous algebraic equations using Gauss Jordan method in C

#include<stdio.h>
int main()
{
    double matrix[10][10],a,b;
    int  i, j, k, n;
    printf("Enter the no of variables: ");
    scanf("%d", &n);
    printf("Enter the agumented matrix:\n");
    for(i = 0; i < n ; i++){
        for(j = 0; j < (n+1); j++){
            scanf("%lf", &matrix[i][j]);
        }
    }
    for(i = 0; i < n; i++){
       for(j = 0; j < n; j++){
            if(i != j){
                a = matrix[j][i];
                b = matrix[i][i];
                for(k = 0; k < n+1; k++){
                    matrix[j][k] = matrix[j][k] - (a/b) * matrix[i][k];
                }
            }
        }
    }
    for(i = 0; i < n; i++){
         a = matrix[i][i];
        for(j = 0; j < n+1; j++){
            matrix[i][j] /= a;
        }
    }
    printf("The required solution is: \n\n");
    for(i = 0; i < n ; i++){
        printf("%c => %.2f", i+97, matrix[i][n]);
        printf("\n");
    }
    return 0;
}

Numerical Methods: Determinant of nxn matrix using C

Source Code:
#include<stdio.h>
int main(){
    float  matrix[10][10], ratio, det;
    int i, j, k, n;
    printf("Enter order of matrix: ");
    scanf("%d", &n);
    printf("Enter the matrix: \n");
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            scanf("%f", &matrix[i][j]);
        }
    }
    /* Conversion of matrix to upper triangular */
    for(i = 0; i < n; i++){
        for(j = 0; j < n; j++){
            if(j>i){
                ratio = matrix[j][i]/matrix[i][i];
                for(k = 0; k < n; k++){
                    matrix[j][k] -= ratio * matrix[i][k];
                }
            }
        }
    }
    det = 1; //storage for determinant
    for(i = 0; i < n; i++)
        det *= matrix[i][i];
    printf("The determinant of matrix is: %.2f\n\n", det);
    return 0;
}