C++ please somebody help..

Re-write your Squares program so that it uses the following functions.
int getInput(void); //function prototype

This function prompts the user to enter an integer. After extracting data from cin, if cin.fail() is true, then print an error message and return -1. If a negative integer is entered, then print an error message and re-prompt the user; otherwise, return the integer.

If getInput() returns a -1, then the calling function should print the number of squares printed along with their average length using the printStats() function and terminate the program.

void printLine(char, char, int); //function prototype

This function prints a line for the square. The first char parameter is the end character. The second char parameter is the interior character. The third parameter is the line length.

Example usage.

int length = ...; //variable storing the square length

// print top line
printLine('+', '-', length);

// print interior line
printLine('|', ' ', length);

void printStats(int, int); //function prototype

This functions prints the number of squares printed and their average length. The first int parameter is the number of squares printed. The second int parameter is the total of the printed square lengths. This function prints a line having the following format.

X squares printed. Average length: Y.YY

This is my codes but I dont know why doesnt work..it is supposed to draw a square...
like

when enter 3
+-+
| |
+-+
when enter 5
+---+
| |
| |
| |
+---+

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#define printline
using namespace std;
int getInput(void){
int s;
do{
    int s;
    cout<<" Enter length between 0 and 64 (-1 to exit): "<<endl;
    cin>>s;
    cout<<" Length Entered: "<<s<<endl;
    
}
while( (s<-1)||(s>64));
    return s;
}
void pritline(char A,char B,int n){
for(int i=1;i<=n;i++)
if(i==1||i==n)cout<<A;
else
cout<<B;
}
void printStats(int N,int s){
cout<<N<<"squares are printed. Their average="<<(s/N)<<endl;
}
int main(){
    int sum=0, N=0;
    while(1)
    {
    int p=getInput();
    if(p==-1)break;
    sum+=p; N++;
    for(int i=1;i<=p;i++)
    if(i==1||i==p)
    printline('+','+','p');
    else 
    printline('+','-',p);
    }
    void printStats(int N,int s);
    
    system("pause");
    return 0;
    }
@Lebron

One problem was that you mistyped printline(...) as pritline(...). You also don't need #define printline at the top. It doesn't do anything. Here is your program, with corrections. I changed the length requested to 1 to 64, and let the zero be a way to quit the program, since entering a zero for length, wouldn't print anything, anyway. Now, you may want to add a way to request length AND height.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Print Boxes.cpp : main project file.

#include <iostream>

using namespace std;

int getInput();
void printline(char, char, int);
void printStats(int, int);

int main()
{
	int sum=0, N=0, p;
	while(1)
	{
		p=getInput();
		if(p==0)
			break;
		sum+=p; // Don't know what this is for 
		N++; // What is this for?
		for(int i=1;i<=p;i++)
		{
			if(i==1||i==p)
			{
				printline('+','+',p); // You had the p in single quotes. Needed an integer here
				cout << endl;
			}
			else
			{
				printline('+','-',p);
				cout << endl;
			}
		}
	}
	void printStats(int N,int s);

	system("pause");
	return 0;
}

int getInput()
{
	int s=1;
	do
	{
		cout<<" Enter length between 0 and 64 (0 to exit): "<<endl;
		cin>>s;
		if (s>0)
			cout<<" Length Entered: " << s << endl; // Print only IF s != 0
	}while( (s<0)||(s>64));
	return s;
}

void printline(char A,char B,int n)
{
	for(int i=1;i<=n;i++)
	{
		if(i==1||i==n)
			cout<<A;
		else
			cout<<B;
	}
}

void printStats(int N,int s)
{
	cout<<N<<"squares are printed. Their average="<<(s/N)<<endl;
}
I run the program but something wrong again. The program works but show the squares like
when I enter 4
it shows
+--+
+--+
+--+
it should be
+--+
| |
| |
+--+
I mean only corner should be '+' and the middle of the spuares should be empty
Also the printStats() function doesnt work, couldnt see the average..thank you so much whitenite, I really appriciated, It is really helpful, there are just some small errors in the code , but thank you again ;)))
@whitenite1

