David W 131 Practically a Posting Shark

Try this ... expanding on Dani's @deceptikon's hint of 'using better variable names'

/* pointer_demo.c */

#include<stdio.h>

/* global */
int q_global = 10;

void func( int* );


int main()
{
    int r = 30;
    int* r_address = &r;
    func( r_address ); /* after this call, value at r_address is set to 15 */
    printf( "%d", *r_address ); /* prints 15 */
    return 0;
}


void func( int* address_copy )
{
    *address_copy = 15; /* set value at (calling) address to 15 */
    address_copy = &q_global; /* update address_copy to NOW hold address of int  q_global */
    printf( "%d ", *address_copy ); /* print value at address_copy, i.e. value of q_global */
}
David W 131 Practically a Posting Shark
int q = 10;

void fun(int *p)
{
    *p = 15; // after this point, the 'int' at the address passed in holds 15
    p = &q; // NOW ... p holds a different address, the address of global q
    printf("%d ",*p);
}    
David W 131 Practically a Posting Shark

See the slight revisions and the comments added ...

#include <iostream>

using namespace std;

class Test
{
public:
    Test(int x): a(x) {} // constructor //
    void display()
    {
        cout << "The value of a is: " << a << endl;
    }
private:
    int a;
    friend void swap( Test& t, Test& t1 );
} ;

// passed in by reference so that (addresses to) objects
// in the calling scope are passed in, 
// (and not local copies used inside) //
void swap( Test& t, Test& t1 ) 
{
    Test tmp( t1 ); // make a tmp copy of t1
    t1 = t; // set t1 (value) to t (value)
    t = tmp; // tmp was holding original value of t1, so assign to t //
}


int main()
{
    Test t(20), t1(30); // construct t to hold 20 and t1 to hold 30
    swap(t, t1); // after this call t holds 30 and t1 holds 20
    t.display(); // prints: The value of a is: 30 
    t1.display(); //on NEXT line prints: The value of a is: 20 
    return 0; // returns 0 value to indicate successful program run //
}
David W 131 Practically a Posting Shark

Do not use system("PAUSE"); // this is not portable C++ code //

Your data file structure of :

/*
DATAFILE << " 2012 "  << "\n";
DATAFILE << " 11" << "\n";
DATAFILE << " 19" << "\n";
DATAFILE << " 230 mm" << "\n";
DATAFILE << " Snow" << "\n";
DATAFILE << " 140" << "\n";
*/

/*
getline(DATAFILE,year);
getline(DATAFILE,avgMinTmp);
getline(DATAFILE,avgMaxTmp);
getline(DATAFILE,totalRainfall);
getline(DATAFILE,reportedWeather);
getline(DATAFILE,daysReported);
*/

seems to implicate a very simple way to start ...

Use a struct to hold each data record:

struct Weather
{
    int year, avgMinTmp, avgMaxTmp, totalRainfall; //  H2O in mm
    string reportedWeather; // example "Snow"
    int daysReported;

    istream& takeIn( istream& is )
    {
        string mm;
        is >> year >> avgMinTmp >> avgMaxTmp >> totalRainfall >> mm >> reportedWeather >> daysReported;
        return is;
    }

    void print( ostream& os = cout )
    {
        return os << year << '\n' << avgMinTmp << '\n' << avgMaxTmp << '\n' totalRainfall << " mm\n" << reportedWeather << '\n' << daysReported;
    }
};

Then use a ...

vector < Weather > data; // to hold all the records read from file

You could use some functions to read and write the file data.

bool takeIn( const char* fname, vector < Weather >& data );
void outPut( const char* fname, const < Weather >& data );

One def'n could be like this:

