Desktop Programming > C/C++ & Visual C++

New thread especially for students of C and C++

<< < (2/11) > >>

David:
Here is a simple approach to dates ... coded in C++ (that wouldn't fit in the 'date' section above) ...


--- Code: ---// Find number of days from 1900-01-01 ...

#include <iostream>
#include <iomanip>

using namespace std;

const int daysInYear[ ] = {0,31,59,90,120,151,181,212,243,273,304,334,365};

bool more()
{
    cout << "\nMore (y/n) ? " << flush;
    char reply;
    cin.clear();
    cin.sync();
    reply=cin.get();
    cin.sync();
    return !(reply=='n' || reply=='N');
}

long toHrs( long days )
{
    return days*24;    
}

long toMins( long days )
{
    return days*24*60;
}

long long toSecs( long days )
{
    return ((long long)days)*24*3600;
}


int main ()
{
    long yr, mo, da, years, days;
    char c;
    
    cout << "This program reads a date and finds\n"
         << "the number of inclusive days since 1900-01-01.\n"
         << "Results valid in date range 1900-01-01 to 2099-12-31.\n";
    do
    {
        cout << "\nEnter a valid 'test' date yyyy-mm-dd : ";
        cin >> yr >> c >> mo >> c >> da;
    
        // first find the whole years that have passed ...
        years = yr-1900;
        
        // convert this to days ...adding one day for each leap year that has passed
        // note 1900 was NOT a yeap year but 2000 WAS a leap year ... so ...
        days = years*365 + years/4;
        
        // now add on the days for the whole months that have passed ...
        days = days + daysInYear[ mo-1 ];
        
        // now add on the days in this month that have passed ...
        days = days + da;
        
        // if in a leap year & if before March, correct for the already added day
        if( yr%4==0 && mo<3 && yr!=1900 ) --days;
        
        cout << "The number of inclusive days from 1900-01-01 to "
             << yr << "-" << setfill('0') << setw(2) << mo << "-"
             << setw(2) << da << " is " << days << ".\n"
             << "Or at midnight, " << toHrs(days) << " hours or "
             << toMins(days) << " minutes or " << toSecs(days) << " seconds.\n";
    
    }while( more() );
}
--- End code ---


And here is a common student date problem ... printout a calander for any month in a year from ...? to ...?

Coded here in C ...


--- Code: ---/*
    Print a calendar from 1600 to 9999
    
    For calibration ref. see ...
    http://www.nr.com/julian.html
*/

#include <stdio.h>

#define HEADER "This program prompts the user to enter a month and a year\n" \
                "and generates a calendar for that period. For example ...\n" \
                "Enter month : 5\n" \
                "Enter year  : 2018\n\n" \
                "Su  M Tu  W Th  F Sa\n" \
                "       1  2  3  4  5\n" \
                " 6  7  8  9 10 11 12\n" \
                "13 14 15 16 17 18 19\n" \
                "20 21 22 23 24 25 26\n" \
                "27 28 29 30 31\n"

#define HEADER_CAL "Su  M Tu  W Th  F Sa"

/*
    This function asks the user to ...
    Enter month : 5
    Enter year  : 2018
    
    And returns, by reference, month and year entered
    Note: Allows only valid input ... month range 1..12, year range 1900..9999
*/
void enterMonthYear(int *month, int *year)
{
    int numGood;
    for( ;; ) /* loop forever ... until break */
    {
        printf("Enter month : ");
        if( (numGood=scanf("%d", month))!=1 || *month<1 || *month>12 )
        {
            while( getchar() != '\n' ) ; /* flush stdin */
            printf("Valid months are 1..12  ");
        }
        else
        {
            while( getchar() != '\n' ) ; /* flush stdin */
            break;
        }
    }

    for( ;; )
    {
        printf("Enter year  : ");
        if( (numGood=scanf("%d", year))!=1 || *year<1600 || *year>9999 )
        {
            while( getchar() != '\n' ) ; /* flush stdin */
            printf("Valid years are 1600..9999  ");
        }
        else
        {
            while( getchar() != '\n' ) ; /* flush stdin */
            break;
        }
    }
}

/* returns 1 if leap year, else returns 0 */
int isLeapYear( int year )
{
    if(year%4 != 0) return 0;  /* not a leap year */
    if(year%100 == 0 && year%400 != 0) return 0; /* not a leap year */
    return 1;
}

/* returns the number of days for a month in any year 1900..9999*/
int daysInMonth(int month, int year)
{
    int days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    if( month==2 && isLeapYear(year) ) return days[month] +1;
    else return days[month];
}

/* returns day number for any day and month in any year 1600..9999 */
int getDayNum(int month, int day, int year)
{
    int dayNum = 0;
    int monthNum;
    for( monthNum=1; monthNum<month; ++monthNum)
        dayNum += daysInMonth(monthNum, year);
    dayNum += day;
    return dayNum;
}

/* returns the number of days from 1/1/1600 to the end of the previous 'year' */
long yearsToDays(int year)
{
    int numDays =0;
    int yearNum;
    for(yearNum=1600; yearNum<year; ++yearNum)
        numDays += 365 + isLeapYear(yearNum);
    return numDays;
}

/*
    Outputs the calendar to the screen ...
    'startDay' says which day of the week is the first of the month
    (0 is Sunday, 1 is Monday, etc...)
    'numDays' is how many days in the month
*/
void printCalendar(int startDay, int numDays)
{
    int i;
    puts(HEADER_CAL);
    
    for(i=0; i<startDay; ++i)
        printf("   ");

    for(i=1; i<= numDays; ++ i)
    {
        printf("%2d ", i );
        if( i< numDays && (i+startDay)%7 == 0 ) puts("");
    }
}

/* defaults to 'yes' */
int more()
{
    char c, reply;
    printf("\n\nMore (y/n) ? ");
    reply=c=getchar();
    while( c != '\n' ) c = getchar(); /* flush stdin */
    return !(reply=='n' || reply=='N');
}


int main()
{
    int month, year, startDay;
    puts( HEADER );
    
    do
    {
        enterMonthYear( &month, &year );
/*
        printf("\n%d %s a leap year.\n",
                year, isLeapYear(year) ? "is" : "is not");
        
        printf("\nDay 1 of the %d month of year %d is day number %d\n",
                month, year, getDayNum(month, 1, year) );
                
        printf("\nNumber of days from 1600/01/01 to the end of the year %d is %d\n",
                year-1, yearsToDays(year) );
*/
        /* 2305448 1600/01/01 was a Saturday; 2415021 1900/01/01 was a Monday */
        startDay = (5 + yearsToDays(year) + getDayNum(month, 1, year)) % 7;
/*
        printf("\nStart day for month %d and year %d is %d\n",
                month, year, startDay +1\ );
*/
        printf("\nYour calender for month %d and year %d is ...\n\n", month, year);
        printCalendar(startDay, daysInMonth(month, year));

    }while( more() );

    return 0;
}
--- End code ---

You may also like to check this student help link for an example of todays local date and time in C/C++ :

http://www.dreamincode.net/forums/index.php?showtopic=64722&st=0&p=422833&#entry422833

David:
Back to pointers ... in C ...

Here is a mini-tutorial on arrays in C ...


--- Code: ---/*
    I am trying to add the contents of this array after entering the values
    of the array ... but I am confused as to how to do this, please help me.
*/
#include <stdio.h>

#define SIZE 5

int main()
{
    float dAry[ SIZE ];
    float sumInput =0, sumAry =0;
    int i, j, numGood;
    printf( "Enter %d floating point numbers ...\n", SIZE );
    for( i=0;  i<SIZE; ++i )
    {
        printf( "dAry[%d] = ", i );
        numGood = scanf( "%f", &dAry[i] );
        if( numGood==1 ) sumInput += dAry[i];
        else
        {
            --i;
            puts("Bad data ... enter numbers only.");
        }
        while( getchar() != '\n' ) ; /* flush stdin ... */
    }

    for( j=0; j<i; ++j ) sumAry += dAry[j];
   
    printf( "sumInput=%f and sumAry=%f", sumInput, sumAry );

    printf("\nPrint 'Enter' to continue ... ");
    getchar();
    return 0;
}
--- End code ---


NOTE in the following code that 'ary' and 'pAry' both point to arrays of type 'int' ... with this important difference:

sizeof(ary) will give the number of bytes allocated for the array of int's in memory ... In the example here of 5 int's and if each int uses 4 bytes ... then sizeof(ary) returns 20

but

sizeof(pAry) will return 4, if in a 32 bit addressing environment ... since all pointer variables, and pAry was declared as a pointer to an int, use 4 bytes to hold an address, in a 32 bit addressing system.


--- Code: ---#include <stdio.h>
#include <stdlib.h>

void show( int a[], int size )
{
    printf("\n\nArray  syntax  ... ");
    int i;
    for(i=0; i<size; ++i) printf("%d ", a[i]);
}

/* alt. version of above ... using a pointer syntax ... */
void show2( int *a, int size )
{
    printf("\n\nPointer syntax ... ");
    int i;
    for(i=0; i<size; ++i) printf("%d ", *a++);
}



int main()
{
    /*
        create an array in (static) memory with intitial values
        ary[0]=1, ary[1]=2, ..., ary[4]=5 
    */
    int ary[] ={1,2,3,4,5};
    int len_ary = sizeof(ary)/sizeof(ary[0]);
    show( ary, len_ary);
    show2( ary, len_ary);
   
    /*
        Create an array in dynamic memory
        with initial int values pAry[0]..pAry[4] undefined ...
        Or using alt. syntax, these initial int values are undefined ...
        *pAry, *(pAry+1), *(pAry+2),  *(pAry+3), *(pAry+4)

        Allocate (dynamic) memory for 5 int's.
        If an int is 32 bits or 4 bytes ...
        5 int's will need 5*4 = 20 (bytes).
        This new memory is 'cast' as type
        'a pointer to int', the same type as pAry.
    */
    int *pAry = (int*) malloc(sizeof(int)*len_ary);
   
    /* give it some values ... */
    int i;
    for(i=0; i<len_ary; ++i) pAry[i] = (i+1)*(i+1);
     
    show(pAry, len_ary); 
    show2(pAry, len_ary);
       
    /* NOTE: ary and pAry both point to arrays of type int */
       
    printf("\n\nPress 'Enter' to continue ... ");
    getchar();
    return 0;
}
--- End code ---


Now here is an example of a 2DArrays with dynamic memory.  Note that it uses 'a pointer to a pointer to an int'.

This example demos the addition of two matrices.


--- Code: ---#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct twoDArray
{
    int **p;
    int rows;
    int cols;
}matrix;

typedef matrix * pMatrix;

/*
   'createMatrix' returns a pointer to a C struct ...
   The 'struct' holds a 'pointer to a pointer to int' for the 2-D array ... 
   AND ALSO holds the number of rows and cols for the 2-D array.
*/
pMatrix createMatrix(int, int);
void showMatrix(pMatrix);
void freeMatrix(pMatrix);


int main()
{
    int r = 2, c = 4;
    int count = r*c*2;
    pMatrix pM1, pM2, pM3;

    pM1 = createMatrix(r, c);
    /* fill in some values ... */
    int i, j;
    for(i=0; i<pM1->rows; ++i)
        for(j=0; j<pM1->cols; ++j)
            pM1->p[ i ][ j ] = count--;

    pM2 = createMatrix(r, c);
    /* fill in some values ... */
    for(i=0; i<pM2->rows; ++i)
        for(j=0; j<pM2->cols; ++j)
            pM2->p[ i ][ j ] = count--;
           
    pM3 = createMatrix(r, c);
    /* sum first two matrices ...*/
    for(i=0; i<pM2->rows; ++i)
        for(j=0; j<pM2->cols; ++j)
            pM3->p[ i ][ j ] = pM2->p[ i ][ j ] + pM1->p[ i ][ j ];
   
    puts("");

    /* showTwoDArray( pAry ); */
    puts("  Matrix1");
    showMatrix(pM1);
    puts("\n+ Matrix2");
    showMatrix(pM2);
    puts("\n= Matrix3");
    showMatrix(pM3);
    puts("\nfree3");
    freeMatrix(pM3);   
    puts("\nfree2");
    freeMatrix(pM2);   
    puts("\nfree1");
    freeMatrix(pM1);   
    printf("\n\nPress 'Enter' to continue ... ");
    getchar();
    return 0;
}

pMatrix createMatrix(int numrows, int numcols)
{
     pMatrix pM = (pMatrix)malloc(sizeof(matrix));
     assert(pM);

     pM->p = (int**)malloc(sizeof(int*)*numrows);
     assert(pM->p);
     int i; // j;
     for(i=0; i<numrows; ++i)
     {
          pM->p[ i ] = (int*)malloc(sizeof(int)*numcols);       
          assert(pM->p[ i ]);
          //for( j = 0; j < numcols; ++j )
              //pM->p[i][j] = 0; /* initialize all to zero  */                 
     }
     pM->rows = numrows;
     pM->cols = numcols;
     return pM;
}

void showMatrix(pMatrix pM)
{
    int i, j;
    for(i=0; i < pM->rows; ++i)
    {
         for(j=0; j < pM->cols; ++j)
              printf("%4d ", pM->p[ i ][ j ]);           
         puts("");
    }       
}

void freeMatrix(pMatrix pM)
{
     int i;
     for(i = pM->rows-1; i >= 0 ; --i)
     {
          printf( "pM->p[%d] = %d . ", i, (int)pM->p[ i ] );
          free( pM->p[ i ] );
     }   
     
     printf( "pM->p = %d . ", (int)pM->p );             
     free( pM->p );

     printf( "pM = %d",  (int)pM );
     free( pM );   
}
--- End code ---


This example demos the multiplication of two matrices.


--- Code: ---#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct twoDArray
{
    int **p;
    int rows;
    int cols;
}matrix;

typedef matrix * pMatrix;

/*
   'createMatrix' returns a pointer to a C struct ...
   The 'struct' holds a 'pointer to a pointer to int' for the 2-D array ... 
   AND ALSO holds the number of rows and cols for the 2-D array.
*/
pMatrix createMatrix(int, int);
void showMatrix(pMatrix);
void freeMatrix(pMatrix);


int main()
{
    int r = 2, c = 4;
    int count = r*c*2;
    pMatrix pM1, pM2, pM3;

    pM1 = createMatrix(r, c);
    /* fill in some values ... */
    int i, j, k;
    for(i=0; i<pM1->rows; ++i)
        for(j=0; j<pM1->cols; ++j)
            pM1->p[ i ][ j ] = count--;

    pM2 = createMatrix(c, r);
    /* fill in some values ... */
    for(i=0; i<pM2->rows; ++i)
        for(j=0; j<pM2->cols; ++j)
            pM2->p[ i ][ j ] = count--;
           
    pM3 = createMatrix(r, r);
    /* x first two matrices ...*/
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
            for(k=0; k<c; ++k)
                pM3->p[ i ][ j ] += pM1->p[ i ][ k ] * pM2->p[ k ][ j ];
   
    puts("");

    /* showTwoDArray( pAry ); */
    puts("  Matrix1");
    showMatrix(pM1);
    puts("\nx Matrix2");
    showMatrix(pM2);
    puts("\n= Matrix3");
    showMatrix(pM3);
    puts("\nfree3");
    freeMatrix(pM3);   
    puts("\nfree2");
    freeMatrix(pM2);   
    puts("\nfree1");
    freeMatrix(pM1);   
    printf("\n\nPress 'Enter' to continue ... ");
    getchar();
    return 0;
}


pMatrix createMatrix(int numrows, int numcols)
{
     pMatrix pM = (pMatrix)malloc(sizeof(matrix));
     assert(pM);

     pM->p = (int**)malloc(sizeof(int*)*numrows);
     assert(pM->p);
     int i, j;
     for(i=0; i<numrows; ++i)
     {
          pM->p[ i ] = (int*)malloc(sizeof(int)*numcols);       
          assert(pM->p[ i ]);
          for( j = 0; j < numcols; ++j )
              pM->p[i][j] = 0; /* initialize all to zero  */                 
     }
     pM->rows = numrows;
     pM->cols = numcols;
     return pM;
}

void showMatrix(pMatrix pM)
{
    int i, j;
    for(i=0; i < pM->rows; ++i)
    {
         for(j=0; j < pM->cols; ++j)
              printf("%4d ", pM->p[ i ][ j ]);           
         puts("");
    }       
}

void freeMatrix(pMatrix pM)
{
     int i;
     for(i = pM->rows-1; i >= 0 ; --i)
     {
          printf( "pM->p[%d] = %d . ", i, (int)pM->p[ i ] );
          free( pM->p[ i ] );
     }   
     
     printf( "pM->p = %d . ", (int)pM->p );             
     free( pM->p );

     printf( "pM = %d",  (int)pM );
     free( pM );   
}
--- End code ---


Now here is a Jacobi Iteration Solution-Method for strictly diagonally dominant square matrices ... (to solve a system of linear equations.)


--- Code: ---/* was int ,,, now 2014-02-16 ,,, char SHOW_ITERS = 0; */ /* defaults to NO ... */

/* see credits to original source below ... this version features all */
/* dynamic arrays ... some input data validation ... results checking ... and */
/* also 2 (major) errors, in the code found on 2009-03-24 on the web, were fixed */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

/* globals ... */

#define HEADER "**********************************************************\n" \
               "             JACOBI ITERATION SOLUTION METHOD             \n" \
               "    (for strictly diagonally dominant square matrices)    \n" \
               "**********************************************************\n"
#define EPSILON 0.0000001
#define MAX_PRINT_ITERS 333

char SHOW_ITERS = 0; /* defaults to NO ... */

/* input matrix elements */
void getInput( int, double** mat );
/* check if diagonally dominant */
int checkIfDD( int, double** mat );
/* calculate and display answers */
void jacobiCalcDisplay( int, double** mat );

double dotProd( int num, double* v1, double* v2 );

void showXcheck( int num, double** mat, double* v1, double* v2 );

int checkFlags( int num, int flags[] );

/* free dynamic memory occupied by 2D square matrix */
void freeMat( int num, double** sqMat );

int more()/* defaults to yes ... */
{
    int reply ;
    printf("\nMore ... (y/n) ? ");
    reply = getchar();
    if( reply != '\n' )
        while( getchar() != '\n' ) ; /* flush stdin ... */
    putchar( '\n' );
    return !(reply=='n' || reply=='N');
}



int main()
{
    double **mat;
    int num;

    do
    {
        puts( HEADER );

        printf( "Show each iteration result 1=Yes, 0=No ? " );
        scanf("%c", &SHOW_ITERS);
        if( SHOW_ITERS != '\n' )
            while( getchar() != '\n' ) ; /* flush stdin ... */

        if( !(SHOW_ITERS=='1'||SHOW_ITERS=='y'||SHOW_ITERS=='Y') )
        {
            puts("Ok ... 'No' it is ...");
            SHOW_ITERS =0;
        }
        else puts("Ok ... 'Yes' show iterations ... (This may take some time.)");

        printf("\nTo solve a system of linear equations ...\n");
        printf("Enter the number of 'equations/unknowns' to find: ");
        num = 0;
        scanf("%d", &num); /* num of unknowns */
        while( getchar() != '\n' ) ; /* flush stdin ... */

        mat = NULL;
        if( num>0 && (mat = (double**) malloc(num*sizeof(double*))) )
        {
            getInput(num, mat);
            if( checkIfDD(num, mat) ) jacobiCalcDisplay(num,mat);
            else freeMat(num, mat);
        }
        else
        {
            puts("Invalid choice or memory available was exceeded ... Try again.");
            if( mat != NULL ) free( mat );
        }
    }while( more() );
    return 0;
}


void getInput( int numUnKnowns, double** mat )
{
    int i, j;

    printf
    (
        "\nEnter values for the specified row and column below ...\n"
        "(The last column is the value for the RHS of the equation.)\n"
    );
   
    for( i = 0 ; i < numUnKnowns ; i++ )
    {
        mat[i] = (double*) malloc( (numUnKnowns+1)*sizeof(double) );
        puts("");
        for( j = 0 ; j < numUnKnowns+1 ; j++ )
        {
            printf("matrix[%d][%d] : ", i, j);
            if( scanf("%lf", &mat[i][j]) != 1 )
            {
                --j;
                puts("Bad entry ... try again with a 'real' number.");
            }
            while( getchar() != '\n' ) ; /* flush stdin ... */
        }
    }

    printf("\nThe matrix entered:\n\n");
    for( i = 0 ; i < numUnKnowns ; i++ )
    {
        for( j = 0 ; j < numUnKnowns+1 ; j++ ) printf("%+9f ", mat[i][j]);
        puts("");
    }

    printf("\nPress 'Enter' to start iteration ... ");
    getchar();
}

/* Check if the matrix entered is strictly diagonally dominant */
int checkIfDD( int numUnKnowns, double** mat )
{
    int   m, n, dd = 0;
    double* chkdd;
    double* sumdd = (double*) malloc( numUnKnowns*sizeof(double) );
    chkdd = (double*) malloc( numUnKnowns*sizeof(double) );

    for( m = 0 ; m < numUnKnowns ; m++ )
    chkdd[m] = sumdd[m] = 0; /* all set to zero ... */

    printf("\nChecking if the matrix is (strictly) diagonally dominant...");

    for( m = 0 ; m < numUnKnowns ; m++ )
    {
        for( n = 0 ; n < numUnKnowns ; n++ )
            sumdd[m] += fabs(mat[m][n] );
        sumdd[m] -= fabs(mat[m][m]);
        chkdd[m] = fabs(mat[m][m]);

        if(chkdd[m] > sumdd[m])
        {
            printf("\n%f > %f",chkdd[m],sumdd[m]);
            dd++;
        }
        else printf("\n%f !> %f",chkdd[m],sumdd[m]);
    }

    if(dd == numUnKnowns)
    {
        printf
        (
            "\nYES ..."
            "\nThe matrix is (strictly) diagonally dominant."
            "\nPress 'Enter' to continue with 'Jacobi Iterative Method'...\n"
        );
        getchar();
    }
    else
    {
        printf
        (
            "\nNO ..."
            "\nThe matrix is NOT (strictly) diagonally dominant ... so STOP!"
            "\n(But ... consider exchanging rows in the matrix "
            "and then to try again.)"

            "\n\nPress 'Enter' to continue ... "
        );

        getchar();
        free( sumdd );
        free( chkdd );
        return 0; /* false */
    }

    free( sumdd );
    free( chkdd );
    return 1; /* true */
}

/* uses global SHOW_ITERS ... */
void jacobiCalcDisplay( int numUnKnowns, double** mat )
{
    int* flag;
    int i, j, counter = 0;
    double* res;
    double* var = (double*) malloc( numUnKnowns*sizeof(double) );
    res = (double*) malloc( numUnKnowns*sizeof(double) );
    flag = (int*) malloc( numUnKnowns*sizeof(int) );

    for(i = 0 ; i < numUnKnowns ; i++ )
    var[i] = res[i] = flag[i] = 0;
    printf("The initial value of each array element was set to zero ...\n\n");

    printf( "*********************\n");
    printf( "START CALCULATING ...\n");
    printf( "*********************\n");

    do
    {
        counter++;
        /* for each iteration keep a copy of the old results ... */
        for(i = 0 ; i < numUnKnowns ; i++ )
        {
            var[i] = res[i];
        }

        if( SHOW_ITERS ) printf("\nIteration number %d ...\n", counter);

        for(i = 0 ; i < numUnKnowns ; i++ ) /* calculation */
        {
            res[i] = mat[i][numUnKnowns];
            for(j = 0 ; j < numUnKnowns ; j++ )
                res[i] = res[i] - mat[i][j]*var[j] ;

            res[i] = res[i] + mat[i][i]*var[i] ;
            res[i] = res[i] / mat[i][i] ;
            if( SHOW_ITERS ) printf("%c = %f\n", 'a'+i, res[i]);
            if( fabs(res[i] - var[i]) < EPSILON ) /* stop condition */
            flag[i]++;

            if( counter==MAX_PRINT_ITERS) SHOW_ITERS = 0;
        }
       
    }while( !checkFlags( numUnKnowns, flag ) );

    printf( "\n********************************\n");
    printf( "The RESULTS of %d ITERATIONS ... \n", counter);
    printf( "********************************\n");

    /*  cross check ...*/

    for( i = 0 ; i < numUnKnowns ; i++)
        var[i] = dotProd( numUnKnowns, mat[i], res );

    showXcheck( numUnKnowns, mat, res, var );

    /* show sol'n vector (again) ... and free up all dynamic memory  */

    printf("\nSolution vector ...\n");
    for( i = 0 ; i < numUnKnowns ; i++)
    {
        printf("%c = %+f\n", 'a'+i, res[i]);
        free(mat[i]);
    }
    free( mat );
    free( flag );
    free( res );
    free( var );
}

int checkFlags( int num, int flags[] )
{
    int i;
    for( i=0; i<num; ++ i)
        if( flags[i] == 0 ) return 0;
    return 1;
}

double dotProd( int num, double* v1, double* v2 )
{
    int i;
    double sum =0;
    for( i=0; i<num; ++i ) sum += v1[i]*v2[i];
    return sum;
}

void showXcheck( int num, double** mat, double* v1, double* v2 )
{
    int i, j;
    puts("\nCross checking ... \nMatrix times sol'n vector ="
         " cal. vector vs. original RHS vector");
    for( i = 0 ; i < num ; i++)
{
        printf("|");
        for( j =0 ; j < num ; j++ )
            printf("%+9f ", mat[i][j] );
        printf("| |%+9f| |%+9f|vs|%+9f|\n", v1[i], v2[i], mat[i][num]);
    }
}


void freeMat( int num, double** sqMat )
{
    int i;
    for( i=num-1; i>=0; --i )
        free( sqMat[i] );
    free( sqMat );
}


/*
Title: Jacobi Iteration for a system of linear equations ...

Consider a 4 unknowns linear system

7a - 2b +  c + 2d =  3
2a + 8b + 3c +  d = -2
-a      + 5c + 2d =  5
     2b -  c + 4d =  4

In my program, when asked for number of unknown, just enter 4.

When asked for value enter, it should be like this referred to the above linear system:

_____________________________________________
                JACOBI ITERATION
         AUTOMATIC ITERATION CALCULATOR
                 PUBLIC VERSION
_____________________________________________
Current available unknown calculation is from 1 until 26.
Please enter the number of unknown: 4
Enter values for the specified row and column below,
Row 1, Column 1 : 7
Row 1, Column 2 : -2
Row 1, Column 3 : 1
Row 1, Column 4 : 2
Row 1, Column 5 : 3
Row 2, Column 1 : 2
Row 2, Column 2 : 8
Row 2, Column 3 : 3
Row 2, Column 4 : 1
Row 2, Column 5 : -2
Row 3, Column 1 : -1
Row 3, Column 2 : 0
Row 3, Column 3 : 5
Row 3, Column 4 : 2
Row 3, Column 5 : 5
Row 4, Column 1 : 0
Row 4, Column 2 : 2
Row 4, Column 3 : -1
Row 4, Column 4 : 4
Row 4, Column 5 : 4

Next is just calculation and result will print on screen.

by AlexTan
Segamat Baru 85000
Segamat, Johor
Malaysia
*/
--- End code ---

You may also want to check here ...

http://www.dreamincode.net/forums/topic/64817-solving-linear-equations-using-iteration/

David:
C++ Student class ... a very common student problem ...

Update: moved to here ...

http://developers-heaven.net/forum/index.php/topic,2585.0.htm


A demo simpler class Student ...


--- Code: ---// a very simple student class that also demos overloading the << operator
#include <iostream>

using namespace std;

class student

public:
    student(string n = "", string d = "") : name(n), department(d) {}
    string get_name() const { return name; }
    string get_department() const { return department; }
    void set_name(const string& n) { name = n; }
    void set_department(const string& d) { department = d; }
private:
    string name;
    string department;
};

