David W 131 Practically a Posting Shark

I almost never (code in a)

return 0;

at the end of main ...
IN a C++ program

Wheres as,

IN C ...

one ALWAYS needs to return an int value in main, and to code that in explicitly, if the compiler conforms to any standard from C89/C90 forward ...

BUT ...

in C++,

with every standard C++ (since at least C++98? ... maybe earlier?) ...

the (standard conforming) compiler WILL ALWAYS supply code to return 0 for the program, if the programmer did not code it in ...

This is similar to how the C++ compiler will always supply code for a default ctor... if NO ctors were coded in a class ... or a struct ... in C++

So, please feel very comfortable NOT being concerned about the programmer adding code,

return 0;

at the end of main, in a C++ program, because the compiler will then always code it in for you.

The only place(s) where you may need to code return 0 (or some other int value) ...

IS ...

if you are returning from some other place(s) BEFORE the end of main is reached.

Please note also, a trend in C++ ...

with C++11 to C++14 ...

it seems to be the trend to have the compiler DO MORE (behind the scenes) supplying code ...

so that the programmer can do less mundane typing ... just to do various routine jobs ...

for example:

for( auto item : someCppContainer ) cout << item << endl;

David W 131 Practically a Posting Shark

Do you know what a struct (a data record) is ?

Do you know how to use arrays?

One nice way to handle this might be to create a const array of pairs of (product, price) ...

Maybe something like this:

#include <string>

// ...

struct Item
{
    string name;
    float price;
} ;

const Item ITEMS[] =
{
    {"mouse", 100},
    {"keyboard", 129},
    {"monitor", 300},
    {"CPU",500}
    {"Package", 3000}
} ;

const int NUM_ITEMS = sizeof ITEMS/ sizeof *ITEMS;

Then could use a struct Order,
maybe something like this:

struct Order
{
    int id;
    int quanity[NUM_ITEMS];
    float getTotal() const;
    {
        float sum = 0;
        for( int i = 0; i < NUM_ITEMS; ++ i )
        {
            sum += quanity[i]*ITEMS[i].price;
        }
        return sum;
    }
} ;

Then, maybe a takeInOrder function
something like this:

void takeInOrder( Order& ord )
{
    ord.id = takeInInt( "Enter the order id" );
    for( int i = 0; i < NUM_ITEMS; ++ i )
    {
        ord.quanity[i] = takeInInt( "How many " + ITEMS[i].name + ": " );
    }
}

Of course the above, pre-supposes that you have already defined a function like ...

