You have to write an ITERATIVE procedure write_digit(d,x) that receives a digit d and a natural number x, and writes x times the digit d in the standard output (cout). For example, the call write_digit(3,5) writes 33333, whereas the call write_digit(5,3) writes 555.
I have problem with this code and it has to do with leading zeroes. Example:
write_digit(0,3) -> 000 -> My output: 0 (not a surprise)
The problem would be resolved in 1 minute if I was allowed to use iomanip
if (d == 0) cout << setw(x) << setfill('0') << "";
However, I CAN ONLY USE iostream and string.
#include <iostream>
using namespace std;
void write_digit(int d,int x) {
int original_d = d;
for (int i = 1; i < x; ++i) d = d*10 + original_d;
if (x == 0) cout << "";
else cout << d;
}
int main () {
int d,x;
cin >> d >> x;
write_digit(d,x);
}
You are completely overcomplicating the assignment, just make a simple loop without any edge conditions, it will work for any number, even for non-digits.
void write_digit(int d, int x) {
for (int i = 0; i < x; ++i) // Loop x times
std::cout << d; // Output digit
std::cout << '\n'; // Output newline
}
Related
Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.
Input: 1 4325121
Output: 2
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.
No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.
As you said, you need to keep it as simple as possible. Then this can be a solution:
#include <iostream>
int main()
{
int first { };
int second { };
std::cin >> first >> second;
int quo { second };
int rem { };
int count { };
while ( quo > 0 )
{
rem = quo % 10;
quo /= 10;
if ( first == rem )
{
++count;
}
}
std::cout << "Result: " << count << '\n';
}
Using while loop
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 4325121;
int count = 0;
while(b > 0)
{
int m = b % 10;
if(m == a)
{
count++;
}
b /= 10;
}
cout << count;
return 0;
}
Nice little problem. But actually, to keep it as simple as possible no calculations are needed at all. I simplified my example, and it just keeps working on the input text, which is 100% sufficient to solve the problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
char digit;
std::string number;
cout << "Input: ";
cin >> digit >> number;
int count = 0;
for (char const character : number)
if (character == digit)
count++;
cout << "Result: " << count << endl;
return 0;
}
Given the question, this code solves the problem.
My code is supposed to print an "a" amount of numbers (1 < a < n < 100000) which are simultaneously divisible by "x" and indivisible by "y" - all this for "t" amount of data sets.
I've written a code which does just that using only the main() function, but - as I'm learning about functions - I'm trying to rewrite this code to include my own function. For example, if I enter t=1, n=35, x=5 and y = 14, the output should be: "5 10 15 20 25 30".
Code 1 is the code which works fine, only with the main function. Code 2 is the code I'm currently working on which is supposed to include my function "check"
I've managed to rewrite the code 2 to a point where it returns the ASCII symbols corresponding to the numbers I'm supposed to obtain, but I'm having problems converting these symbols into numbers fulfilling my requirements.
When entering "1 7 2 4" as input data, the code returns two symbols instead of "2 6".
Any help with fixing this issue would be very appreciated...
Code 1:
#include <iostream>
using namespace std;
int main()
{
int t, n, x, y;
cin >> t;
for (int i=0; i<t; i++)
{
cin >> n >> x >> y;
for (int a=0; a<n; a++)
{
if ((a%x==0)&&(a%y>0))
cout << a << " ";
}
cout << endl;
}
return 0;
}
Code 2:
#include <iostream>
using namespace std;
string check (int n, int x, int y)
{
string result;
for (int a=0; a<n; a++)
{
if ((a%x==0)&&(a%y>0))
{
result += a;
result += " ";
}
}
return result;
}
int main()
{
int t, n, x, y;
cin >> t;
for (int i=0; i<t; i++)
{
cin >> n >> x >> y;
cout << check (n, x, y) << endl;
}
return 0;
}
What's the problem ?
This is because the following statement is understood by the compiler as if you wanted to add a single char to the string (so the char corresponding to the ascii code of a, if the string encoding is ascii):
result += a;
You may test this behavior of operator+= by trying:
result += 64; // ascii code for #
How to solve it ?
To get the result you expect, you need to convert a explicitly into a string. So change the line to:
result += to_string(a);
Isn't there an easier way ?
Alternatively, if you have a lot of formatting, and if you're comfortable with streams, you may want to consider stringstream:
string check (int n, int x, int y)
{
stringstream result;
for (int a=0; a<n; a++)
{
if ((a%x==0)&&(a%y>0))
{
result << a << " ";
}
}
return result.str();
}
The stringstreams behave as ordinary streams (e.g. cout), except that they write the result into memory. You can then easily transform the end result using the str() member function.
I am brand new to C++, and am trying to make a simple program to determine if a user-entered integer is four digits, and if so, to reverse the order of said digits and print that output.
I have a (mostly) working program, but when I try, one of two things happens:
a) if line 16 is commented out and line 17 is active, then the program prints out an infinite number of reversed numbers and the IDE (in this case, repl.it) crashes; or
b) if line 17 is commented out and line 16 is active, then the program prints out one correct line, but the next line is "Your number is too short...again" (look at code below)
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
int n, reversedNumber, remainder;
bool loopControl;
char userFinalResponse;
reversedNumber=0;
cout<<"Input a 4 digit integer and press Return\n"<<endl;
cin>>n;
while (loopControl=true){
//if ((n>9999)||(n<1000))
if ((n>9999)||((n<1000)&&(n>0)))
{
cout<<"Your number is too short or too long. Please try again.\n"<<endl;
cin>>n;
loopControl=false;
} else {
while(n != 0)
{
remainder = n%10;
reversedNumber=reversedNumber*10+remainder;
n /= 10;
loopControl=true;
}//closing brace for reversal loop
cout<<"Your reversed number is "<<reversedNumber<<"\n"<<endl;
}//closing brace for else
}//closing brace for "while (loopControl>0){"
return 0;
}//closing brace for "int main() {"
You can try this:
int number = 1874 //or whatever you need
auto str = std::to_string(number);
if (str.length() == 4) {
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
I suggest you to give a look at the algorithm header that contains a lot of useful methods that can help you while developing programs.
According to the cpp tutorials = is the assignment operator, not the comparison operator. Because of this your while loop will never terminate. You can simply initialize loopControl to true, and then set it to false when it's okay to exit:
int n, reversedNumber, remainder;
bool loopControl = true; //Initialize to true
char userFinalResponse;
reversedNumber = 0;
cout << "Input a 4 digit integer and press Return\n" << endl;
cin >> n;
while (loopControl) {
//if ((n>9999)||(n<1000))
if ((n>9999) || ((n<1000) && (n>0)))
{
cout << "Your number is too short or too long. Please try again.\n" << endl;
cin >> n;
loopControl = true; //need to keep on looping
}
else {
while (n > 0)
{
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
loopControl = false; //Ok to exit
}//closing brace for reversal loop
cout << "Your reversed number is " << reversedNumber << "\n" << endl;
}
}
#include <iostream>
using namespace std;
void gcd(){
int a,b,hcf;
for (int i = 1; i <= b; ++i) {
if (a % i == 0 && b % i ==0) {
hcf = i;
}
}
}
void pirm(){
int a,b,n,hcf;
for (int a=1;a<n;a++){
for (int b=1;b<n;b++){
gcd();
if (hcf==1) {
cout << a << " and " << b << endl;
}
}
}
}
int main(){
int n,a,b,i,hcf;
cout << "Enter a natural n, less than 100" << endl;
cin >> n;
if (n>=1 && n<100){
pirm();
}
else
cout << "You didn't enter a natural number" <<endl;
}
When I run it and enter a number, it doesn't do anything. The task is as follows:
User enters a natural N, that is less than 100. Find and output all pairs of co-primes that are < 100.
As you can tell by the code, I'm a complete newb at C++. Just wondering why the program "stops" or where I messed up the code in general. Any help is greatly appreciated.
There are a number of issues here.
First, the direct answer to your question: your program never prints because it never executes a print statement. If you enter a natural number, but hcf is never equal to 1, you will never print anything.
Now the question becomes why is hcf never 1? And that's where we start to run into more issues with your code. The main misunderstanding seems to be about scope. If you declare variables inside a function, they are within the function's "scope" -- the function can use them, and any scope inside the function can use them (e.g. loops and conditionals), but no outer scope can use them. You declare a, b, and hcfseveral times, but you only ever use them in gcd(). Not only is this unnecessary, but critically, these are different variables. You change the hcf in the scope of gcd(), but the hcf in pirm() is unchanged!
There are many ways to do what you're trying to do. The one that's closest to what you already have is to have gcd() take parameters by reference. If you change your declaration of gcd() to void gcd(int a, int b, int &hcf), and do not redeclare those variables in the first line of the function, then you are able to modify hcf in a way that will stick even when the function goes out of scope. You will then need to change your call on line 15 to gcd(a,b,hcf);.
Your algorithm could also be improved, though I believe it will still work. If you're interested in a more canonical way to find the gcd, try looking into Euclid's algorithm.
You should learn how to pass arguments to a function. Corrected your code for you, seems to be working:
#include <iostream>
void gcd(int &hcf, int a, int b)
{
for (int i = 1; i <= b; ++i)
{
if (a % i == 0 && b % i == 0)
{
hcf = i;
}
}
}
void pirm(int n)
{
int hcf;
for (int a = 1; a<n; a++)
{
for (int b = 1; b<n; b++)
{
gcd(hcf, a, b);
if (hcf == 1)
{
std::cout << a << " and " << b << std::endl;
}
}
}
}
int main()
{
int n;
std::cout << "Enter a natural n, less than 100" << std::endl;
std::cin >> n;
if (n >= 1 && n<100)
{
pirm(n);
}
else
std::cout << "You didn't enter a natural number" << std::endl;
system("pause");
return 0;
}
I was recently doing a problem in C++:
Write a program to work out if a series of 5 digits are consecutive
numbers. To make this easier, assumes the digits are a string:
string numbers = "10-9-8-7-6";
Make sure your code works for the following sequence, as well:
string numbers = "1-2-3-4-5";
I solved it, however I saw when I used cin for the string the console window threw some exception & didn't execute the program but on replacing it with getline, it worked perfectly.
Could anyone explain me the reason behind it because logically both should work properly.
The program is:
#include<iostream>
#include<string>
using namespace std;
void change(int x, int y, int &inc, int &dec)
{
if (x - y == 1)
++dec;
else if (y - x == 1)
++inc;
}
int main()
{
string s = "", snum = "";
cout << "enter 5 nos and use \'-\' to separate them: ";
cin >> s;
int i = 0, x = 0, y = 0, inc = 0, dec = 0;
for (char &ch : s)
{
if (ch == '-')
{
++i;
if (i == 1)
{
y = stoi(snum);
cout << y << endl;
}
else
{
x = y;
y = stoi(snum);
cout << x << " " << y << endl;
change(x, y, inc, dec);
}
snum = "";
}
else
snum += ch;
}
x = y;
y = stoi(snum);
cout << x << " " << y << endl;
change(x, y, inc, dec);
if (inc == 4 || dec == 4)
cout << "ORDERED";
else
cout << "UNORDERED";
return 0;
}
If you have to enter everything at the same time such as:
10 9 8 7 6
All on one line then cin does not record all that at the same time.
Concerning cin it only takes the characters before a space (" ") for example. Getline however takes that entire line and uses it. Another way to do the same thing would be to use the cstdio library and have it set up with either using printf or puts to prompt, and then use gets to gather all the information from the puts prompt. This is what I assume why it works.
Example:
cstdio library
char string[50];
printf("Enter a string of text");
gets(string);
cout << string << endl;
*EDIT
After the comment below I realized what you are asking, and if you are assuming the numbers are strings, and they are separated with hyphens and no spaces then it should work fine. It shouldn't be the problem of cin by maybe something else?
If there are spaces involved in your code then what I wrote above EDIT will be a simple solution to THAT problem.
If you need to get a formatted string, I recommend you scanf like this:
if( 5 == scanf("%d-%d-%d-%d-%d", &a, &b, &c, &d, &e) )
//welldone
// work with above 5 int easily :)
else
// Please enter again
This way you don't have to work with string at all and life would be easier.
You can easily check if these 5 are consecutive or not .
If you need not a new solution and want to get your code fixed, tell me in comment.