ostream& operator << (ostream& os, const student& s )
{
    return os<<s.get_name()<<", "<<s.get_department();
}

int main()
{
  student s( "Billy Kid", "Zoology" );
  student t, w;
  t = s;
  w.set_name( "Bobby Stone" );
  w.set_department( "Geology" );
  t.set_department( w.get_department() );
    cout << s << endl << t << endl << w << endl;
   
  system("pause");
return 0;
}

--- End code ---


And an Entry class ...


--- Code: ---// using a vector to hold objects of class Entry
// a 'shell'... for a contact/address data base

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cctype>

using namespace std;

class Entry
{
    friend istream&operator>>(istream&, Entry&);
    friend ostream&operator<<(ostream&, Entry&);
   
public:
   
    // default constructor
    Entry() {}
   
    // constructors
    Entry(string N, string A1, string A2, string P)
    {
        Person=N; Add1=A1; Add2=A2; Phone=P;
    }
   
    void setPerson(string temp) {Person=temp;}
    void setAdd1(string temp) {Add1=temp;}
    void setAdd2(string temp) {Add2=temp;}
    void setPhone(string temp) {Phone=temp;}
   
    // accessors
    string getPerson() {return(Person);}
    string getAdd1() {return(Add1);}
    string getAdd2() {return(Add2);}
    string getPhone() {return(Phone);}
   
private:
    string Person, Add1, Add2, Phone;
};

