nested looping C++ - c++

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;)...

Related

Continuous x no. of A and then after (n-x) no.s of B

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";
}

comparation of 2 binary numbers

I need to write program that will compare 2 binary numbers and return the result
I wrote this code using XOR, but idk how to improve my code, so for example 100101 and 101001 will return a < b. Can you help me fix this please?
string a,b;
la = a.length();
lb = b.length();
int x = 0;
if (la == lb)
{
for (int i = 0; i < la; i++)
{
if (a[i]^b[i] == 1)
{
if(a[i] > b[i])
x++;
}
else {x--;}
}
if (x > 0)
cout << a << " > " << b << endl;
if (x < 0)
cout << a << " < " << b << endl;
if (x == 0)
cout << a << " = " << b << endl;
}
Guess this would be better
Here no need to iterate th whole string unless they are equal.
Just find the first '1' and the one which has 1 before will be bigger.
As simple as that
int main()
{
string a,b;
cin>>a>>b;
size_t aLoc=-1,bLoc=-1;
do
{
aLoc = a.find("1",aLoc+1);
bLoc = b.find("1",bLoc+1);
if(aLoc<bLoc)
{
cout<<a<<">"<<b;
return 0;
}
else if(aLoc>bLoc)
{
cout<<a<<"<"<<b;
return 0;
}
}while(aLoc==bLoc && aLoc!=string::npos);
cout<<a<<"="<<b;
return 0;
}
Edit:
aLoc give the position of 1 in first string, and bLoc for 2nd string
Lets take 1 exmaple
a = 10111000;
here first aLoc = 1 as the first '1' is at position 1
b = 10001100;
here bLoc = 1;
now for next iteration,
aLoc will be 3 as next '1' is at 3rd position
and bLoc will be 5 so naturally aLoc
which means '1' comes first in string a.
Hence
if(aLoc<bLoc)
a>b;
Let a = 01, b = 10.
In your program, in the first iteration, the value of a[i]^b[i] will be 1. But a[i] < b[i] and you have not accounted for this case, thus the value of x remains 0.
In the second iteration, again the XOR condition is true, and the condition (a[i] > b[i]) is also true, thus incrementing the value of x to 1.
After the loop, it will print 01 > 10 which is obviously false.
Modified Code:
#include <iostream>
int main() {
std::string a, b;
std::cin >> a >> b;
int la = a.length(), lb = b.length();
int x = 0;
// -1 if both are equal
// 0 if a > b
// 1 if b > a
int flag = -1;
// if you only want to check for equal length strings
if (la == lb)
{
for (int i = 0; i < la; i++)
{
if (a[i]^b[i] == 1)
{
if(a[i] > b[i])
flag = 0;
else
flag = 1;
break;
}
}
if (flag == 0)
std::cout << a << " > " << b << std::endl;
if (flag == 1)
std::cout << a << " < " << b << std::endl;
if (flag == -1)
std::cout << a << " = " << b << std::endl;
}
}

Printing triangle with given letter in C++

I would like to to print a triangle with a given letter. For example, if I input D, the program should return:
A
AB
ABC
ABCD
So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?
#include <iostream>
using namespace std;
int main() {
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
if (65 < c) {
cout << "A";
cout << endl;
}
if (66 < c) {
cout << "AB";
cout << endl;
}
if (67 < c) {
cout << "ABC";
cout << endl;
}
for (int i = 64; i < c; i++) {
cout << static_cast<char>(i + 1);
}
return 0;
}
You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.
char first = 'A';
char last = 0;
cout << "Enter a char: ";
cin >> last;
fflush(stdin);
cout << "\n\n";
if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
{
last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
}
if ((last > 64) && (last < 91))
{
for (char i = 65; i <= last; i++)
{
for (char j = 65; j <= i; j++)
{
cout << j;
}
cout << "\n";
}
}
else
{
cout << "\nWrong character!!\n\n";
return 0;
}
Use a nested loop structure. Use the outer loop to 'walk' down your triangle,
lineLength = 1;
while(lineLength <= (c - 64)){
...stuff...
lineLength++;
cout << endl;
}
Use the inner loop to 'walk' down the alphabet (you've already done most of this):
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
Putting it together:
lineLength = 1;
while(lineLength <= (c - 64)){
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
lineLength++;
cout << endl;
}
I see that someone else has posted a similar answer. Between these two answers, you should be able to find your way. I haven't compiled and run this code, but I believe that it should work or be very close.
Don't harcode ascii integer values into code. Explicitly use the character or string literals (e.g. 'A' instead of 65)
Start with a helper function to print exactly one line
// prints all the characters of the alphabetic sequence from "A" to the final char designated by <c>
void printTriangleLine(char c)
{
if ((c < 'A') || (c > 'Z'))
{
return;
}
for (char x = 'A'; x <= c; x++)
{
cout << x;
}
cout << endl;
}
Then put it all together in your main:
int main()
{
char i;
cout << "Enter char ";
cin >> i;
if ((i < 'A') || (i > 'Z'))
{
return 0;
}
for (char x = 'A'; x <= i; x++)
{
printTriangleLine(x);
}
return 0;
}
We must run the loop from position is above 'A' character
until we reached the charanter you enter
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
in each loop we increment character value by 1 to go to the next value
// go to next letter
chNew++;
inner loop simply print the character from A to next value relative to current chNew + 1, it is because we also want to include current character to our printed line.
Here is your working code.
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
// start with 'A' - 1 character
char chNew = 'A' - 1;
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
// we have done
return 0;
}

