Okay, I'm new at programming and decided to jump into this book called Accelerated C++. I'm only on the second chapter and I tried following the exercise, which is to create a program that asks for your name and then output it with a frame around it and padding.
When I execute it, it doesn't seem to be moving onto the next row. I'm guessing it's to do with my while() loop but I'm too dumb to figure out what it is exactly
// ask for a person's name, and greet the person
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;
int main()
{
// fetch name
cout << "Please enter your first name: ";
string name;
cin >> name;
// message
const string greeting = "Hello, " + name + "!";
// padding
const int pad = 1;
//desired rows/columns
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
// seperate output from input
cout << std::endl;
// invariants
int r = 0;
string::size_type c = 0;
while (r != rows) {
while(c != cols) {
if (r == 0 || r == rows -1 || c == 0 || c == cols -1) { // if in bordering column or row
cout << "*"; //output *
} else {
if (r == pad + 1 && c == pad + 1) { //if on row for greeting
cout << greeting; // write greeting
c += greeting.size(); // adjust invariant
} else {
cout << " ";
}
}
++c;
}
++r;
cout << std::endl;
}
return 0;
}
Consider moving the column counter c to nearer where you use it, then as tuckermi says it will start at 0 for each row.
while (r != rows) {
string::size_type c = 0;
while(c != cols) {
At the bottom of your outer loop you need to reset the variable c to zero, otherwise it keeps its old value and won't re-enter the inner loop.
A good way to accomplish this is to move the definition/initialization of the variable into the beginning of the outer loop. That way c will be reinitialized before you start the inner loop each time.
You're almost there.
You need to clear c each row, and you need to take one off the greetings.size() to make it format properly (accounting for the fact you will be incrementing it later in the loop)
// ask for a person's name, and greet the person
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;
int main()
{
// fetch name
cout << "Please enter your first name: ";
string name;
cin >> name;
// message
const string greeting = "Hello, " + name + "!";
// padding
const int pad = 1;
//desired rows/columns
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
// seperate output from input
cout << std::endl;
// invariants
int r = 0;
while (r != rows) {
string::size_type c = 0;
while(c != cols) {
if (r == 0 || r == rows -1 || c == 0 || c == cols -1) { // if in bordering column or row
cout << "*"; //output *
} else {
if (r == pad + 1 && c == pad + 1) { //if on row for greeting
cout << greeting; // write greeting
c += (greeting.size()-1); // adjust invariant
} else {
cout << " ";
}
}
++c;
}
++r;
cout << std::endl;
}
return 0;
}
http://ideone.com/mb9InW
Apart from reseting the variable c in the outer loop, you are not getting padding between the asterick and the message. So for that include the below code just after where you are printing the message.
for(int i = 0;i<pad;i++)
{
cout<<" ";
}
Related
i want to asking this problem.
this output is the expected output
*
*#
*#%
*#%*
*#%*#
*#%*#%
and this is my solution
#include <iostream>
using namespace std;
int main(){
int a,b,n;
cout << "Input the row";
cin >> n;
for (a = 1; a <= n; a++){
for(b = 1; b <= a; b++){
if (b == 1 || b == 1 + 3){
cout << "*";
}
if (b ==2 || b == 2 + 3){
cout << "#";
}
if (b ==3 || b == 3 + 3){
cout << "%";
}
}
cout << endl;
}
}
this solution is only work if the n = 6. what should i do if i want this work in every row when user input the row to the n
thank you in advance.
Here, I tried using the modulo "%" on your if's
#include <iostream>
using namespace std;
int main(){
int a,b,n;
cout << "Input the row";
cin >> n;
for (a = 1; a <= n; a++){
for(b = 1; b <= a; b++){
// After every first digits will cout #
if (b % 3 == 2){
cout << "#";
}
// The first after the third digit will cout *
if (b % 3 == 1){
cout << "*";
}
// The third digit after the second digit will cout %
if (b % 3 == 0){
cout << "%";
}
}
cout << endl;
}
}
To make your solution work for any value of n, you can use the modulo operator % to check whether a given value of b is the first, second, or third element of each row.
Here is one way you could modify your code to do this:
#include <iostream>
using namespace std;
int main() {
int a, b, n;
cout << "Input the row: ";
cin >> n;
for (a = 1; a <= n; a++) {
for (b = 1; b <= a; b++) {
// Use the modulo operator to check whether b is the first, second, or third element of each row
if (b % 3 == 1) {
cout << "*";
} else {
if (b % 3 == 2) {
cout << "#";
} else {
cout << "%";
}
}
}
cout << endl;
}
return 0;
}
With this change, the code will output the correct pattern for any value of n.
Just adding a nice optimisation (note: C++ loops naturally go up from 0 to not including n, i.e. for(int i = 0; i < n; ++i) – this is especially relevant if you are indexing arrays which have a first index of 0 and last of n - 1, while n already is invalid!).
While you do use b % 3 to decide which character and you indeed can use this by chaining if(){} else if(){} else{} (where a switch() { case: case: default: } actually would have been preferrable) you can have a much more compact version as follows (and even more efficient as it avoids conditional branching):
for(int b = 0; b < a; ++b)
{
std::cout << "*#%"[b % 3];
}
The C-string literal "*#%" actually represents an array of char with length four (including the terminating null character) – and you can index it just like any other array you have explicitly defined (like int n[SOME_LIMIT]; n[7] = 1210;)...
I am stuck in one of the problem related string in c++. My logic has worked well for some test cases, but not for all test cases. Please suggest me the actual logic of the following question::
I am given a string s of n character, comprising only of A's and B's . I can choose any index i and change s(i) to either A or B. Find the minimum no. Of changes that you must make to string S such that the resultant string is of format : AAAAA.....BBBBB. In other words, your task is to determine minimum no. of changes such that string s has x no. of A's in the beginning, followed by the remaining (n-x) no. of B's.
my code::
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, i, flag = 0;
cin >> n;
string str;
cin >> str;
int cnt = 0, cnt1 = 0;
for (i = 0; i < str.length(); i++) {
if (str[i] == 'A') {
cnt++;
} else {
cnt1++;
}
}
int pp = 0;
//cout << cnt << " " <<cnt1;
for (i = 0; i < cnt; i++) {
if (str[i] == 'B') {
pp++;
}
}
for (i = cnt; i < n; i++) {
if (str[i] == 'A' && str[i - 1] != 'A') {
pp++;
}
}
cout << pp << endl;
}
}
For example: AAB = 0 changes, BABA= 2 changes , AABAA= 1 changes
How to approach this question. Do respond!!!
I wrote the following code to compute the number of changes needing to order a string containing unorderd A e B according to the order that shall be "A[...A]B[...B]". (function countChanges).
The algorithm (countChanges) used to count modifications acts in three steps:
Step 1: counts how much 'A' chars are in the string (cnt).
Step 2: scans how much 'B' chars are in the first cnt chars of the string increasing a counter (sum) for each encounterd 'B'.
Step 3: scans how much 'A' chars are in the remaining chars of the string after the 2nd step increasing a counter (sum) for each encountered 'A'.
At the end of the function sum is the expected result.
The code also computes and executes the minimum number of swaps needing to obtain the string ordered according to the requirement.
The code contains two evaluation functions (the code under the main):
cntChanges. It computes the needing number of changes (The code gives the result as foreseen changes).
executeSwaps. It performs swaps on the string, counts them and may or may not show the steps performed.
Code result:
Do you have a code composed of A and B? [y]es/[n]o/[I] do it/[q]uit y
Insert your code? BABA
Do you want to print swap steps? [y]es/[n]o y
Input: BABA
Step 1 BABA swap(3,0) ==> AABB
Result AABB performed with 1 swap - foreseen changes 2
--
Do you have a code composed of A and B? [y]es/[n]o/[I] do it/[q]uit n
How much codes do you want to generate? 5
What's your preferred length for all generated codes? 10
Do you want to print swap steps? [y]es/[n]o y
Input: AAAAABAABB
Step 1 AAAAABAABB swap(7,5) ==> AAAAAAABBB
Result AAAAAAABBB performed with 1 swap - foreseen changes 2
--
Input: ABBABAAABA
Step 1 ABBABAAABA swap(9,1) ==> AABABAAABB
Step 2 AABABAAABB swap(7,2) ==> AAAABAABBB
Step 3 AAAABAABBB swap(6,4) ==> AAAAAABBBB
Result AAAAAABBBB performed with 3 swaps - foreseen changes 6
--
Input: AAABBAABBB
Step 1 AAABBAABBB swap(6,3) ==> AAAABABBBB
Step 2 AAAABABBBB swap(5,4) ==> AAAAABBBBB
Result AAAAABBBBB performed with 2 swaps - foreseen changes 4
--
Input: BABAABBABB
Step 1 BABAABBABB swap(7,0) ==> AABAABBBBB
Step 2 AABAABBBBB swap(4,2) ==> AAAABBBBBB
Result AAAABBBBBB performed with 2 swaps - foreseen changes 4
--
Input: AAABAABAAA
Step 1 AAABAABAAA swap(9,3) ==> AAAAAABAAB
Step 2 AAAAAABAAB swap(8,6) ==> AAAAAAAABB
Result AAAAAAAABB performed with 2 swaps - foreseen changes 4
--
The code:
#include <iostream>
#include <ctime>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
unsigned int executeSwaps(string &x, bool printSteps);
unsigned int cntChanges(const string& x);
unsigned int cntChangesJarod42(string const &x);
unsigned int cntChangesDamien(string const &x);
void questionToStart(int &c, size_t &cl, char &ync, char &ynps, string &x);
string generateCode(size_t n);
const char char1='A';
const char char2='B';
int main(void)
{
srand(static_cast<unsigned int>(time(nullptr)));
int c;
size_t cl;
char ync='n';
char ynps='n';
string x;
x.clear();
do {
questionToStart(c,cl,ync,ynps,x);
if (ync == 'q')
break;
for(int i=0;i<c;i++) {
unsigned int cnt=0;
if (ync=='n') {
x=generateCode(cl)
}
/* unsigned int fc2 = cntChangesJarod42(x);
unsigned int fc1 = cntChangesDamien(x);*/
unsigned int fc3 = cntChanges(x);
cout << "Input: " << x << endl;
cnt=executeSwaps(x, (ynps=='y')?1:0);
cout << "Result " << x << " performed with "
<< ((cnt>0)?to_string(cnt):"no")
<< " swap"
<< ((cnt>1)?"s ":" ") << " - foreseen changes " << fc3 << endl << "--" << endl;
/* << "foreseen changes (#Damien) " << fc1
<< " - foreseen changes (#Jarod42) " << fc2
<< endl << endl;*/
}
} while(ync != 'q');
return 0;
}
unsigned int cntChanges(const string& x)
{
const char * s;
unsigned int cnt=0,sum=0,i;
if (x.empty())
return 0;
s=x.c_str();i=0;
// count char1
while(*(s+i))
if (*(s+i++) == char1)
cnt++;
/* verify how much elements, from start to cnt,
* are different than char1 (equal to char2).
*/
for(i=0;i<cnt;i++)
if (*(s+i)==char2)
sum++;
cnt=static_cast<unsigned int>(strlen(s));
/* verify how much of the remaining elements
* are different than char2 (equal to char1).
*/
for(;i<cnt;i++)
if (*(s+i)==char1)
sum++;
return sum;
}
// #Jarod42
unsigned int cntChangesJarod42(const string& s)
{
if (s.empty()) { return 0; }
std::vector<std::size_t> switch_count(s.size());
{ // Count 'B' before index
unsigned int sum = 0;
std::size_t i = 0;
for (auto c : s) {
switch_count[i++] += sum;
sum += c == 'B';
}
}
{ // Count 'A' after the index
unsigned int sum = 0;
std::size_t i = 0;
for (auto c : std::string(s.rbegin(), s.rend())) {
switch_count[s.size() - 1 - i++] += sum;
sum += c == 'A';
}
}
return static_cast<unsigned int>(*std::min_element(switch_count.begin(), switch_count.end()));
}
// #Damien Algorithm
unsigned int cntChangesDamien (string const &x)
{
size_t n = x.length();
int cntCh_1 = 0, cntCh_2 = 0;
// there's nothing to swap!! :p
if (n < 2)
return 0;
for (size_t i = 0; i < n; ++i) {
if (x.at(i) == char1) {
cntCh_1++;
} else {
// x.at(i) is equal to char1
cntCh_1 = min (cntCh_2, cntCh_1);
// Now the foreseen swap are equal to cntCh1
cntCh_2++;
}
}
return static_cast<unsigned int>(std::min (cntCh_2, cntCh_1));
}
unsigned int executeSwaps(string &x, bool printSteps)
{
unsigned int cnt =0;
size_t apos=0;
size_t bpos=0;
// cout << "Start: " << x << " " << apos << " " << bpos << endl;
do {
apos=x.find_last_of(char1);
if (apos == string::npos)
break;
bpos=x.find_first_of(char2);
if (bpos == string::npos)
break;
if (apos>bpos) {
++cnt;
if (printSteps) {
cout << "Step " << cnt << " " << x << " swap(" << apos << "," << bpos <<") ==> ";
}
x.at(bpos)=char1;
x.at(apos)=char2;
if (printSteps)
cout << x << endl;
}
} while(apos>bpos);
return cnt;
}
string generateCode(size_t n)
{
string x;
x.clear();
size_t i,cb=0;
char ch;
if (n==0) {
n=rand()%10;
}
for (i=0;i<n-1;i++) {
ch = ( char1 + (rand()&1) );
if (ch == char2 )
cb++;
x +=ch;
}
if (cb==n-1) {
ch=char1;
} else if (cb==0) {
ch=char2;
} else {
ch=( char1 + (rand()&1) );
}
x += ch;
return x;
}
void questionToStart(int &c, size_t &cl, char &ync, char &ynps, string &x)
{
int ex=1;
do {
ex=1;
cout << "Do you have a code composed of "<<char1 << " and " << char2 <<"? [y]es/[n]o/[I] do it/[q]uit ";
cin >> ync;
switch(ync) {
case 'n':
cout << "How much codes do you want to generate? ";
cin >> c;
cout << "What's your preferred length for all generated codes? ";
cin >> cl;
break;
case 'I':
c=10; cl=(rand()&7)+9;
cout << c <<" attempts with " << cl << " characters long strings will be executed" << endl;
break;
case 'y':
c=1;
cout << "Insert your code? ";
cin >> x;
cl = x.length();
break;
case 'q':
break;
default:
ex=0;
}
} while(!ex);
if ( ync != 'q' ) {
if ( ync != 'I' ) {
cout << "Do you want to print swap steps? [y]es/[n]o ";
cin >> ynps;
} else {
ynps = 'y';
ync = 'n';
}
cout << endl;
}
}
As state by Tfry,
you might count the number of switch needed to have
XBBB
AXBB
AAXB
AAAX
which is the number of 'B' before the index + number of 'A' after the index.
Then take the minimum:
std::size_t count_switch_for_ab(const std::string& s)
{
if (s.empty()) { return 0; }
std::vector<std::size_t> switch_count(s.size());
{ // Count 'B' before index
int sum = 0;
std::size_t i = 0;
for (auto c : s) {
switch_count[i++] += sum;
sum += c == 'B';
}
}
{ // Count 'A' after the index
int sum = 0;
std::size_t i = 0;
for (auto c : std::string(s.rbegin(), s.rend())) {
switch_count[s.size() - 1 - i++] += sum;
sum += c == 'A';
}
}
return *std::min_element(switch_count.begin(), switch_count.end());
}
Demo.
The solution can be found in a simple loop, considering a 2-state process.
A state corresponds to the fact that for the given index, we decide to be in the A part or the B part. The transition from B state to A state is not allowed.
The corresponding number of changes up to index i can then be calculated iteratively.
For index i, let us call countA[i] the number of changes to get A only until index i, and let us call countB[i] the optimal number of changes up to i, assuming that somewhere before i, or at i time, we decided that the following part of the last string will containt B only.
It the current character s[i] is equal to A, then
countA[i] = countA[i-1]
countB[i] = countB[i-1] + 1
If the current character is B, then
countA[i] = countA[i-1] + 1
countB[i] = min (countB[i-1], countA[i-1])
if the last equation, countB[i] = countB[i-1] corresponds to the case that the transition to B state already occurs, and
countB[i] = countA[i-1] corresponds to the case that the transition occurs now.
In practice, we don't need an array to update countA and countB.
Here is the code:
#include <iostream>
#include <string>
int nb_changes (const std::string &s) {
int n = s.size();
if (n < 2) return 0;
int countA = 0, countB = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'A') {
countB++;
} else {
countB = std::min (countA, countB);
countA++;
}
}
return std::min (countA, countB);
}
int main() {
std::string s;
s = "AAB";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
s = "BABA";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
s = "AABAA";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
}
I've been following Accelerated C++ for a couple of weeks now but I have been stuck at exercise 2.4 for a while and finally I thought I found it out but after trying giving it different dimensions I found out that it doesn't really work and I don't really understand why
The code initially prints a framed message, in this particular exercises I was supposed to change how the code prints the blanks from one character at a time into writing all the planks at once
here is the code:
// [2-0, 2-4] Exercises
#include<iostream>
#include<string>
// saying what standard-library names we use
using std::cout; using std::endl;
using std::cin; using std::string;
int main()
{
// asking for the name
cout << "Please enter your first name: ";
// reading the name
string name;
cin >> name;
// building the message that we intend to write
const string greeting = "Hello, " + name + "!";
// 2.2 & 2.3 asking for inpadY
cout << "Please enter the number of padY (Vertical padding): ";
// 2.2 & 2.3 reading the inpadY
int inpadY;
cin >> inpadY;
// 2.2 & 2.3 asking for inpadX
cout << "Please enter the number of padX (Horizontal padding): ";
// 2.2 & 2.3 reading the inpadX
int inpadX;
cin >> inpadX;
// the number of planks surrounding the greeting
// 2.2 & 2.3 added inpadY as the number of planks;
const int padY = inpadY;
// 2.2 & 2.3 added inpadX
const int padX = inpadX;
// 2.4 pad size
const int pad = inpadX + inpadY;
// the number of rows and columns to write
const int rows = padY * 2 + 3;
const string::size_type cols = greeting.size() + padX * 2 + 2;
// 2.4 creating a padding string left and right and top and bottom
const string LeftRightPad(padY, ' ');
const string TopBottomPad(cols - 2, ' ');
// write a blank line to separate the output and the input
cout << endl;
// write rows rows of output
// invariant: we have written r rows so far
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
// invariant: we have written c characters so far in the current row
while (c != cols) {
// is it time to write the greeting?
if (r == padY + 1 && c == padX + 1)
{
cout << greeting;
c += greeting.size();
} else {
// are we on the border?
if (r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
{cout << "*";
++c;}
else
// 2.4 typing out the spaces at once
{cout << LeftRightPad;
c += LeftRightPad.size();}
}
}
cout << endl;
}
return 0;
}
Edited to have the input and output
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 2
Please enter the number of padX (Horizontal padding): 2
**********************
* *
* *
* Hello, Estrogen! *
* *
* *
**********************
Process returned 0 (0x0) execution time : 3.281 s
Press any key to continue.
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 2
Please enter the number of padX (Horizontal padding): 5
****************************
* *
* *
* *
* *
* *
****************************
Process returned 0 (0x0) execution time : 5.098 s
Press any key to continue.
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 3
Please enter the number of padX (Horizontal padding): 2
**********************
*
*
*
*
*
*
*
**********************
Process returned 0 (0x0) execution time : 4.333 s
Press any key to continue.
Update: I've rewritten the code and the output is an infinite loop of asterisks here is the new code
#include<iostream>
#include<string>
using std::string; using std::endl;
using std::cout; using std::cin;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
const string message = "Hello, " + name + "!";
cout << "Enter the length: ";
int length;
cin >> length;
cout << "Enter the height: ";
int height;
cin >> height;
const int rows = height * 2 + 3;
const string::size_type cols = message.size() + length * 2 + 2;
const string TopBottom(cols, '*');
const string Blank(cols - 2, ' ');
const string messageblank(cols - 3 - message.size(), ' ');
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if ( r == height + 1 && c == length + 1)
{
cout << messageblank << message << messageblank;
c += Blank.size();
} else
if (r == 0 && c == 0 || r == rows - 1 && c == cols -1)
{
cout << TopBottom;
c += TopBottom.size();
} else
if ( r != 0 && c == 0 || r != rows -1 && c == cols - 1)
{
cout << "*";
++c;
} else
cout << Blank;
c += Blank.size();
}
cout << endl;
}
return 0;
}
Thank you guys for help in advance
Unless the code is supposed to be written this way, I would propose another, row by row approach:
print_frame_row(cols);
for (int i = 0; i < padY; ++i)
print_v_padding(cols);
print_greeting(padX, greeting);
for (int i = 0; i < padY; ++i)
print_v_padding(cols);
print_frame_row(cols);
where
void print_frame_row(int cols)
{
std::cout << std::string(cols, '*') << '\n';
}
void print_v_padding(int cols)
{
const std::string h_padding(cols - 2, ' ');
std::cout << '*' << h_padding << "*\n";
}
void print_greeting(int padX, const std::string &msg)
{
const std::string h_padding(padX, ' ');
std::cout << '*' << h_padding << msg << h_padding << "*\n";
}
This way you have a simpler logic, and need not worry about counting columns or deciding when to write each character.
ok so it took me 3 days but I finally figured it out here is the working code
#include<iostream>
#include<string>
using std::string; using std::endl;
using std::cout; using std::cin;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Enter the length: ";
int length;
cin >> length;
cout << "Enter the height: ";
int height;
cin >> height;
const string message = "Hello, " + name + "!";
const int rows = height * 2 + 3;
const string::size_type cols = message.size() + length * 2 + 2;
const string TopBottom(cols, '*');
const string Blank(cols - 2, ' ');
const string messageblank(length, ' ');
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if ( r == height + 1 && c == 0)
{
cout << "*" << messageblank << message << messageblank << "*";
c += TopBottom.size();
} else
if (r == 0 && c == 0 || r == rows - 1 && c == 0)
{
cout << TopBottom;
c += TopBottom.size();
} else
if ( c == 0 && r != 0 || c == 0 && r != rows - 1)
{
cout << "*" << Blank << "*";
c += TopBottom.size();
}
}
cout << endl;
}
return 0;
}
This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
I am trying to get my program to print letters instead of numbers. I used char c = static_cast<char>(N); to attempt to do this but it wont work, instead it prints character images that are not (a-z) How can I get the numbers to be printed as letters?
#include <cstdlib>
#include <iostream>
using namespace std;
// Function getUserInput obtains an integer input value from the user.
// This function performs no error checking of user input.
int getUserInput()
{
int N(0);
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
if (N < 1 || N > 51 || N % 2 == 0)
{
cout << "Error value is invalid!" << "\n";
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
system("cls");
}
cout << endl;
return N;
} // end getUserInput function
// Function printDiamond prints a diamond comprised of N rows of asterisks.
// This function assumes that N is a positive, odd integer.
void printHourglass(int N)
{
char c = static_cast<char>(N);
for (int row = (N / 2); row >= 1; row--)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print top ~half of the diamond ...
for (int row = 1; row <= (N / 2 + 1); row++)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print bottom ~half of the diamond ...
return;
} // end printDiamond function
int main()
{
int N = 1;
while (N == 1)
{
printHourglass(getUserInput());
cout << endl;
cout << "Would you like to print another hourglass? ( 1 = Yes, 0 = No ):";
cin >> N;
}
} // end main function
The letters are not numbered with A starting at 1 or anything like that. You're likely on an ASCII/UTF-8 system. So, in printHourglass, replace cout << N with
cout << static_cast<char>('A' + count - 1);
C functions, itoa
C++, using stringstream
boost::lexical_cast
Actually for your case, you can directly print it out. cout << N
I'm new to learning how to code and I was wondering if there's a way to see values during each iteration of a loop. Here's a code I'm trying to understand. I know some of it but as it gets deeper, I get confused.
#include <iostream>
#include <string>
using std::cin; using std::endl;
using std::cout; using std::string;
int main()
{
cout << "Please enter your first name: ";
string name = "Jae";
const string greeting = "Hello, " + name + "!";
const int pad = 1;
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if (r == pad + 1 && c == pad + 1) {
cout << greeting;
c += greeting.size();
} else {
if (r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
cout << "*";
else
cout << " ";
++c;
}
}
cout << endl;
}
}
You can debug your code. If you debug, you can see values during each iteration of a loop
if r is your iterator, write inside the loop this line:
cout << r;
Google is your friend.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide
Simply you can execute your program line-by-line by pressing F10 key. And hovering mouse over variables shows their current value.