// friend function to overload the >> operator for input
istream &operator>>(istream &input, Entry &e)
{
   string temp[5];
   for(int i=0; i<5; i++) getline(input, temp[i], '\n');
   Entry e_temp(temp[0],temp[1],temp[2],temp[3]);
   e=e_temp;
   return(input);
}

// friend function to overload the << operator for output
ostream&operator<<(ostream &output, Entry &e)
{
    output << e.Person<<endl
           << e.Add1<<endl
           << e.Add2<<endl
           << e.Phone<<endl;
    return(output);
}

// prototypes of functions used in 'main'
void appendBook(vector< Entry>&);           // add to book from keyboard ...
void printBook(vector< Entry >&);           // print the current book to screen
void readBook(const char[], vector< Entry >&);  // read book from file
void writeBook(const char[], vector< Entry >&); // write the current book to file

// Globals ...
const char line[] = "-----------------------------------";
const char fName[] = "MyBBook.dat";

int main()
{
    vector < Entry > Book;          // construct a new vector Book for 'entries'
    appendBook(Book);               // add to Book from keyboard ...
   
    cout << "\nHere is the 'book' you just entered ...\n";
    cout << line << endl;
    printBook(Book);                // show book on screen
    writeBook(fName, Book);         // write Book to file
    cout << "\nThe 'last' record is " << Book.size() << "\n\n";
    system("pause");
   
    vector< Entry > v;
    Book = v;                       // set to empty ...
    readBook(fName, Book);          // read Book from file
    cout << "\nHere is the 'book'  read  from file ...\n";
    cout << line << endl;
    printBook(Book);
    cout << "The 'last' record is " << Book.size() << "\n\n";
    system("pause");
}