I forgot to add my old squares assignment men sorry,,i think,it is gonna be helpful
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;
 int main(void){

 int s,n;
 do{
 cout << "Enter length between 0 and 64 (-1 to exit):" ;
 cin >> s;
 cout << "Length entered :"<< s <<endl;
 if (s<-1 || s>64 ){
 cout << s <<" is invalid" <<endl;
 cout <<"Length must be between 0 and 64 inclusive, or enter -1 to exit\n";
 continue;
 
 }
 if(s==-1) break;
 if(s==0){
 cout <<"      " <<endl;
 }
 int p=1;
 while( p<=s){
 cout << ((p==1 || p==s)? '+':'|');
 for( n=2 ;n<s;n++)
 cout << ((p==1 || p==s)? '-':' ');
 if(s>1)
 cout << ((p==1 || p==s)? '+':'|');
 cout <<endl;
 p++;
 }
 
 }while(true);

 system("pause");
 return 0;
 }
Last edited on
@Lebron

Sorry. I didn't notice that the inside of your squares was supposed to be open. Corrected the program I gave you, so it does. Also, the average is now printed. The reason it wasn't before, is you had a void printStats(int N,int s), instead of printStats(N, sum);, and I never noticed. ***SLAP FOREHEAD***
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Print Boxes.cpp : main project file.

#include <iostream>

using namespace std;

int getInput()
{
	int s=1;
	do
	{
		cout<<" Enter length between 0 and 64 (0 to exit): "<<endl;
		cin>>s;
		if (s>0)
			cout<<" Length Entered: " << s << endl;
	}while( (s<0)||(s>64));
	return s;
}

void printline(char A,char B,int n)
{
	for(int i=1;i<=n;i++)
	{
		if(i==1||i==n)
			cout<<A;
		else
			cout<<B;
	}
}

void printStats(int N,int s)
{
	cout<<N<<" squares were printed. Their average size was " <<(s/N) <<endl;
}

int main()
{
	int sum=0, N=0, p;
	while(1)
	{
		p=getInput();
		if(p==0)
			break;
		sum+=p; 
		N++;
		for(int i=1;i<=p;i++)
		{
			if(i==1||i==p)
			{
				printline('+','-',p);
				cout << endl;
			}
			else
			{
				printline('|',' ',p);
				cout << endl;
			}
		}
	}
	
	printStats(N, sum);

	system("pause");
	return 0;
}
Last edited on
I got it , thanks again ;))
@whitenite1

I tried to write some program following the directions but something.. I couldn write some part..and doesnt work..


Write a program that allows the user to play guessing games.

A guessing game is where the computer generates a random number and the user tries to guess it. The program loops until the user guesses the random number, or enters a sentinel value to give up. After five wrong guesses, the user is given help (higher or lower messages).

After a game has been completed, the program asks the user if they want to play again. The user is allowed to play at most 256 games.

Prior to terminating program, print the following.

number of games played
number of games won
winning percentage

Required Manifest Constants

Your program must define the following manifest constants prior to the definition of the main() function (i.e. make these global):

const int MIN_NUMBER = 1;
const int MAX_NUMBER = 100;
const int EXIT_VALUE = -1;
const int MAX_GAMES = 256;

Generating a Random Number

Include the time.h header file. To generate a random number that ranges between MIN_NUMBER and MAX_NUMBER (inclusive), use code similar to the following.

srand(time(NULL));
randomNumber = MIN_NUMBER + rand() % (MAX_NUMBER - MIN_NUMBER + 1);

The time() function returns the current date and time in seconds since 01-Jan-1970 00:00:00 GMT. Passing this return value to srand() "seeds" the random number generator so that a different set of random numbers are generated every time the program is executed. The rand() function returns a random number between 0 and RAND_MAX (a manifest constant defined in stdlib.h).