After completing the output,console application exits.. How to make it ask for input again?

I created a console application in VStudio 2015.... and after it executes properly,asks for input and shows the output, it says press any key to continue.
I want the program to ask again for the input...
Heres the code :-
#include "stdafx.h"
#include "iostream"
#include "stdio.h"
using namespace std;
int main()
{
int a, b, n;
cout << "Enter the number of lines:";
cin >> n;
for (a = 1; a <= n; a++)
{
for (b = 1; b <= a; ++b)
{
cout << a;
}
cout << "\n";
}
system("pause");
return 0;
}
Add another loop:
int a, b;
int n = 1;
while (n > 0)
{
cout << "Enter the number of lines:";
cin >> n;
for (a = 1; a <= n; a++)
{
for (b = 1; b <= a; ++b)
{
cout << a;
}
cout << "\n";
}
}
Put a third loop on top of your code.
int a, b, n;
while(true)
{
// here you need to figure out how to break loop
// I mean how to go out from it. It depends on your
// purpose
cout << "Enter the number of lines:";
cin >> n;
if (n==-1)
{
// I assume n should be larger than 0 for your purpose.
break;
}
for (a = 1; a <= n; a++)
{
for (b = 1; b <= a; ++b)
{
cout << a;
}
cout << "\n";
}
}
Edit
Although I do not think its necessary, as you can see, someone thinks that using n<=0 is better choise than n==-1. Its your call. You can either change it, or just type an information which states that which number the user should give as an input in order to terminate the program.

Display output 4 per line

I'm taking my first programming course and am new to this forum. Any help will be greatly appreciated! For one of my class assignments I had to write a program that would find the factors of a given number, I've got the program up and running but one of the stipulations is that the output must be displayed four to a line and that's where I'm running into trouble. I've read around on some other forums as well as here but I guess I'm not grasping what I would have to do in my particular case.
Here's my code as is:
#include <iostream>
using namespace std;
int main(){
int n;
while (cout << "Please enter a number: " && !(cin >> n) || (n < 0.0) || cin.peek() != '\n')
{
cout << "Input must be a positive number!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
for (int i=2; i <= n; i++)
{
while (n % i == 0)
{
n /= i;
cout << "*" << i;
}
}
cout << endl;
system ("PAUSE");
return 0;
}
You're going to need to add a counter outside the loop.
//int counter = 0;
for (int i=2; i <= n; i++)
{
while (n % i == 0)
{
n /= i;
cout << "*" << i;
}
}
The counter will need to keep track of how many entries have been printed.
Once you have seen 4 entries printed:
print an extra newline
and set the counter back to 0
You may use the following:
void display_factors(std::size_t n, std::size_t factor_by_line)
{
const char* sep = "";
std::size_t count = 0;
std::cout << n << " = ";
for (int i = 2; i <= n; ++i) {
while (n % i == 0) {
n /= i;
if (count == factor_by_line) {
std::cout << std::endl;
count = 0;
}
++count;
std::cout << sep << i;
sep = " * ";
}
}
std::cout << std::endl;
}
Live Demo