// definitions of functions used in 'main'
string takeIn(string message)
{
    cout<<message<<": ";
    string inStr;
    getline(cin, inStr, '\n');
    return(inStr);
}

void appendBook(vector< Entry > &b)
{
    Entry e;
    do
    {
        e.setPerson(takeIn("Enter name            "));
        e.setAdd1  (takeIn("Enter address 1st line"));
        e.setAdd2  (takeIn("Enter address 2nd line"));
        e.setPhone (takeIn("Enter phone           "));
        b.push_back(e);
       
    }while( tolower(takeIn("More y/n ?            ")[0]) != 'n' );
}

void printBook(vector< Entry > &b)
{
    for(size_t i=0; i<b.size(); ++i) cout << b[i] << endl;
}

void writeBook(const char f[], vector< Entry > &b) // write the current book to file
{
    // 5 lines of data are written for each 'entry' (includes 5th blank line)
    ofstream OUTFILE( f );
    for(size_t i=0; i<b.size(); i++) OUTFILE << b[i] << endl;
    OUTFILE.close();
}

void readBook(const char f[], vector< Entry > &b)
{
    ifstream INFILE( f );
    Entry e;
    while(INFILE >> e) { b.push_back(e); }
    INFILE.close();
}
--- End code ---

David:
A C way to handle student records using a linked list of C struct ... ("Student GRADES MANAGEMENT SYSTEM")

moved/updated ... now appears later here (near the end, at present ... click on the next link to jump to there right now:)

http://developers-heaven.net/forum/index.php/topic,106.msg273.html#msg273


David:
The following function definitions belong to the program above ...

Code update/moved as per notice on above page ...

Navigation

[0] Message Index

[#] Next page

[*] Previous page

Go to full version