bool takeIn( const char* fname, vector < Weather >& data )
{
    ifstream fin( fname );
    if( fin )
    {
        Weather w;
        while( w.takeIn(fin) ) …
David W 131 Practically a Posting Shark

@Atiq_1 ... you may not yet have learned that it is NOT appropriate to 'hijack' an other poster's thread ? So please post your beginner level question in a NEW thread.

Also, you need to know that you MUST make an effect to code a solution and post the code that you have tried, if you actually expect anyone here to see how to help you. <Your homework MUST be YOUR work.> We are glad to help you to learn ... but we can not do your work for you, or else we would be the ones to be hired by any of your possible future employers.

@Hia ... please read and understand the (2nd part of the) above also.
HINT! You could use a loop ... while( fin >> word ) { // ... // }... to read the words in your file ... etc.

David W 131 Practically a Posting Shark

Instead of iostream use stdio.h

instead of cout << "text " << some_int << endl; // use printf( "text %d\n", some_int );

and do a web search on C printf to see how to print other types

remember to declare all your variables at the top of any new block

{
   int a, b; /* declare here if using C90 compiler standard */
   /* use this for all C90 standard comments  ... NOT //   */
}

and ... you do not use ...

  /* using namespace std; // NOT in C */
David W 131 Practically a Posting Shark

After you have posted the code you yourself have so far coded ... and tried ... including posting all the compiler error messages ... if any ... we will then be able to see what to suggest to you for a next step.

Please note that this is a very common and simple student problem to code ... that is typically handled ok, if you have coded an 'Hello World' program ... and are around the 2rd or 3rd lesson.

There are so very many examples/tutorials on the web that you could find to get ideas how to get started.

In a search window ... you could search under:

"C++ program to find average"

or look here:
http://developers-heaven.net/forum/index.php/topic,2019.0.html

David W 131 Practically a Posting Shark

Since this was your first post, please be advised that ...

you will need to firstly post the code that you, yourself, have coded ... and tried,

also include a full and exact copy of the assignment you were given,

also include all design specifications and limitations, if any were added.

Then, we may be able to see where you are having difficulty and how to best help you.

David W 131 Practically a Posting Shark

Since you posted your question as a C programming question, here is a little C demo program that uses || ... (OR) ... you may find helpful.

/* bp.c */  /* revised 2016-01-31 */


#include <stdio.h>

const char* MY_FILE = "BP.txt";

/* (make a test) data file structured as per the following: */
/*
Smith Jane 111/76
Jones Rob 98/70
Costello Judy-Ann 144/90
Frank-Anderson Bibby-Bonnie 190/30
Sue Peggy 10/5
James-Thomas Andrew 190/111
*/


const char* UNKNOWN = "*** Unrecognized diagnosis ***\n"
                      "*** Please check validity of data entered ***";


typedef struct
{
    char lname[20];
    char fname[20];
    int sys;
    int dia;

} BP ; /* BloodPressure*/


const char* get_diagnosis( int sys, int dia ) /* Note: need 'const' since returning 'literal' */
{
    if( sys < 120/2 || dia < 80/2 ) /* ?? */
        return UNKNOWN;
    if( sys > 120*2 || dia > 80*2 ) /* ?? */
        return UNKNOWN;

    if( sys >= 160 || dia > 100 )
        return "*** Check age re. possible Stage 2 Hypertension ***";
    if( sys >= 140 || dia >= 90 )
        return "*** Check age re. possible Stage 1 Hypertension ***";
    if( sys >= 120 || dia >= 80 )
        return "*** Check age re. possible Pre-Hypertension ***";

    /* else ... */
    return "Normal";
}



void print( const BP* p )
{
    char buf[40] = {'.'};
    sprintf( buf, "%s, %s ", p->fname,  p->fname );

    printf( "%s blood pressure was %d/%d\n", buf, p->sys, p->dia );
    printf( "%s\n", get_diagnosis( p->sys, p->dia ) );
}

int …
David W 131 Practically a Posting Shark

Welcome to Daniweb.

Please note that the first part of any solution process is to get a clear and complete understanding of the problem.

So, are you sure of:

... I was assigned to create a stack in c++ and my professor asked to put arrays inside each stack ... ?

Note: It is quite common to 'use an array' as the container for a 'stack'.

Note too that a C++ vector container is really just an easily expandable dynamic array that has added push_back, (read) back and pop_back methods (functions).

So ... since a stack is a LIFO (last in first out) type of container structure ... any container that has 'push_back', '(read) back' and' pop_back' methods (functions) could be used for a stack ... (and/or push_front, (read) front, pop_front).

This is why a C++ list is also often used as a container to code a stack.

Make you best efforts to code a solution to your problem ... but firstly ... make sure that you have a clear and complete statement of that problem.

If you need help to understand that 'statement' ... you will also need to include the exact statement of the problem as it was given.

David W 131 Practically a Posting Shark

@admir192 ... did you miss this first line by the OP?

"the program is supposed to find the sum of 10 integer numbers stored in an array ..."

It seems the OP has either figured out the problem from the good clue provided by Dani's @rubberman ... or ... perhas has abandoned this forum?

The only further hint to the OP ...might be to plainly state ...
that your problem spec's seem to clearly enough direct you
to use just a 1-D array to hold 10 integers.

This is such a common beginning C++ student type problem that some years ago I put this link up for students to see ... (it also shows a 'student way' to take in valid integers so that the running program will not crash on invalid data input.)

http://developers-heaven.net/forum/index.php/topic,2019.0.html

David W 131 Practically a Posting Shark

If the file will all fit into memory, then the better (much faster) method is to read the whole file into dynamic memory ... traverse that data and update as desired ... then write all that updated data back to the (overwritten) file.

David W 131 Practically a Posting Shark

If you don't wish to re-invent code, feel free to use the dynamic C string library here:

see file CvecOfString.h at ...
http://developers-heaven.net/forum/index.php/topic,2580.0.html

that uses files ...
readLine.h
Cvec.h

David W 131 Practically a Posting Shark

You really have two distinct problems that are easiest/best to be each solved on their own:

1) code a linked list.
2) code a contact list using a linked list as a container.

You might like to look at the next two links to see this division of labour:

http://developers-heaven.net/forum/index.php/topic,2606.0.html
Steps to a C++ template class List

http://developers-heaven.net/forum/index.php/topic,2586.0.html
Class Student using STL list

David W 131 Practically a Posting Shark

A more general way to take in data records in C is to use a struct ... maybe something like the example below.

(Note the use of several functions to break up the program into jobs ...
a function for each task.)

You could start with several utility functions like this:

/* name_id_struct_example.c */

#include <stdio.h>
#include <string.h> /* re. strchr, strlen */
#include <ctype.h> /* re. toupper, tolower */

#define MAX_NAME_LEN 23

const int MIN_ID = 1;
const int MAX_ID = 999;

const char* HEADER = "Demo of a way to get valid name and id for a Student Record.";


/* 2 handy utilities for many C student coding problems ... */
int takeInChr( const char* msg )
{
    char chr;
    printf( msg ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}
int more() /* defaults to 'true'/'yes'/'1' ... unless 'n' or 'N' entered */
{
    int c = takeInChr( "\nMore (y/n) ? " );
    if( c == 'n' || c == 'N' ) return 0;
    /* else ... */
    return 1;
}

/* a simple student way to handle numeric input ...
   so program won't crash on bad input */
int takeInInt( const char* msg, int min, int max )
{
    int val = 0;
    while( 1 ) /* loop forever until break is reached ... */
    {
        printf( msg ); fflush( stdout );

        if( scanf( "%d", &val ) == …
David W 131 Practically a Posting Shark

For line 52 ... do NOT use unsafe 'gets' ... you can use fgets instead (or use my readLine to read in dynamic C strings of any length, if you wish to use dynamic C strings.)

http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864

@rubberman note wrt line 41:

/* OP is passing in address of n */
MOVIE* readMovies(int *n)//read data about movies with actors
{
    MOVIE *me;
    do
    {
        printf("n=");
        scanf("%d",n); /* line 41 ... NOTE 'n' is an address already */
    }

    /* ... */

How to implement function for printing data about all movies that contain one read actor?

Traverse the array of movies ... for each movie ... if the number of actors in that movie is 1, then print out that movie info.

David W 131 Practically a Posting Shark

I would use a Cvec of dynamic C strings to hold all the strings read in from file.

See:

http://developers-heaven.net/forum/index.php/topic,2580.0.html

Then traversing the Cvec of strings
to see if any other string in the Cvec is a permutation of the string at this index ...

use a compare function that makes a sorted copy of each string to be compared ... then if sorted copies match ... you have a permutation.

OR ...

you may want to firstly make a copy of the Cvec of strings ...
then sort each string in that copy ...
then use the relevant index to compare strings while looking for permutations.

David W 131 Practically a Posting Shark

We really can not help you on a free public forum if the code you present has copywrite attached ... how can we copy/edit it then?

Also ... over 1000 lines of code ? If you really need help, isolate the few lines of code that you need help to implement ... make a minimal test program to test that code out ... and then we may be able to help ... if it is your original code ... and if it does not have copywrite to it?

David W 131 Practically a Posting Shark

As Dani's @ tinstaafl suggests ...

firstly ...

to get a design for just simple addition (of large int's of any size) to work,

you could use some functions to read in dynamic C strings of any size, maybe something like this:

Note that file "readLIne2.h" is available here:

http://developers-heaven.net/forum/index.php/topic,2582.msg3143.html#msg3143

/* add_dynamic_Cstrings.c */

#include "readLine2.h"



/* 2 handy utilities here ... */
int takeInChr( const char* msg )
{
    char chr;
    fputs( msg, stdout ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}
int more() /* defaults to 'true'/'yes'/'1' ... unless 'n' or 'N' entered */
{
    if( tolower( takeInChr( "More (y/n) ? " )) == 'n' ) return 0;
    /* else ... */
    return 1;
}

int is_valid( const char* str )
{
    while( *str )
    {
        if( *str < '0' || *str > '9' ) return 0;
        ++str;
    }
    return 1;
}


char* add( const char* a, unsigned len_a, const char* b, unsigned len_b, unsigned* len_c )
{
    char* c;
    int i, j;
    int overflow = 0;
    if( len_a >= len_b )
    {
        c = newMem( len_a+1 );
        c[len_a] = 0;
        for( i = len_a-1, j = len_b-1; j >= 0; --i, --j )
        {
            c[i] = a[i] + (b[j] - '0') + overflow;
            if( c[i] > '9' )
            {
                overflow = 1;
                c[i] -= 10;
            }
            else
            {
                overflow = 0;
            }
        }

        for( ; i >= 0; …
David W 131 Practically a Posting Shark

I just remembered this link that you might like to see:

http://developers-heaven.net/forum/index.php/topic,127.msg235.html#msg235

Chapter 06: The Computer rolls the dice … a first simulation

... an interactive project with a little Google research to find out about the random function in the C++ library

David W 131 Practically a Posting Shark

Hi Alfadil,
If you get stuck, please post what you have tried (and any error messages) so we can see where you are at and how to help you.
Shalom shalom,
David
P.S. Thank you for the 'up-vote.'

David W 131 Practically a Posting Shark

You seem to be using C++ ... so use C++ string ...
(and this question should then be in the C++ forum.)

Another way to get the string you need is to use an array of strings (a table) ...
See the example below:

// return_a_string.cpp//

#include <iostream>
#include <iomanip> // re. setw
#include <string>  // use C++ string in C++ //
#include <sstream> // re. stringstream objects //
#include <cctype> // re. tolower //

using namespace std;


const string DELIVERY[] =
{
    "UNKOWN", "BlueDart", "FedEx", "Delhivery", "DTDC/FirstFlight",
    "Ecom Express", "India Post", "ATS", "Ekart", "Aramex"
} ;
const int NUM_DELIVERY_TYPES = sizeof DELIVERY / sizeof *DELIVERY;

const string CHOICES[] =
{
    "", "Baby & Mom", "Books & Magazines", "Cameras & Optics", "Automotive",
    "stringity", "Clothing & Accessories", "Coins & Notes", "Collectibles",
    "Fitness & Sports", "Fragrances, Beauty & Health", "Fun Stuff", "Games & Accessories",
    "Home and Living", "Home & Kitchen Appliances", "Jewellery & Precious Coins", "Kitchen & Dining",
    "Laptops & Computer Peripherals", "LCD, LED & Televisions", "Memory Cards, Pen Drives & HDD", "Mobile Accessories",
    "Mobile Phones", "Gaming Consoles", "Movies & Music",  "Musical Instruments", "Services & Real Estate",
    "Shoes", "Stamps", "Stationery & Office Supplies", "Tablets & Accessories",
    "Hardware & Electricals", "Toys, Games & School Supplies", "Travel", "Watches", "Warranty Services", "Wearable Devices",
    "Audio & Home Entertainment", "Everything Else"
} ;
const int NUM_CHOICES = sizeof CHOICES / sizeof *CHOICES;


template< typename T >
T takeIn( const string& msg )
{
    T val;
    while( true )
    {
        cout << msg << flush;
        if( …
David W 131 Practically a Posting Shark

... airport simulation program
... the airport has one runway ..
one plane can land (or) one plane can fly (takeoff) but not both (at the) same time.
the (waiting) plans are kept in 2 queues
one for landing
one for taking off.

Is the above the totality of your supplied design spec's?

If not ...
it would help to supplied the complete and exact copy of the spec's you were given.

I suspect your design could be improved?

David W 131 Practically a Posting Shark

There are few things about your style of coding that could be improved:

/* use Global const (in C use #define) instead of 'magic numbers' */
#define MAX_LEN 31 /* pick numbers that give multiplies of 4 (or 8) bytes */ 

typedef struct
{
    char name[MAX_LEN+1], /* recall need space for terminal 0 */
         surname[MAX_LEN+1];
    int number;

} Player ; /* Use Cap then small case here */


typedef struct
{
    char nameofteam[MAX_LEN+1];
    int numberofplayers;
    Player* players;

} Team ;

/* 
Note: usually it is better to pass in data records by passing the address.
 */
void pr_replaces_numout( Team* tm, const Player* pr, int numout )
{
    int i;
    for( i = 0; i < tm->numberofplayers; ++ i )
    {
        if( tm->players[i].number == numout )
        {
            strcpy( tm->players[i].name, pr->name );
            strcpy( tm->players[i].surname, pr->surname );
            tm->players[i].number = pr->number;
            break;
        }
    }
}
David W 131 Practically a Posting Shark

There are several steps to the final solution of your problem ...

The first step that I would suggest you take would be to get some test data,
perhaps like this ... to get a bin file to test the rest of your code:

/* spiltInto2Files.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strcmp */

#define MAX_STR_LEN 19
#define FORMAT_STR_IN " %19s %19s %19s %19s %lf"
#define FORMAT_STR_OUT "%-19s %-19s %-19s %-19s %10.2f\n"


const char* START_TXT = "start.txt";
/*
12345 Samuels Joe Prof 60000
12348 Plummer Bob Assist 30000
12347 Anderson Kim Assist 25000
12344 Davidson George Prof 110000
12346 Bowers Ann Assist 20000
*/

const char* TEST_BIN = "test.bin";

const char* PROF_FILE   = "prof.txt";
const char* ASSIST_FILE = "assist.txt";


typedef struct
{
   char id[MAX_STR_LEN+1],
        surname[MAX_STR_LEN+1],
        name[MAX_STR_LEN+1],
        title[MAX_STR_LEN+1];
   double salary;

} Employee ;

int create_bin_file( const char* fname_in, const char* fname_out)
{
    FILE* fin  = fopen( fname_in, "r" );
    FILE* fout = fopen( fname_out, "wb" );
    if( fin && fout )
    {
        char buf[128];
        Employee tmp;
        while( fgets( buf, sizeof buf, fin ) )
        {
            if( sscanf( buf, FORMAT_STR_IN, tmp.id, tmp.surname, tmp.name, tmp.title, &tmp.salary ) != 5 )
                return 0;;
            /* size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); */
            if( fwrite( (char*)&tmp, sizeof(Employee), 1, fout ) != 1 )
                return 0;
        }
        fclose( fout );
        fclose( fin );
        return 1;
    }
    /* else */
    printf( "Error opening files ...\n" );
    return 0;
}

After that, you should test that …

David W 131 Practically a Posting Shark

All you need to do is change the print function to a ....
get and fill array function ...
like this:

void get_positions( const int* ary, int size, int val, int* pos_ary )
{
    int i, j = 0;
    for( i = 0; i < size; ++ i )
    {
        if( ary[i] == val )
            pos_ary[j++] = i;
    }
}

Then, you could update the main function, to be like this:

int main()
{
    int arr[] = { 14, 10, 2, 1, 14, 1, 10, 14, 14, 2, 3, 4, 14, 14, 1, 4, 14, 14 };
    int size = sizeof arr / sizeof *arr ;
    int i, i_mc, size_vc_ary = 0;

    ValCount* vc_ary = malloc( sizeof(ValCount) * size );

    if( vc_ary )
    {
        int* pos_ary;

        for( i = 0; i < size; ++ i )
            size_vc_ary = update( vc_ary, size_vc_ary, arr[i] );

        i_mc = get_i_of_max_count( vc_ary, size_vc_ary );

        printf( "The most frequent value was %d and it occured %d times.\n",
                vc_ary[i_mc].val, vc_ary[i_mc].count );
        printf( "The value %d occured at positions: ", vc_ary[i_mc].val );

        pos_ary = malloc(sizeof(int) * vc_ary[i_mc].count );
        if( pos_ary )
        {
            get_positions( arr, size, vc_ary[i_mc].val, pos_ary );

            for( i = 0; i < vc_ary[i_mc].count; ++ i )
            {
                printf( "%d ", pos_ary[i] );
            }
            /* free up all dynamic memory when done with it */
            free( pos_ary );
        }

        /* free up all dynamic memory when done with it */
        free( vc_ary );
    }

    printf( "\n\nPress 'Enter' to continue/exit ... " );
    fflush( stdout );
    return 0;
}
David W 131 Practically a Posting Shark

A very common beginner level simulation is 'rolling a die' or 'rolling a pair of dice', using rand() to get random values in the range 1.. 6

See what you can do coding something like a guessing game with that idea firstly.

alfadil ahmed commented: thank you very much indeed , I appreciate your help. +0
David W 131 Practically a Posting Shark

You could form a string and print the reversed string ...
(i.e. similar to using a 'stack' to unwind the recursive calls)
like this:

#include <stdio.h>

/*
    Write an iterative function char* conversion(unsigned int num, int base),
    that converts an integer num into any base (base <=10).

    How to transform the following recursive function conversion() 
    into (an) iterative:
*/


void conversion( unsigned num, unsigned base )
{
    if( num / base )
        conversion( num / base, base );
    printf( "%u", num % base);
}

/* assumes number is greater than base ... */
void conversion_iterative( unsigned num, unsigned base )
{
    char buf[64]; /* make extra large enough to hold digits */
    int i = 0, size = 0;
    while( num / base )
    {
        buf[size++] = num % base + '0';
        num /= base;
    }
    buf[size++] = num % base + '0';
    buf[size] = 0; /* '\0' terminate */

    /* now reverse string */
    --size;
    while( i < size )
    {
        char tmp = buf[i];
        buf[i] = buf[size];
        buf[size] = tmp;
        ++i, --size;
    }
    printf( "%s", buf );
}



int main()
{
    unsigned num, base;
    printf( "num = " );
    if( scanf( "%u", &num ) == 1 && getchar() == '\n' )
    {
        do
        {
            printf( "base = " );
            if( scanf( "%u", &base ) != 1 )
            {
                printf( "Numbers only here please in range 2..10\n" );
                while( getchar() == '\n' ); /* flush 'stdin' ... */
            }
        }
        while( base < 2 || base > 10 );

        conversion( num, base );
        putchar( '\n' );
        conversion_iterative( num, base );
    }


    return 0;
}
David W 131 Practically a Posting Shark

I would use a struct (with a typedef) to create a data record to track the frequencies of each value in the int array.

Maybe something like this ...

Firstly:

/* most_frequent.c */


#include <stdio.h>
#include <stdlib.h> /* re. malloc */

typedef struct
{
    int val;
    int count;
} ValCount ;

Then some functions:

int update( ValCount* ary, int size, int val )
{
    int i, found = 0;
    for( i = 0; i < size; ++i )
    {
        if( ary[i].val == val )
        {
            ++ary[i].count;
            found = 1;
            break;
        }
    }
    if( !found )
    {
        ValCount tmp;
        tmp.val = val;
        tmp.count = 1;
        ary[size] = tmp;
        ++size;
    }
    return size;
}

int get_i_of_max_count( const ValCount* ary, int size )
{
    int i, i_mc = 0;
    for( i = 1; i < size; ++ i )
    {
        if( ary[i].count > ary[i_mc].count ) i_mc = i;
    }
    return i_mc;
}


void print_positions( const int* ary, int size, int val )
{
    int i;
    for( i = 0; i < size; ++ i )
    {
        if( ary[i] == val ) printf( "%d ", i );
    }
}

Then the main function could be like this:

int main()
{
    int arr[] = { 14, 10, 2, 1, 14, 1, 10, 14, 14, 2, 3, 4, 14, 14, 1, 4, 14, 14 };
    int size = sizeof arr / sizeof *arr ;
    int i, i_mc, size_vc_ary = 0;

    ValCount* vc_ary = malloc( sizeof(ValCount) * size );

    if( vc_ary )
    {
        for( i …
David W 131 Practically a Posting Shark

You might also like to see the info/examples here:
http://www.cplusplus.com/doc/tutorial/polymorphism/

David W 131 Practically a Posting Shark

As Dani's own @rubberman has indicated ... the char '0' has the ASCII int value of 48

But you do not need to worry about memorizing that (48) value,
as you can convert form char to int
for the digits 0...9
very easily like this:

/* problem3.c */

#include <stdio.h>

int main()
{
    const int ary[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const int size = sizeof ary / sizeof *ary;
    int i;
    char buf[256];
    const char* numStr = "123456789";
    const char* p = numStr;

    int sum = 0;
    while( *p != 0 )
    {
        sum += *p - '0';
        ++ p;
    }
    printf( "The sum for 1 to 9 is %d\n", sum );

    for( i = 0; i < size; ++ i )
    {
        buf[i] = i + '1'; /* OR: i+1 + '0'; */
    }
    buf[size] = 0; /* terminate C string with '\0' char ...*/

    printf( "\nHere are the digits 1..9 placed into a C string: %s\n", buf );

    fputs( "\nPress 'Enter' to continue.exit ... ", stdout );
    fflush( stdout );
    getchar();
    return 0;
}
David W 131 Practically a Posting Shark

No bother ... I enjoy seeing students learn new things.

You do realize that char is stored as an int ?

See below to see that getchar() returns an int
http://en.cppreference.com/w/c/io/getchar

So since char are stored as int, you can use an array of int to store the char's
Then just remember to treat (cast) the int values back to char
to get the char with that int value displayed.

See revised demo below:

/* problem_int2char.c */

#include <stdio.h>

#define MAX_SIZE 8


void print( int ary[MAX_SIZE][MAX_SIZE], int, int );



int main()
{
    int ary[MAX_SIZE][MAX_SIZE];

    int row, col;
    for( row = 0; row < MAX_SIZE; ++ row )
    {
        for( col = 0; col < MAX_SIZE; ++ col )
        {
            ary[row][col] = 0;
        }
    }

    /* now add a border of # char's ... */
    for( row = 0; row < MAX_SIZE; ++ row )
    {
        for( col = 0; col <MAX_SIZE; ++ col )
        {
            if( row == 0 || row == MAX_SIZE -1 )
                ary[row][col] = '#';
            else if( col == 0 || col == MAX_SIZE-1 )
                ary[row][col] = '#';
        }
    }


    fputs( "Demo printing int as char ... \n", stdout );
    print( ary, MAX_SIZE, MAX_SIZE ) ;

    fputs( "\nPress 'Enter' to continue.exit ... ", stdout );
    fflush( stdout );
    getchar();
    return 0;
}



void print( int ary[MAX_SIZE][MAX_SIZE], int rows, int cols )
{
    int row, col;
    for( row = 0; row < rows; ++ row )
    {
        for( col = 0; col < …
David W 131 Practically a Posting Shark

Hi again @Rimaa21,
Have you ever heard about the concept of 'backtracking' ?
Suppose you were moving a robot about in some maze, and recording every step by pushing them onto a stack ... but you reach a dead end ... so now ... you can backtrack ... by popping the former moves from the stack, going in the opposite direction you did on the way in ... until you find some new passage way to try ... and then begin to push all those next forward moves onto the stack ... to be able tobacktrack again ...if needed.

Note also ...
that if your reverse a series of elements twice,
you will then get back the original order.

Until we see your complete original program specifications ...
and the code you have tried so far in your attempt to implement a solution ...
we are just best guesssing what your coding problem might be.

David W 131 Practically a Posting Shark

Hi @Rimaa21,

How are you progressing?

Did the see begiinning coding steps ... and the list examples at the link I suggested?

Can you show you show us some code that you have tried so far ... so we can see how to best help you.

Does your stack (structure) need to be an array ... or can it be a linked list?

Also, when you show us the code you have tried so far, please also show the spec's for the problem that you were assigned ... so that we can see clearly, what you were supposed to do.

David W 131 Practically a Posting Shark

Try this ...

/* problem2.c */

#include <stdio.h>
#include <stdlib.h>


#define MAX_SIZE 8


void print( int ary[MAX_SIZE][MAX_SIZE], int, int );


/* void main() */
int main()
{
    int ary[MAX_SIZE][MAX_SIZE];

    int row, col;
    for( row = 0; row < MAX_SIZE; ++ row )
    {
        for( col = 0; col <MAX_SIZE; ++ col )
        {
            ary[row][col] = 0;
        }
    }

    print( ary, MAX_SIZE, MAX_SIZE ) ;

    getchar();

    return 0; /* Note! main function returns an int */
}



void print( int ary[MAX_SIZE][MAX_SIZE], int rows, int cols )
{
    int row, col;
    for( row = 0; row < rows; ++ row )
    {
        for( col = 0; col < cols; ++ col )
        {
            printf( "%d ", ary[row][col] );
        }
        putchar( '\n' );
    }
}
David W 131 Practically a Posting Shark

And ... if you would like to see an example of customer order validation, using some of the power of C++, just ask.

David W 131 Practically a Posting Shark

In particular, if you wish to validate a pruduct number entered by the user, you could maintain a data stucture of valid numbers, either in a file, or loaded into memory in some container like a C++ (sorted) vector and do a binary search / table lookup ... or you may like to use a C++ map or a C++ set container to hold the data for you to do your lookup of unique numbers to see if one already exist in the container.

David W 131 Practically a Posting Shark

If you will Google "C stack" ... you may be surprised how much is at your finger tips but you never looked to see?

A 'stack' is a 'last-in-first-out' (LIFO) data structure that has many uses in programming.

So ... say you have the word "first" and you have a 'stack' to hold characters ...

and if first you put on the stack the char ...
'f'
then 'i'
then 'r'
then 's'
then 't'

Now if you pop the letters from the top of the stack and print them as you pop them, you will print:

tsrif

if you print them all, one after the other, on the same line.

There are many ways one might implement a stack.

One might be to use an array ...
and to advance a pointer into the array
after every element is 'pushed' onto the stack,
then to retreat the pointer after every pop.

Another common way could be
to use a linked list
and push_front to put new elements on the stack ...
then to pop_front ... to pop them off.

If you need help coding a linked-list in C,
you might like to start by looking at several examples linked here:
http://developers-heaven.net/forum/index.php/topic,2022.0.html

If you need to push 'words' onto a stack of 'words' ...
you could use the ClistOfString.h file (and the other files it uses freely available there) to use a Clist of …

David W 131 Practically a Posting Shark

Your code would do well to have a fresh start ...

Do NOT use getch if you want your code to be portable.

Do not mix C and C++ style.

Use functions with good discriptive names to handle each job.

For example, your input could be handled by a function and your validation of the input could also be handled by a function.

You my like to check here ...
http://developers-heaven.net/forum/index.php/topic,2019.0.html
to get some ideas about using functions to validate input.

David W 131 Practically a Posting Shark

Try looking here to see some working examples ...

http://en.cppreference.com/w/cpp/utility/bitset

David W 131 Practically a Posting Shark

What is the output supposed to look like?

David W 131 Practically a Posting Shark

...using push_front and then pop_back ... you can easily do next menu item.

However ...
it makes clearer logic ...
to 'push_back' to add new customers to the end of 'the line' ...
and then to, some-time (asap) later ...
serve the customers from the 'front' of the line ... using pop_front.

David W 131 Practically a Posting Shark

You could also use a list ...
All these containers mentioned so far... 'know their' size (hint for menu item 2)
And, using iterators ... you can easily traverse a list (hint re. menu item 3)
And using push_front and then pop_back ... you can easily do next menu item.

David W 131 Practically a Posting Shark

And just to round out this demo ...
the edits needed to go to a template class
are fairly straight forward
once you have some code working ok for the class List (or struct List) with just an int data type;

Take a look:

// findNextGreatestAfterAvg2.cpp //


#include <iostream>
#include <fstream>

using namespace std; 

const char* FNAME = "numbers.txt";

template < typename T >
class List; // forward declaration //

template < typename T >
class Node
{
public:
    // ctor...
    Node( T key=0, Node* next = 0 ) : key(key), next(next) {}
    T get_key() const { return key; }
private:
    T key;
    Node* next;
    friend class List< T >;
} ;


template < typename T >
class List
{
private:
    Node< T >* head;
    Node< T >* tail;
    size_t len;
public:
    // ctor...
    List( Node< T >* head=0, Node< T >* tail=0 ) :  head(head), tail(tail), len(0) {}
    // detor...
    ~List() { clear();   }

    void clear()
    {
        while( head != 0 )
        {
            Node< T >* cur = head;
            head = head->next;
            delete cur;
        }
        tail = 0;
        len = 0;
    }

    size_t size() const { return len; }

    void push_front( const T& key )
    {
        head = new Node< T >( key, head );
        if( !len ) tail = head;

        ++ len;
    }

    void push_back( const T& key )
    {
        Node< T >* old_tail = tail;
        tail = new Node< T >( key );
        if( len ) old_tail->next = tail;
        else head = tail;

        ++ …
David W 131 Practically a Posting Shark

Did you notice the steps I took to get a solution?

Firstly using the C++ library container to solve the problem at hand.

Then, if you need to code your own 'home-grown' List container ... (a single-link linked list is what you looked to be coding) ... that is a SEPARATE problem.

And when that List is working ok ... just plug-in that List.

See below:

#include <iostream>
#include <fstream>
#include <climits>

using namespace std; 

const char* FNAME = "numbers.txt";

struct Node
{
    int key;
    Node *next;

    // ctor...
    Node( int key=0, Node* next = 0 ) : key(key), next(next) {}
} ;

struct List
{
    Node* head;
    Node* tail;
    int len;

    // ctor...
    List( Node* head=0, Node* tail=0 ) :  head(head), tail(tail), len(0) {}
    // detor...
    ~List() { clear();   }

    void clear()
    {
        while( head != 0 )
        {
            Node* cur = head;
            head = head->next;
            delete cur;
        }
        tail = 0;
        len = 0;
    }

    int size() const { return len; }

    void push_front( int key )
    {
        head = new Node( key, head );
        if( !len ) tail = head;

        ++ len;
    }

    void push_back( int key )
    {
        Node* old_tail = tail;
        tail = new Node( key );
        if( len ) old_tail->next = tail;
        else head = tail;

        ++ len;
    }

    int pop_front()
    {
        if( len )
        {
            Node* cur = head;
            head = head->next;

            --len;
            if( !len ) tail = 0;
            int key = cur->key;
            delete cur;
            return key;
        }

        cout << "List was empty …
David W 131 Practically a Posting Shark

You may like to know that this problem could nicely be handled using a struct and a C++ vector to hold all the struct's ...

struct Temps
{
    double high, low;
} ;

See example below ...

// takeInHighLowTemp.cpp //

/*
    The program should output the
    * average high,
    * average low,

    * and the highest
    * and lowest temperatures,
    * along with the corresponding month.
*/


#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const char* FNAME = "high_low_temps.txt";
/*
42.6 23.7
44.9 25.2
52.0 30.9
61.6 39.1
69.4 47.5
75.7 55.1
78.2 58.9
77.5 57.7
72.0 51.6
63.4 40.8
53.0 32.1
44.9 25.7
*/




struct Temps
{
    double high, low;

    istream& takeIn ( istream& is )
    {
        is >> high >> low;
        return is;
    }
} ;


bool load_from_file( const char* fname, vector< Temps >& vt )
{
    ifstream fin( fname );
    if( fin )
    {
        Temps ts;
        while( ts.takeIn( fin ) ) vt.push_back( ts );
        fin.close();
        return true;
    }
    // else if reach here ...
    cout << "There was a problem opening file: '" << fname
         << "'\n";
    return false;
}

void process_display( const vector< Temps >& vt )
{
    if( vt.size() )
    {
        double avg_low = vt[0].low, avg_high = vt[0].high;
        int m_low = 0, m_high = 0;

        for( size_t i = 1; i < vt.size(); ++ i )
        {
            if( vt[i].low < vt[m_low].low ) m_low = i;
            if( vt[i].high > vt[m_high].high ) m_high = i;
            avg_low += vt[i].low;
            avg_high += vt[i].high;
        }

        avg_low /= …
David W 131 Practically a Posting Shark

What code have you tried do far? (You have not yet given us any real clue about where you are stuck.)

David W 131 Practically a Posting Shark

3) start with setting the 1st int in the new deque as the x value. If the next val is greater than the average and less than that previous x value, update x ... when you have emptied the deque you will have the desired x value;

The above idea was missing some things here ...

You need to firstly go though the container and select, as a comparator, the first element that was greater than the average ... then the above idea is valid.

Also ... you can traverse a deque with iterators.

See below ...
(an example of how this could be coded using the C++ library deque.)

// findNextNumAfterAvg.cpp //

/*
    How i can find the smallest number, higher than average value.

    For example in deque I have these numbers:
    46 84 25 93 91 25 37 32 64 49 17 81 59 38 79 22 57 17 61 11
    (transferred from file Stack.txt to deque.txt).

    The average of these numbers is 49.4,
    and the smallest number greater than this value should be 57.
    I should find it without using arrays.

*/


#include <iostream>
#include <fstream>
#include <deque>

using namespace std;

const char* FNAME = "numbers.txt";
/*
46 84 25 93 91 25 37 32 64 49 17 81 59 38 79 22 57 17 61 11
*/


bool load_from_file( const char* fname, deque< int >& dq )
{
    ifstream fin( fname );
    if( fin )
    {
        int i;
        while( fin >> i ) …
David W 131 Practically a Posting Shark

So you have several problems ...

/*
1) using the C++ library deque (FIFO) container to the hold the int's input from file
2) using pop / push onto a 2nd deque ...  get sum/size to get average
3) start with setting the 1st int in the new deque as the x value.
   if the next val is greater than the average and less than that previous x value, update x
    when you have emptied the deque you will have the desired x value;
4) when you get all the above debugged and working ok, code you own class Deque 
    (if you must) 
    and use that in the place of the C++ library deque you developed with above.
    */
David W 131 Practically a Posting Shark

For your simple program ...
the first suggest by Dani's @ryantroop is quite adequate.

include stdlib.h and time.h.

then ...

     /* seed the random gerator ... */
     srand (time(0) ); /* somewhere near the top of main */

     /* then can do this as needed */
     /* give me a random number between 1 and 20 */
     int iRand = rand() % 20 + 1;