Help: time() | srand() | rand()
Example Game

Assume the computer generated random number is 34 for game #1, 73 for game #2, and 99 for game #3. For example purposes, user inputs are enclosed in brackets <>.

*** You are playing the CSC100 Guessing Game ***

Enter a number between 1 and 100 (-1 to give up): <3>
nope...
Enter a number between 1 and 100 (-1 to give up): <1001>
1001 is too big...
Enter a number between 1 and 100 (-1 to give up): <0>
0 is too small...
Enter a number between 1 and 100 (-1 to give up): <33>
nope...
Enter a number between 1 and 100 (-1 to give up): <50>
nope...
Enter a number between 1 and 100 (-1 to give up): <21>
nope...
Enter a number between 1 and 100 (-1 to give up): <41>
nope...
Enter a number between 1 and 100 (-1 to give up): <27>
nope...higher
Enter a number between 1 and 100 (-1 to give up): <57>
nope...lower
Enter a number between 1 and 100 (-1 to give up): <34>
*** GOT IT *** it took you 8 guesses

Do you want to play again? (y/n): <y>

Enter a number between 1 and 100 (-1 to give up): <99>
nope...
Enter a number between 1 and 100 (-1 to give up): <-1>
*** QUITTER ***

Do you want to play again? (y/n): <y>

Enter a number between 1 and 100 (-1 to give up): <21>
nope...
Enter a number between 1 and 100 (-1 to give up): <99>
*** GOT IT *** it took you 2 guesses

Do you want to play again? (y/n): <n>

Thanks for playing the CSC100 guessing game.

You played 3 games and won 2 of them.
Your winning percentage is 66.7%.


and here is my codes..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;  
  
    int r_number(int interval) {
    srand(time());
    int randomNumber = MIN_NUMBER + rand() % interval;
    
    return randomNumber;
}
    again()
{ 
    const int MAX_GAMES = 256;
    int decision;
    cout<<"Do you want to play again? (y/n): ";
    cin>>decision;
    MAX_GAMES--;
        if(MAX_GAMES==0){
        return EXIT_SUCCESS;
        }
        
        return decision;
    }

int main(int,char**){
    int gnumber;
    int dnumber;
    const int MIN_NUMBER = 1;
    const int MAX_NUMBER = 100;
    const int EXIT_VALUE = -1;
    const int MAX_GAMES = 256;
    int counter = 5;
    char decision2;
    system("color 2b");    
    cout <<"*** You are playing the CSC100 Guessing Game ***"<<endl<<endl;
    
    dnumber = r_number(100);
    
    ask:
    do{
    cout<<"Enter a number between 1 and 100 (-1 to give up): ";
    cin>>gnumber;
    
    if(counter!=0){
            
                    if((gnumber>100) || (gnumber<1))
                    {       cout<<gnumber<<" is too big"<<endl;
                            goto ask;    
                    }
                    if(gnumber==-1){
                           cout<<"*** QUITTER ***"<<endl;
                           cout<<"The number was "<<dnumber<<endl;            
                   	       decision2= again();
                           }
		                     
                    if(gnumber==dnumber)
                    {
                    cout<<"**GOT IT** it took you "<<5-counter<<" guesses"endl;
                           counter=5;
                           decision2 = again();
                           dnumber=r_number(100);
                    }
                    else if(gnumber < dnumber)
                    {
                          cout<<"nope.."<<endl;
                          counter--;
                          goto ask;
                    }
                    else if(gnumber>dnumber)
                    {
                          cout<<"nope..."<<endl;
                          counter--;
                          goto ask;
                 }    
                 }
         else if(counter<=0)
         {              if(gnumber < dnumber){
                                      cout<<"nope....higher.."<<endl;                
                                                 }
                        else if(gnumber > dnumber){
                                      cout<<"nope....lower.."<<endl;
                                                      } 
                        else if(gnumber==dnumber) {
                   cout<<"**GOT IT** it took you "<<5-counter<<" guesses"<<endl;
                           counter=5;
                           dnumber=r_number(100);
                           decision2 = again(); }                        
         }
        }while(decision2 == 'Y' || 'y');
        
        cout<<"Thanks for playing the CSC100 guessing game."<<endl;
        

    system("PAUSE");
    return EXIT_SUCCESS;
    }