int takeInInt( const string& msg )
{
    while( true )
    {
        cout << msg << flush;
        int tmp;
        if( cin >> tmp && cin.get() == '\n' && tmp >= 0 )
            return tmp;
        // else ...
        cin.clear(); // clear any error flags
        cin.sync(); // 'flush' cin stream
        cout << "\nPlease enter only integers >= 0 …
David W 131 Practically a Posting Shark

I found this a short time ago and thought it looked interesting enough to test it out... (I only tested it on a MS Windows OS.)

/* cpu_times.h */

/*
found at:
http://stackoverflow.com/questions/17432502/how-can-i-measure-cpu-time-and-wall-clock-time-on-both-linux-windows

*/

#ifndef FoundOnWeb_CPU_TIMES_H
#define FoundOnWeb_CPU_TIMES_H

/*  Windows */

#ifdef _WIN32
#include <Windows.h>

double get_wall_time()
{
    LARGE_INTEGER time, freq;
    if (!QueryPerformanceFrequency(&freq))
    {
        /*  Handle error */
        return 0;
    }
    if (!QueryPerformanceCounter(&time))
    {
        /*  Handle error */
        return 0;
    }
    return (double)time.QuadPart / freq.QuadPart;
}

double get_cpu_time()
{
    FILETIME a, b, c, d;
    if ( GetProcessTimes( GetCurrentProcess(), &a, &b, &c, &d ) != 0 )
    {
        /*  Returns total user time.
            Can be tweaked to include kernel times as well. */
        return
            (double)(d.dwLowDateTime |
            ((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
    }
    else
    {
        /*  Handle error */
        return 0;
    }
}

/*  Posix/Linux */
#else

#include <sys/time.h>
double get_wall_time()
{
    struct timeval time;
    if( gettimeofday( &time , NULL ) )
    {
        /*  Handle error */
        return 0;
    }
    return (double)time.tv_sec + (double)time.tv_usec * .000001;
}
double get_cpu_time()
{
    return (double)clock() / CLOCKS_PER_SEC;
}

#endif


#endif /* FoundOnWeb_CPU_TIMES_H */

If trying to compare, for example, two sort methods, of a large array of data redords ...

I usually, simply track the clock times, for several runs,

(maybe 5 to 10 runs each, and often in different orders of being run ... also),

and then take an average, (and some times even the sd),

to get a feel for the real running time the process could …

David W 131 Practically a Posting Shark

You may also like to see this:

(that attempts to salvage your 'get_word' function ...
and then to add some extras)

/* get_word.c */


#define MAX_LEN_STR "255"
#define MAX_LEN 255

#define NUM_WORDS 3

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


#ifndef dwMYASSERT
#define dwMYASSERT
void myAssert( int condition, const char* msg )
{
    if( !condition )
    {
        fprintf( stderr, "%s\n", msg );
        fputs( "Press 'Enter' to exit program ... ", stderr );
        getchar();
        exit(1);
    }
}
#endif

#ifndef dwMY_STRLEN
#define dwMY_STRLEN
size_t my_strlen( const char* str )
{
    if( str ) return strlen(str);
    return 0;
}
#endif

#ifndef dwNEWMEMORY
#define dwNEWMEMORY
char* newMem( int bytes )
{
    char* n = (char*) malloc( bytes ); /* cast (in case) C++ compiler */
    myAssert( (n != NULL), "Error: malloc failed in 'newMem' ... " );
    return n;
}
#endif

#ifndef dwNEWCOPY
#define dwNEWCOPY
char* newCopy( const char* str )
{
    char* n = newMem( (my_strlen(str) + 1)*sizeof(char) ); /* cast for C++ compilers */
    strcpy( n, str );
    return n;
}
#endif


#ifndef dwNEWFGETSFIXED
#define dwNEWFGETSFIXED
char* newFgetsFixed( FILE* fin )
{
    char buf[MAX_LEN+1];

    if( fgets( buf, sizeof(buf), fin ) )
    {
        char *p = strchr( buf, '\n' ), c ;
        if( p ) *p = 0; /* strip off '\n' at end ... IF it exists */
        else while( (c = fgetc( fin )) != '\n'  &&  c != EOF ) ; /* flush... */
        return newCopy( buf );
    }
    else return NULL;
}
#endif

#ifndef dwGETWORD
#define dwGETWORD
char* …
David W 131 Practically a Posting Shark

@rubberman

Do you forget that this was a C++ program ... and just using C stuff in it :)

http://en.cppreference.com/w/cpp/string/byte/memset

// demo_memset.cpp //

/*
http://en.cppreference.com/w/cpp/string/byte/memset
*/


#include <iostream>
#include <cstring> // re. memset //

const int BUF_LEN = 20;

struct Student
{
    int id;
    char fName[BUF_LEN];
    char lName[BUF_LEN];

    void print() const
    {
        std::cout << id << ": " << lName << ", " << fName;
    }
} ;


int main()
{
    int iAry[3];
    std::memset( iAry, 0, sizeof iAry ) ; // initial all memory to 0 //

    std::cout << "sizeof iAry = " << sizeof iAry << '\n';

    iAry[1] = 1; // give one array element same value //

    for( int i = 0; i < 3; ++ i )
        std::cout << i << ", " << iAry[i] << '\n' ;

    std::cout << "sizeof iAry = " << sizeof iAry << '\n';



    Student myStuds[3];
    std::memset( myStuds, 0, sizeof myStuds );

    std::cout << "sizeof myStuds = " << sizeof myStuds << '\n';


    // give one array element same value //

    myStuds[1].id = 1;
    strcpy( myStuds[1].fName , "Sam" );
    strcpy( myStuds[1].lName , "Jones" );

    for( int i = 0; i < 3; ++ i )
    {
        myStuds[i].print();
        std::cout << '\n';
    }
    std::cout << "sizeof myStuds = " << sizeof myStuds << '\n';
}
David W 131 Practically a Posting Shark

Firstly ...

please note that it is a bad idea to use

#include <conio.h> 

// and later ... //

getch(); 

if you wish to have portable code that conforms to standard C++

Maybe, by "hard-coding" you were thinking of this ?

Consider:

struct Student
{
    int id;
    string name;
};

// ...

Student studs[] =
{
    { 1, "Sam" },
    { 2, "Joe" },
    { 3, "Pat" )
} ;
const int size = sizeof studs / sizeof *studs;


// ...

for( int i = 0; i < size; ++ i )
    cout << studs[i].id << ", " << studs[i].name << '\n';
David W 131 Practically a Posting Shark

@ShiftLeft,

I think the OP stated ...

average; // ... display in decimal

thus there is a problem with what you suggested, and also ...

int Grades [4], Average, Total; // you meant to have Total = 0; // here //
for (int count=0; count < 4; count++) {
    cout << "Grade " << count + 1 << ": ";
    cin >> Grades [count];
    Total += Grades [count]; // Total NEEDS an inital value of 0 //
}
Average = Total / count; // integer division here & ?scope of count? //

The above will only give the (rounded down) integer quotient (after integer division ... which integer value may also NOT help obtain the correct letter grade.)

To get the decimal fraction results, the OP desires,
it is easy to just do this:

#include <iostream>

const int NUM_GRADES = 4; 


int main( void ) 
{
    using std::cout; using std::cin;

    int grades[NUM_GRADES]; 
    double total = 0.0; // INITIAL to ZERO here //
    int count = 0 ; // count needs this 'scope' //
    while( count < NUM_GRADES ) 
    { 
        cout << "Grade " << (count + 1) << ": ";
        if( cin >> grades[count] && cin.get() == '\n' )
        {
            total += grades[count];
            ++ count; // update count ONLY on good data //
        }
        else // bad data entry ... so ...
        {
            cin.clear(); // clear any error flags //
            while( cin.get() != '\n' ) ; // flush cin stream //
            cout << "\nPlease …
David W 131 Practically a Posting Shark

@Petcheco,

wrt your suggestion ... please note added comments below:

cout << "Enter your string:";
getline(cin, myString); // this will read the whole line
cout<<"Enter your name: ";
getline(cin, myName);   // this will read the whole line
// cin.sync(); // SO this is *NOT needed* here //

/*
cout<<"Age: ";
cin>>age;
cin.sync(); // may fail here if cin >> age failed
*/
while( true )
{
    cout << "Age: ";
    if( cin >> age && cin.get() == '\n' )
        break; // since good data was entered followed by '\n' char //

    // else if reach here ...

    cin.clear(); // clear any error flags
    while( cin.get() != '\n' ) ; // flush cin stream //
    cout << "\nPlease enter ONLY a valid integer here ...\n";
}
David W 131 Practically a Posting Shark

@basitji,

If you wish help on your C++ programming problem, you need to firstly show us the code that you have tried so far ... and any compiler errors.

David W 131 Practically a Posting Shark

@waqas tayyab,

If you wish help on your different C++ programming problem,
please start 'a new thread'.

Do NOT just add your different question to the end of an existing one.

Also, you need to show us the code that you have tried so far ...
and any compiler errors.

David W 131 Practically a Posting Shark

Can you write a 'shell' program that compiles and runs ok ...
producing the exact output expected?

What might you put in a start-up working 'shell'?

#include <iostream>

const int MAX_SIZE_HERE = 10; // keep small at start to keep testing easy //


int main()
{
   // print some opening message ...

   // declare your arrays
   // in a loop for i from 0 to < MAX_SIZE_HERE
   int i = 0
   while( i < MAX_SIZE_HERE )
   {
      // prompt for each fruit and also take in num_desired each 
      // and store at index i in each array
      // ...
      // ...
      // ...
      // ...
      // calculate and show bill for this index i

      ++ i; // update array index
    }

    // print some ending message if needed ...
    std::cout << "\nAll done now.\n";

    // add these next 2 lines if needed ...
    std::cout << "\nPress 'Enter' to continue/exit ... ";
    std::cin.get(); // to keep 
}
David W 131 Practically a Posting Shark

//Hint:

//Do you know what modular arithmetic (here, division) means?

//If you have these next two integers stored in 'a' and 'b':

int a = 23;
int b = 10;

// Do you know what values the following x, y would hold?
int x = a / b ;
int y = a % b ;

// if not,
// study (do a web search on)
// 'integer division'
// and also
// 'modular division'.

David W 131 Practically a Posting Shark

Addendum:

The comments at the top of the function below ...
are hopefully obviously seen to be wrong.

I simply forgot to change the comments (delete the comments) when I changed the code ...
from returning a void ... and passing in a ref...
to passing in a const value and returning the updated size.

// returns new size by ref... //
int takeInAndWrite( fstream& fs, const int siz )
{
    Student stud;
    int count = siz;
    while( true )
    {
    // ...

Also, I was thinking about the problem called the 'endian problem' ...

http://en.wikipedia.org/wiki/Endianness

A way to handle that problem could be to change both the integers in the struct to fixed length C strings if reading in number data as numbers ...and then converting them to strings to be stored in the struct

Then reverse the proccess after reading the struct back from file.

David W 131 Practically a Posting Shark

P.S.

This validation check should also be added ...

Matrix mat1, mat2;
do
{
    int n = takeInInt( "Enter n to see it's pattern: " );

    // add in this check //
    if( n < 1 )
    {
        cout << n << " < 1 is NOT valid input here ...\n";
        continue;
    }

    // .... rest of code ...
David W 131 Practically a Posting Shark

Further to the above Posting Pro @ Schol-R-LEA comments ...

and since ... the meaning to be helpful @ Aditya_13 ...
posted his first code here ...

please also note these comments that are also meant to be helpful to, now especially, @ Aditya_13 ...

Please take a look at the revisions and comments in this revision of the code posted, that uses some of the power tools of C++ ... power tools like over-loading operators and vector containers ... and of course ... the general tool of breaking up a problem into steps ... each step having its own function

The goal here was not to as brief as possible, but rather to make clearer the steps to a solution ...

// print_pattern.cpp //

// these are old style //
//#include<iostream.h>
//#include<conio.h> // do NOT use if you wish code to be portable //
//#include<math.h>

#include <iostream>
#include <string>
#include <vector>
#include <cmath>

using namespace std;

#define myDebug 0 // toggle zero & one ... to turn off & on //


/////////////////////////////////////////////
// some helpful student utility functions //
int takeInInt( const char* msg);
int takeInChr( const char* msg );
bool more();
/////////////////////////////////////////////


/*
If N=4 the code should print the following pattern.
                                 1*2*3*4*17*18*19*20
                                 --5*6*7*14*15*16
                                 ----8*9*12*13
                                 ------10*11
Again if N=5 the code should print
                                 1*2*3*4*5*26*27*28*29*30
                                 --6*7*8*9*22*23*24*25
                                 ----10*11*12*19*20*21
                                 ------13*14*17*18
                                 --------15*16
For N=2  the pattern will be
                                 1*2*5*6
                                 --3*4

*/

// from the pattern above, it seems that ...
// if n = 4, 4*5 = 20 numbers are …
David W 131 Practically a Posting Shark

Ah ha ...

@ArpitJ.25

you have arrived at a wonderful spot to hang out to see all the code examples sailing past you ...

Now ... if you try out the easy examples ... see if you can make some changes and fixes ...

Note all the compiler error messages and how to fix them ...

You will soon enough be sailing too :)

David W 131 Practically a Posting Shark

Note: There are many way to design a solution ...

Here is just one simple way ...

and a shell program that should get you started:

// cal_shell.cpp //


#include <iostream>

using namespace std;

// your functions go here ...??

double add( double a, double b )
{
    return a + b;
}

 double sub( double a, double b )
{
    return a - b;
}

// ... the rest of your functions go here //



int main() 
{
    // print out an intro...

    // prompt and take in the op requested ...add, sub, etc...
    cout << "Which op ... Enter + or - or ... ";
    char op = 0;
    cin >> op;

    double a = 0.0, b = 0.0, c = 0.0; // get some doubles

    // now prompt and take into 'a' annd 'b' valid doubles

    switch( op )
    {
        case '+' : c = add( a, b ); break;
        case '-' : c = sub( a, b ); break;

        // ... rest goes here ...//



        default:
            cout << op << " is NOT implemented here yet ...\n";
    }

    cout << "for the binary op " << op << " on " << a << " and " << b
         << ", the result returned was " << c << endl;
    cout << "All done ... press 'Enter' to cobtinue/exit ... " << flush;
    cin.get();
}
David W 131 Practically a Posting Shark

You could try something like this ... to get you started:

// binFile_structStudent.cpp //


// This example allows ONLY UNIQUE student ID's //

#include <iostream>
#include <fstream>
#include <cstring> // re. strcpy
#include <climits> // re. INT_MAX, INT_MIN


using namespace std;


// NOTE! file gets created first time program is run //
const char* FNAME = "stud.bin";

const int MIN_ID = 1000;
const int MAX_ID = 9999;
const int MIN_MARK = 0;
const int MAX_MARK = 100;
const int TOT_NAME_CHARS = 20;



struct Student
{
    int id;
    char name[TOT_NAME_CHARS];
    int mark;

    // ctors ... //
    Student() : id(-1), mark(-1) { strcpy( name, "unknown"); }
    Student( int i, const char* n, int m ) : id(i), mark(m) { strcpy( name, n); }

    fstream& save( fstream& fs ) const
    {
        fs.write( (char*)this, sizeof(Student) );
        return fs;
    }
    fstream& load( fstream& fs )
    {
        fs.read( (char*)this, sizeof(Student) );
        return fs;
    }

    void print() const
    {
        cout << id << ' ' << name << ' ' << mark;
    }
} ;



////////////////////////////////////////////////////////////
// BEGIN 5 UTILITIES helpful to students here //////////////
int takeInInt( const char* msg, int min = INT_MIN, int max = INT_MAX )
{
    int val = 0;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
        {
            if( val >= min && val <= max )
            break;
            cout << "Valid input range here is: "
                 << min << ".." << max << endl;
        }
        else
        {
            cout << "Valid integers …
David W 131 Practically a Posting Shark

Can you show us the code you have so far?

in a loop :

    step 1 input a number after a prompt was printed

    step 2 check if number was in valid range 1..100
           if not 
           after printing error message
           continue back from loop top

    step 3 get computer to produce a random value in range 1..100

    step 4 ...
David W 131 Practically a Posting Shark

You have NOT supplied enough info about your problem.

Using some functions would help to see each of the problem steps.

Also ... using some global constants could help here ...
maybe for something like the following:

if total_kms >= STEP3_RATE_KMS use_rate = STEP3_RATE;
else if total_kms >= STEP2_RATE_KMS use_rate = STEP2_RATE;
else use_rate = STEP1_RATE;

David W 131 Practically a Posting Shark

Late comment to add:

(It is too late now to edit the above code.)

// It might be better to just use a double for the total ? //
// Be aware of the potential problem in the result when you divide
// an integer value by an other integer value !!! //

David W 131 Practically a Posting Shark

Late comment to add:

(It is too late now to edit the above code.)

// It might be better to just a double for the total ? //
// Be aware of the potential problem in the result when you divide
// an integer value by an other integer value !!! //

David W 131 Practically a Posting Shark

You may fine this little edit/clean_up of your code ... a useful example for your future coding problems ...

Note: little typos in your code will cause your code to NOT compile.

For example:

for (moneky = 0, monkey ...
What is the typo above?

// monkey_food.cpp //


#include <iostream>
#include <iomanip>
#include <string>

using namespace std;


const int MONKEY_TOT = 3; // number of monkeys
const int NUM_DAYS = 2;   // KEEP small for testing, change later //


void takeInFoodEaten( double food[MONKEY_TOT][NUM_DAYS] );
void dispFoodEaten( double food[MONKEY_TOT][NUM_DAYS] );




int main ()
{
    double food[MONKEY_TOT][NUM_DAYS]; // array to store information

    // You are NOT using these !!! //
    /*
    int monkeys;
    int days;
    int most = 0;
    int least = 0;
    int total = 0;
    double average = 0;
    */

    takeInFoodEaten(food);

    // rest of program done here //
    dispFoodEaten(food);

    return 0;
}





void takeInFoodEaten(double food[MONKEY_TOT][NUM_DAYS])
{// Fill array with numbers
    for( int monkey = 0; monkey < MONKEY_TOT; monkey++ )
    {
        for( int day = 0; day < NUM_DAYS; day++ )
        {
            cout << "Enter pounds of food eaten by monkey "
                 << (monkey + 1) << ", day " << (day + 1) << ": ";
            cin >> food[monkey][day];
            cout << "You entered : " << food[monkey][day] << endl;
        }
        cout << endl;
    }
}


void dispFoodEaten( double food[MONKEY_TOT][NUM_DAYS] )
{// Sum all food eaten (array elements) by all monkeys

    int total = 0, monkeyDayMealCount = 0;
    double average = 0;

    for( int monkeys = …
David W 131 Practically a Posting Shark

Ok ... bad idea to use conio.h and getch ... if you want to use standard C++ and have portable code ...

But where is your attempt to use the C++ find a string function ... to find some string in some longer string?

Instead of using getch to keep the window open at the end ...

Keep the cin stream flushed (as you go) ... and then you can use cin.get() at the end to keep the window open.

Did you check the link?

http://www.cplusplus.com/reference/string/string/find/

David W 131 Practically a Posting Shark

Maybe you are thinking of a hash table... a kind that also uses lists ???

http://en.wikipedia.org/wiki/Hash_table#Separate_chaining_with_other_structures

Chained hash tables with linked lists are popular because they require only basic data structures with simple algorithms, and can use simple hash functions that are unsuitable for other methods.

David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

Can you show us what code you have tried so far ... so that we can see where you need help?

Can you write out the steps you might do on paper?

1st step ... enter amount of water used in each month (in a loop so can do calculation for each next month)

ONE way to help guide you to code a solution is to use fake code like this:

loop until break out of loop:
   take in amount used
   if amount was zero break out of loop
   calculate bill
   print bill
David W 131 Practically a Posting Shark

See if you can make the changes suggested above ... then try it out and re-submit the new version for help ... if you need more help?

I would suggest also some more descriptive variable names ... names that help you see what is happening as the program flows ...

string my_str;
cout<<"Please enter your paragraph.."<<endl;
getline (cin, my_str);

could be changed to

cout << "Please enter your paragraph ... \n";
string paragraph;
getline( cin, paragraph );

And ... could use ...

cout << "Please enter a word to find : " << flush;
string word;
getline( cin, word ); 

This link is a also a good ref... to keep handy ...

http://www.cplusplus.com/reference/string/string/find/

Hint!

If you want to find all the words that repeat in a big string of words ...
you will need a loop ...

and as you keep searching for the next possible place the search word occurs

you will have to keep up-dating the position to begin on each call to find

so ...

use the form of find that allows you to pass in the start index ...
i.e the position to begin the new search in the string to be searched.

David W 131 Practically a Posting Shark

You could use something like this:

struct WeekData
{
    int weekNum;
    int values[7][2];

    // ctor...
    WeekData( int weekNum, int new_values[7][2] ) : weekNum( weekNum )
    {
        for( int i = 0; i < 7; ++ i )
        {
            values[i][0] = new_values[i][0];
            values[i][1] = new_values[i][1];
        }
    }

    double get_avg() const
    {
        double sum = 0;
        for( int i =0; i < 7; ++ i ) sum += values[i][0] + values[i][1];
        return sum/14;
    }
    int get_max() const
    {
        int max = values[0][1];
        for( int i = 1; i < 7; ++ i )
             if( values[i][1] > max ) max = values[i][1];
        return max;
    }
    int get_min() const
    {
        int min = values[0][0];
        for( int i = 1; i < 7; ++ i )
             if( values[i][0] < min ) min = values[i][0];
        return min;
    }

    // show all the info for this week ... //
    friend std::ostream& operator << ( std::ostream& os, const WeekData& wd )
    {
        os << "For week " << wd.weekNum << ":\n";
        for( int i = 0; i < 7; ++ i )
             os << wd.values[i][0] << ":" << wd.values[i][1] << ' ';
        os << "\nmin: " << wd.get_min() << ", max:" << wd.get_max()
           << ", avg: " << wd.get_avg() << '\n';

        return os;
    }
} ;

You could use these to create some random values:

double random() { return double( rand() )/RAND_MAX ; }

int random_in_range( const int RAND_BOT, const int RAND_TOP )
{
    return (RAND_TOP-RAND_BOT+1) * random() + RAND_BOT ;
}

Then you …

David W 131 Practically a Posting Shark

So ... show us an example of the data you were given to process.

David W 131 Practically a Posting Shark

What have you tried?

It would help if you would show us an example of the (file) data (structure) that you seem to need to read and process,

David W 131 Practically a Posting Shark

Can you solve the problem on paper?

If you can ... then turn those steps into code ... and show it, as far as you can go.

David W 131 Practically a Posting Shark

If one apple costs 65 cents, how much will n apples cost?

Do you know how to multiply n*65 for all (positive integer) values of n?

David W 131 Practically a Posting Shark

You could use a 'Table Look Up' method ...

I need help to display on the screen rock when user picks rock, paper when user picks paper, and scissors when user picks scissors. Thanks

// define table ...
const char* CHOICES[] = { "ROCK", "PAPER", "SCISSORS" };

// function prototype ...
int takeInValidIntInRange( const char* prompt, int min, int max );


// in main ...

cout << "Choices are ";
for( int i = 0; i < 3; ++ i ) cout << "(" << (i+1) << ") " << CHOICES[i] << " ";
cout << endl;

int choice = takeInValidIntInRange( "Enter an integer in the range 1..3: ", 1, 3 );

cout << "Your choice was: " << CHOICES[choice-1] << endl;
David W 131 Practically a Posting Shark

You need to clarify your original problem ...

  1. Are you wanting, to instead, sort the array in descending order?

Or...

  1. having sorted the array in ascending order,
    do you THEN want to move the element at index 0,
    to the memory location at index size-1,
    having moved all the elements up one place first?

If 2. is the case, then @prvnkmr449 has supplied the steps.

This edit make help?

int tmp = array[0]; // get copy of element at index 0

for( int i = 0; i < arraySize-1; ++ i )
    array[i] = array[i+1]; // copy-over  / move each element up one

array[arraySize-1] = tmp;
David W 131 Practically a Posting Shark

What do you think it is ... and why?

http://en.cppreference.com/w/cpp/algorithm/copy

David W 131 Practically a Posting Shark

Since you mentioned pointers were to be used as part of your solution ...

I'm wondering if the prof meant ... function pointers?

If so ... then this might get you started:

int add( int a, int b )
{
    return a+b;
}
int sub( int a, int b )
{
    return a-b;
}
int mul( int a, int b )
{
    return a*b;
}
int dvd( int a, int b )
{
    if( b ) return a/b;
    // else ...
    cout << "DIVIDE by ZERO ERROR ... INVALID "
         << INT_MIN << " returned ...\n";
    return INT_MIN; // divide by zero returned error value //
}

// f is a function pointer ... //
int binOP( int a, int b, int (*f) (int, int) )
{
    return f( a, b );
}
David W 131 Practically a Posting Shark

I have found Orwell Dev-C++ to work well for C++11 and before ... it is easy for students to use ... can easily compile a single (student type problem) file (withOUT needing to make a project) ... and run to see the output ... without having to add code to keep the window open when the program is done.

im looking to brush up on my C++ coding

Take a look at these edits ...
1. functions used
2. code reuse made easy via using an include file for the bubble sort
3. comment as you go ...
.
.
.

// test_bsort_ary.cpp //

#include <iostream>
#include <cstdlib> // re, rand
#include <ctime> // re. srand


#include "bsort_ary_vec.h"


//using namespace std;


// can easily adjust array size here as desired ...
// (and then recompile) //
const size_t SIZE_RAN = 20;


// can show arrays of any type ...
template < typename T >
void showAry( const T* ary, size_t size, size_t numOnLine = 10 )
{
    using std::cout; using std::endl;

    for( size_t i = 0; i < size; ++ i )
    {
        if( i % numOnLine == 0 ) cout << endl;
        cout << ary[i] << ' ';
    }
    cout << endl;
}



int main ()
{
    using std::cout; using std::endl;

    // random seed
    srand( (unsigned)time(0) ); 

    // reserve space to hold numbers
    unsigned ranNums[SIZE_RAN];

    // fill ary with random numbers
    for( size_t i = 0; i < SIZE_RAN; ++ …
David W 131 Practically a Posting Shark

If you can use an 'helper' calling function then ... HINT:

double sumToN( const double nSum, const double x, const double nTerm, const int N )
{
    // if( N ...... /// return nSum;
    // return sumToN( nSum + /////////////////////
}

// helper calling function ...
double sumToN( const double x, const int N )
{
    return sumToN( 0, x, x*x, N );
}

Just fill in the 2 lines and you are done.
David W 131 Practically a Posting Shark

Try somethinh like this:

class Transaction
{
public:
    Transaction(QString type, QDateTime datetime) : m_Type(type), m_DateTime(datetime) {}
    QString getType() const { return m_Type; }
    QString toString() const { return m_Type + " @ " + m_DateTime; }
    QDateTime getDateTime() const { QDateTime now; return now.get_date_time(); }
    virtual double computeCost() = 0;
protected:
    QString m_Type;
    QDateTime m_DateTime;
} ;

class Deposit : public Transaction{
public:
    // note order beloe ... //
    Deposit(double amount) : Transaction("Deposit", getDateTime() ), m_Amount(amount) {}

    QString toString() const;
    double computeCost();
private:
    double m_Amount;
    static double m_Fee;
};
David W 131 Practically a Posting Shark

Can you start the non-recusive function ... show what you can do ... so we can see what you are missing ... hopefully ... not everything :)

David W 131 Practically a Posting Shark

An other hint?

What could the function prototype look like?

int sumToN( const int nSum, const int nTerm, const int N );

What would the tail recursive call look like?

How would you call the the function?
(What initial values ?)

David W 131 Practically a Posting Shark

Please post the code you have tried already, the part that is causing you a problem ... and a copy paste of the compiler error message, if any.

Also, the specs for the program, (or a brief description of what the program is supposed to do), so we can easily see what you were supposed to do.

David W 131 Practically a Posting Shark

This edit from part of your code above, may give you some further ideas to help you see how you you might break up the code into jobs (functions)... and thus make the logic flow easier to see ...

/* PizzaHut2.c */

#include <stdio.h>
#include <ctype.h> /* re. tolower */


/*header*/
const char* HEADER = "\t\t\t\t    Pizza Hut\n\t\t\t\t  Billing System\n\t\t\t   Philippines Food Corporation\n";


void showMenu1()
{
    printf("                                    ===                            \n");
    printf("                                  ========                         \n");
    printf("                                ==============                     \n");
    printf("                             ====================                  \n");
    printf("                           =========================               \n");
    printf("                       ===================================         \n");
    printf("                  =============================================    \n");
    printf("              =====================================================\n\n\n");
    printf("\t  ========   ==                          ==    ==            ==   \n");
    printf("\t  ==     ==  ==                          ==    ==            ==   \n");
    printf("\t  ==     ==                              ==    ==            ==   \n");
    printf("\t  ==     ==  ==  ======  ====== ======   ========  ==   == ====== \n");
    printf("\t  ========   ==     ==      ==      ==   ==    ==  ==   ==   ==   \n");
    printf("\t  ==         ==    ==      ==   ======   ==    ==  ==   ==   ==   \n");
    printf("\t  ==         ==   ==      ==    =   ==   ==    ==  ==   ==   ==   \n");
    printf("\t  ==         ==  ======  =====  ======   ==    ==  =======   ==   \n\n\n");
    printf("\t\t\t     [ 1 ] - Make an order.\n");
    printf("\t\t\t     [ 2 ] - Exit.\n\n");
}

const char* CHOICES[] = { "Hawaiian Supreme", "Cheesy Pepperoni", "Meat Lovers Pizza", "Bacon Supreme" };
const float PRICES[] = { 250, 275, 260, 290 };


void showMenu2()
{
    printf("\n================================================================================");
    printf("\t\t\t\t       MENU\n");
    printf("================================================================================");
    printf("\n\tCode:\tPizza flavors:  \t       Price\t\t\n");
    printf("\t(1)  \t\tHawaiian Supreme       \tPhp250.00\t\t\n");
    printf("\t(2)  \t\tCheesy Pepperoni       \tPhp275.00\t\t\n");
    printf("\t(3)  \t\tMeat Lovers Pizza      \tPhp260.00\t\t\n");
    printf("\t(4)  \t\tBacon Supreme          \tPhp290.00\t\t\n");
    /*printf("\t(5)  \tDrinks available:\n\t\t\t>Coke\n\t\t\t>Iced Tea\n\t\t\t>Mineral Water\n\n");*/
    printf("================================================================================\n");
}

void order();
void …
David W 131 Practically a Posting Shark

This little example, uses functions to help you see the logic flow:

typedef struct
{
    int item1;
    int item2;

    /* ... */
    int itemN;
} Order ;

const char* MENU = " ... stuff on menu ... ";

/* prototypes */
void initialOrder( Order* );  /* initial all to zero */
void showMenuFillOrder( Order* );
void showOrder( const Order* );
double getBill( const Order* );

int more( void ); /* asks if more, returns NO =0, YES = 1 */

int main( void )
{
    do
    {
        double bill;
        Order tmp;
        initialOrder( &tmp ); /* address passed in */

        showMenuFillOrder( &tmp );
        showOrder( &tmp );
        bill = getBill( &tmp );
        printf( "Your bill was: %.2f\n", bill );
    }
    while( more() );

    return 0;
}
/*  function def'ns follow here ... */
David W 131 Practically a Posting Shark

Whow ... that is a lot of code to scan through !

First off ...

You must be using an ancient NON-standard C compiler !

The standard is: int main() ... i.e. main returns an int value

/*Placement*/
void order( void );
void lo( void );

/* ............. */

int main( void )
{
   /* your code goes here */
   return 0;
}

/* ............. */

Think of the logic flow ...

What do you do first ... then next ... then next ...

Are there any branches?
(You have many cases...)
If so ...
What are the conditions on any of the branches?

Are there any loops?
I see SEVERAL goto loops ... BETTER to re-code using ...

while( ... ) /* your big loop */
{  
   /*    */
   if( conditionA ) continue; /* go to top of while now */

   /*     */
}

Do you know how to pass in parameters to functions?

Do you know how functions can return a value (or values) ?

Using more functions to break up each little job into a well named function could be a big help to you to SEE the FLOW of the logic in the program.

David W 131 Practically a Posting Shark

If the pattern holds ( as per @ddanbe )...

you might like to try parsing, using the power of C++ stringstream,
something like this ...

// getFileDataParsed.cpp //

/*
    I have a text file that represents a book ,
    this first line of it for example is:

    P.G. Wodehouse, "Heavy Weather 1" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
    P.G. Wodehouse, "Heavy Weather 2" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
    P.G. Wodehouse, "Heavy Weather 3" (336 pp.) [PH.411 AVAILABLE FOR LENDING]
    P.G. Wodehouse, "Heavy Weather 4" (336 pp.) [PH.411 AVAILABLE FOR LENDING]

    So there is:
    authors name,
    title,
    number of pages
    and if the book is available.

    As they are not all seperayed by a comma,
    how can I read this file and store them in appropriate arrays ?

*/

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

using namespace std;


const char* FILE_IN  = "books.txt";

// file line structure ...
// P.G. Wodehouse, "Heavy Weather" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
struct Book
{
    string author;
    string title;
    string pages;
    string available;

    friend ostream& operator << ( ostream& os, const Book& b )
    {
        return os << b.author << ", " << b.title << ", "
                  << b.pages << ", " << b.available;
    }
} ;

bool takeInFileLine( istream& fin, Book& b )
{
    string line;
    if( getline( fin, line ) )
    {
        istringstream iss(line); // construct istringstream obj 'iss'
        getline( iss, b.author, ',' );

        string skip;
        getline( iss, skip, '"' );
        getline( iss, b.title, '"' …
ddanbe commented: Nice. +15
David W 131 Practically a Posting Shark

This little example of simple file input from a well ordered (valid) file (of all valid data) ...

// getFileWeatherData //

/*
    My project for my C++ class requires that I take a bunch of weather data.
    It's a ton of lines so I won't include all of the text file,
    but here's a sample of it:

    0 943
    0 5
    0 107
    2 401
    0 299

    The first column is snowfall and the second is total precipitation.
    I have to find things like mean and median with the data,
    but that's not an issue as I can do math fine.
    I just don't know how to input all of that data into an array.
    I was sick and missed class when they went over this so I'm compeltely lost.
    Basically what I need is help with:
    1. creating an array that can intake a ton of lines
    2. taking the lines from the text file into an array
*/

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

using namespace std;

const char* FILE_IN  = "precipitation.txt";

struct Precipitation
{
    int snow;
    int rain;
};




int main()
{
    ifstream fin( FILE_IN );

    if( fin )
    {
        vector< Precipitation > myData;
        Precipitation tmp;

        while( fin >> tmp.snow >> tmp.rain ) // will read till end of file
        {
            myData.push_back( tmp );
        }
        fin.close();

        // show contents of vector ... //
        for( size_t i = 0; i < myData.size(); ++ i )
            cout << myData[i].snow << ", " << myData[i].rain << endl;

    }
    else …
David W 131 Practically a Posting Shark

But for quick and easy ... beginning student-type numeric input type coding problems ...

I agree. That's why I didn't burn you more harshly. ;) There's a certain iterative process in learning, where the strict quality of code improves bit by bit as edge cases like this are learned. So I'm tolerant of poorer examples even though I still prefer to mention that they're poor and point to supplementary resources for improvement if the student is so inclined.

Yeh! I could not have said it better. Amen!

David W 131 Practically a Posting Shark

@deceptikon, thank you for keeping fresh this C++ (and C) problematic issue.

It is good for students to know the content of the above link.

However, students may also appreciate knowing that the author of C++,

Bjarne Stroustrup himself,

recommended cin.sync() to flush the cin stream,
as used in the above code.

And I have never had a problem on a modern compiler ...
when used for keyboard input, as in the example above.

(But yes ... it never worked on really old compilers like Turbo C++)

I have had the rare occasion where it did not work as expected.

These were always to do with file reads.

And there, when reading files, just using ...

ignore some_big_num_like_max_int_size

did the trick.

But yes, students be aware of this!!!

And as well stated above:

The best approach, in my opinion is either 1) don't depend on the stream being 'clean' in the first place or 2) ensure that it's clean by reading full lines and parsing them in memory where you have more control.

On production code, reading the whole line, where ever possible, and then parsing that line, and validating the parts ... is highly recommended.

But for quick and easy ...
beginning student-type numeric input type coding problems ...
cin was made for you ... as long as you understand how it works.