Here's a small program, showing ways of using srand(), rand() and seeding srand().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// srand.cpp : Defines the entry point for the console application.
//

#include <ctime>
#include <string>
#include <iostream>

using namespace std;

int main(void)
{
   int i;
   string Congrats[5] = {"Great","Fantastic","Superb","Wow","Nice going!!"};
   time_t t;
   srand((unsigned) time(&t));

   printf("\t\t     One hundred random numbers from 0 to 999\n\n");
   for(i=0; i<20; i++)
       printf("\t%i\t\t%i\t\t%i\t\t%i\t\t%i\n", rand()%1000, rand()%1000, rand()%1000, rand()%1000, rand()%1000);

for (i=0;i<5;i++)
cout << Congrats[rand()%5] << " : ";
printf("\n\t\t\t");
return 0;
}
@whitenite1 can you help to figure out that?
The program doesnt ask user to play again the game..and I am just wondering that how can I add number of game and percentage of won or lost..Like "You played 4 game and you win 2 of them percentage %..."
Also how do I allow to user to play MAX 256 game?

I got it @whitenite1,, thank you.. here is new codesthat I have now..I just need that small part..
After a game has been completed, the program asks the user if they want to play again. The user is allowed to play at most 256 games.

Here is my codes and I dont know how could I fix that part..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*    Programmer:   XXXXxxxx....                                             *                        
*    Assignment:   GuessingGame0                                               *
*    Description:  A program that allows the user to play guessing games       *     
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;  
  
    int r_number(int interval ) {
    const int MIN_NUMBER = 1;
    const int MAX_NUMBER = 100;    
    srand(time(NULL));
    int randomNumber = MIN_NUMBER + rand() % interval;
    
    return randomNumber;
}
    char again()
{
    int MAX_GAMES = 256; 
    char decision;
    
        if(MAX_GAMES>=0)  { 
    cout<<"Do you want to play again? (y/n): "<<endl;
    cin>>decision;
    MAX_GAMES--;
    }
               
        return decision;
    }

int main(int,char**){
    int gnumber;
    int dnumber;
    const int MIN_NUMBER = 1;
    const int MAX_NUMBER = 100;
    const int EXIT_VALUE = -1;
    const int MAX_GAMES = 256;
    int counter = 5;
    char decision2;
    double lost=0;
    double game=0;
    system("color 2b");    
    cout <<"*** You are playing the CSC100 Guessing Game ***"<<endl<<endl;
    
    dnumber = r_number(100);
    
    ask:
    do{
    cout<<"Enter a number between 1 and 100 (-1 to give up): ";
    cin>>gnumber;
    
    if(counter>0){
            
                    if(gnumber==-1){
                           cout<<"*** QUITTER ***"<<endl;
                           cout<<"The number was "<<dnumber<<endl;
                           game++;
                           lost++;            
                   	       dnumber=r_number(100);
                           decision2= again();
                           }
                    else if(gnumber>100)
                    {       cout<<gnumber<<" is too big"<<endl;
                            goto ask;    
                    }
                    else if(gnumber<1){
                            cout<<gnumber<<" is too small"<<endl;
                            goto ask;
                    }
                                     
		                   
                    else if(gnumber==dnumber)
                    {
                    cout<<"**GOT IT** it took you "<<6-(counter)<<" guesses";
                    cout<<endl;
                           counter=5;
                           game++;
                           decision2 = again();
                           dnumber=r_number(100);
                    }
                    else if(gnumber < dnumber)
                    {
                          cout<<"nope.."<<endl;
                          counter--;
                          goto ask;
                    }
                    else if(gnumber>dnumber)
                    {
                          cout<<"nope..."<<endl;
                          counter--;
                          goto ask;
                 }    
                 }
         else if(counter<=0)
         {              if(gnumber < dnumber){
                                      cout<<"nope....higher.."<<endl;
                                      counter--;
                                      goto ask;                
                                                 }
                        else if(gnumber > dnumber){
                                      cout<<"nope....lower.."<<endl;
                                      counter--;
                                      goto ask;
                                                      } 
                        else if(gnumber==dnumber) {
                   cout<<"**GOT IT** it took you "<<6-counter<<" guesses"<<endl;
                           counter=5;
                           game++;
                           dnumber=r_number(100);
                           decision2 = again(); }                        
         }
        }while((decision2 == 'Y') || (decision2=='y'));
        
      cout<<"Thanks for playing the CSC100 guessing game."<<endl;
      cout<<"You played "<<game<<" gamed and won "<<game-lost<<" of them"<<endl;
      cout<<"Your winning percentage is "<<((game-lost)/game)*100<<"%"<<endl;
              

    system("PAUSE");
    return EXIT_SUCCESS;
    }


Ialready have that part
1
2
3
4
5
6
7
8
9
10
11
12
13
char again()
{
    int MAX_GAMES = 256; 
    char decision;
    
        if(MAX_GAMES>=0)  { 
    cout<<"Do you want to play again? (y/n): "<<endl;
    cin>>decision;
    MAX_GAMES--;
    }
               
        return decision;
    }

but it doesnt work..it evaluates 255 every time.

@Lebron

Using 'goto' in a program, is considered really bad form. It makes what programmers refer to as, 'spaghetti code'. Hard to follow and prone to errors. Anyway, I removed all of those, and made it into a do/while loop. One mistake you made, is forgetting that variables are forgotten, when you leave a function, so MAX_GAMES never decreases below 255, since it is reset to 256 each time into the function. I passed games played and MAX_GAMES, into the function, checked if games subtracted from MAX_GAMES is over zero, then you can continue. If not, then decision is assigned a 'N', and returned, causing the game to end. Hope this all helps. Here's the new, corrected code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// Guessing Game.cpp : main project file.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*    Programmer:   XXXXxxxx....                                             *                        
*    Assignment:   GuessingGame0                                               *
*    Description:  A program that allows the user to play guessing games       *     
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;  

int r_number(int interval )
{
	const int MIN_NUMBER = 1;
	const int MAX_NUMBER = 100;    
	srand(time(NULL));
	int randomNumber = MIN_NUMBER + rand() % interval;

	return randomNumber;
}
char again(int games_played, int MAX_GAMES )
{
	char decision = ' ';

	if(games_played != MAX_GAMES) 
	{ 
		cout << "You have played " << games_played << " out of " << MAX_GAMES << endl;
		cout << "You have only " << MAX_GAMES-games_played << " more times you can play..." << endl; 
		do
		{
		cout<<"Do you want to play again? (y/n): "<<endl;
		cin>>decision;
		decision = toupper(decision);
		if(decision != 'Y' && decision != 'N')
		{
			cout << "Enter a 'y' or 'n', please.." << endl;
		}

		} while (decision != 'Y' && decision != 'N');
	}
	else
	{
		cout << "Sorry, you have reached the top limits of these games. We will stop now.." << endl;
		decision = 'N';
	}

	return decision;
}


int main()
{
	int gnumber;
	int dnumber;
	const int MIN_NUMBER = 1;
	const int MAX_NUMBER = 100;
	const int EXIT_VALUE = -1;
	const int MAX_GAMES = 256;
	int counter = 5;
	char decision2 = 'Y';
	int lost = 0;
	int game = 0;
	bool ok = true;
	system("color 2b");    
	cout <<"*** You are playing the CSC100 Guessing Game ***"<<endl<<endl;

	dnumber = r_number(100);

	do
	{
		ok = true;
		cout<<"Enter a number between 1 and 100 (-1 to give up): ";
		cin>>gnumber;

		if(gnumber == -1)
		{
			cout<<"*** QUITTER ***"<<endl;
			cout<<"The number was "<<dnumber<<endl;
			game++;
			lost++;            
			decision2 = again( game, MAX_GAMES);
			if ( decision2 == 'Y')
			{
				ok = false;
			}
			else
				break;
		}

		if(counter>0 && ok )
		{

			if(gnumber>100)
			{    
				cout<<gnumber<<" is too big"<<endl;
			}
			else if(gnumber<1)
			{
				cout<<gnumber<<" is too small"<<endl;
			}

			else if(gnumber==dnumber)
			{
				cout<<"**GOT IT** it took you "<<6-(counter)<<" guesses";
				cout<<endl;
				counter=5;
				game++;
				decision2 = again(game,  MAX_GAMES);
				dnumber=r_number(100);
			}
			else if(gnumber < dnumber)
			{
				cout<<"nope.."<<endl;
				counter--;
			}
			else if(gnumber>dnumber)
			{
				cout<<"nope..."<<endl;
				counter--;
			}    
		}
		else if(counter<=0 && ok)
		{  
			if(gnumber < dnumber)
			{
				cout<<"nope....higher.."<<endl;
				counter--;
			}

			else if(gnumber > dnumber)
			{
				cout<<"nope....lower.."<<endl;
				counter--;
			} 
			else if(gnumber==dnumber) 
			{
				cout<<"**GOT IT** it took you "<<6-counter<<" guesses"<<endl;
				counter=5;
				game++;
				dnumber=r_number(100);
				decision2 = again( game, MAX_GAMES);
			} 
		}
	} while( decision2 == 'Y' );

	cout<<"Thanks for playing the CSC100 guessing game."<<endl;
	cout<<"You played "<<game<<" games and won "<<game-lost<<" of them"<<endl;
	cout<<"Your winning percentage is "<< 100-(((double)lost/game)*100)<<"%"<<endl;


	system("PAUSE"); 
	return EXIT_SUCCESS;
}


Last edited on
@whitenite 1

Here are my Palindromic number asssingment codes.. teacher said rewrite these codes with using arrays.. can you help to figure it out?

here is asssingment.
Write an interactive program that gets positive integer numbers as inputs and checks to see if those numbers are palindromic.

Process inputs until the user enters 0.

If a non-integer is entered, print an error message and continue the loop (i.e. get the next input).

If a negative number is entered, print an error message and continue the loop (i.e. get the next input).

Important note: String objects cannot be used to determine if a number is a palindrome. In other words, this program must be implemented using an array of characters.

Enter a positive integer (0 to exit): <1228>
1228 is not a palindrome

Enter a positive integer (0 to exit): <15851>
15851 is a palindrome

Enter a positive integer (0 to exit): <hello>
*** error: inputs must be an integer

Enter a positive integer (0 to exit): <919>
919 is a palindrome

Enter a positive integer (0 to exit): <-99>
*** error: inputs must be greater than zero

Enter a positive integer (0 to exit): <4115>
4115 is not a palindrome

Enter a positive integer (0 to exit): <0>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<string>
using namespace std; // the namespace for cout<< & such functions
int main()
{
char strn[80];
cout<<"Enter the string: ";
cin.getline(strn,80);
int len=strlen(strn);

bool flag=true; // create a Boolean value, "flag" to be used in our loop

for(int c=0;c!=len/2;c++) // do a loop from 0 to half the length of the string
{
if(flag) // if it is a palindrome so far
{
if(strn[c]!=strn[len-c-1]) // check the characters match
{
flag=false; // if they don't set the indicator to false
}

}
else
{
break; // if it is not a palindrome, exit the for loop
}
}

// if flag is true cout "Palindrome" otherwise output "Not Palindrome"

if(flag)
{
cout<<"Palindrome";
}
else
{
cout<<"Not Palindrome";
}

cin.get();
return 0;
}
Let me see your ideas first, Lebron. I have the program fully running with a char array, but I would prefer to help with your program, rather than give you a completed program, that wouldn't really help you learn anything.
To help though, with an idea.. Create a char array, and fill it with the strn array. Use for(int x=len;x>0;x--) and check if strn[x-1] is equal to the char array[len-x]; If they all are, it's palindromic, otherwise, no
Last edited on
Ok whitenite 1 you are right.. I tried something..I dont understand that part

Create a char array, and fill it with the strn array.



I wrote that but I doesnt work..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*    Programmer: XXXxxx,,,...                                             *                        
*    Assignment:   Palindromic Numbers                                         *
*    Description:  Checking numbers to see if those numbers are palindromic    *     
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include<iostream>
using namespace std;

int main(int, char**){

int EXIT_VALUE = 0;
char strn[80];




        cout<<"Enter a positive integer (0 to exit): ";
        cin>>strn;
int len=strlen(strn);
        
bool f=true;
    for(int c=0;c!=len/2;c++) 
{
         if(f) 
        {
            if(strn[c]!=strn[len-c-1]) 
                 {
                  f=false; 
                          }

          }
         else
         {
         break; 
         }
         }
        
        
        
        while(strn!=0){
        
            if (cin.fail()) {
                    cout << "*** error: inputs must be an integer" << endl;
                    continue;  }
            else if(strn<0){
                    cout<<"*** error: inputs must be greater than zero"<<endl;
                    continue;  }
            else if(f){
                    cout<<strn<<" is a Palindrome"<<endl; 
                               }
            else
             cout<<strn<<" is not a Palindrome"<<endl; 
}
}
        


Last edited on
@Lebron

At the start of your program, you have char strn[80]; You just need another. Let's call it char arr[80];
After the input of the number, you get its length with len=strlen(strn); You then use a for loop to put the data from strn into arr. With something like..
1
2
for(int x=0;x<len;x++)
    arr[x]=(strn[x]);
Then you can use a for loop to check if they're the same with
1
2
3
4
5
6
7
8
9
10
11
12
13
for(int x=0;x<len;x++)
{
if(arr[x] == strn[(len-1)-x]) // need to subtract 1 from len since arrays start at 0
                                     // so if len equals 5, you read 0 to 4
{
	flag = true;
}
else
{
	flag = false;
       break; // end checking. Otherwise, if the next check is equal, you would get flag to equal true 
                  // but number was actually, false. 
}
Last edited on
Like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*    Programmer: XXXxxx,,,...                                             *                        
*    Assignment:   Palindromic Numbers                                         *
*    Description:  Checking numbers to see if those numbers are palindromic    *     
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include<iostream>
using namespace std;

int main(int, char**){

int EXIT_VALUE = 0;
char strn[80];
char arr[80];




        cout<<"Enter a positive integer (0 to exit): ";
        cin>>strn;
int len=strlen(strn);
        
bool flag=true;
    for(int x=0;x<len;x++)
{
if(arr[x] == strn[(len-1)-x]) 
                                    
{
	flag = true;
}
else
{
	flag = false;
       break; 
                  
                  }
        
        
        
        while(strn!=0){
        
            if (cin.fail()) {
                    cout << "*** error: inputs must be an integer" << endl;
                    continue;  }
            else if(strn<0){
                    cout<<"*** error: inputs must be greater than zero"<<endl;
                    continue;  }
            else if(flag){
                    cout<<strn<<" is a Palindrome"<<endl; 
                               }
            else
             cout<<strn<<" is not a Palindrome"<<endl; 
}
}
system("pause");
return 0;
}
Almost.. So far, you have not made arr[] equal strn[], with the for loop I mentioned first. You're just checking the arrays against each other, so it actually should say that it is not a palindrome. Also, since you are using a char, the program should work also on single words, but not sentences.
Topic archived. No new replies allowed.