Problems with terminating loop at specific time - c++

Having trouble with my loop. The program is supposed to resemble a print out of a
lotto ticket. The user enters in how many sets of lotto numbers he/she wants. Each line is labeled alphabetically, yet if someone wants more then ten lines (letter J) of lotto numbers the program is supposed to start back over at A again. My problem is that if anyone enters 10 (or any interval of ten) "mega" gets printed like so:
"Mega" should only be printed again if there is another line of lotto numbers.
In "int main()" inside the "for()" is my attempt to remedy this problem.
#include <iostream> //I/O
#include <iomanip> //setw
#include <ctime> //seeding srand
#include <string> //size
#define RAND(a,b) (a+rand()% (b-a+1))
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
/*
Author: Zachary Stow
Date: July/20/15
Homework #5
Objective: To design a program that imitates the print out
of a lottery ticket.
*/
//********************************fillup()********************************
void fillup(int lotto[], int n, int from, int to)
{
void bubble_sort(int x[], int n);
for(int i = 0; i < n; i++)
{
lotto[i] = RAND(from,to);
}
bubble_sort(lotto,5);
}
//*****************************bubble_sort()******************************
void bubble_sort(int x[], int n)
{
for(int i = 0; i < n-1; i++)
{
int temp;
for(int j=i+1; j<n ; j++)
{
if(x[i] > x[j])
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
//********************************print()*********************************
void print(int x[], int n)
{
for(int i = 0; i < n; i++)
{
cout << setfill('0') << setw(2) << x[i] <<" ";
}
cout <<" ";
cout << setfill('0') << setw(2) << RAND(1,46);
cout << endl;
}
//********************************isNumber********************************
bool isNumber(string str)
{
for(int i = 0; i < str.size(); i++)
{
if(!isdigit(str[i]))return(false);
}
return(true);
}
//**********************************check*********************************
void check(int argc, char **argv)
{
bool isNumber(string);
if(argc != 2)die("usage: megaMillion number_tickets");
string num_tickets = argv[1];
if(!isNumber(num_tickets))die("Not a digit."); //removed num_tickets for now
int num;
num = atoi(num_tickets.c_str());
if(num <= 0)die("Zero or negative number."); //doesnt work
}
//*********************************printmega()****************************
void printmega(int letter)
{
if(letter == 65)
{
cout << endl;
cout <<" Mega" << endl; //10 you get a mega
}
}
//*********************************main()*********************************
int main(int argc, char **argv)
{
void fillup(int x[], int n, int from, int to);
void print(int x[], int n);
void check(int argc, char **argv);
void printmega(int letter);
check(argc, argv);
srand(time(NULL));
cout <<" Mega" << endl;
int letter = 65;
for(int i = 0; i < atoi(argv[1]); i++)
{
if(i == atoi(argc[1]))cout << "Hi"; //my attempt to stop the loop from printing
//only mega after J
cout <<(char)letter++; //when theres no more lines
cout <<" ";
if(letter == 75)letter = 65;
int lotto[5];
fillup(lotto,5,1,56);
print(lotto,5);
printmega(letter);
}
return(0);
}

For this problem I would choose to use two nested loops, here is a minimal example:
#include <iostream>
int main(int argc, char** argv)
{
double aValues[] = {1, 2, 3, 4, 5, 6, 7, 8, 6, 2};
int nTotalLines = sizeof(aValues)/sizeof(double);
int nLinesPerBlock = 5;
int nLineNumber = 0;
for (int i = 0; i <= nTotalLines/nLinesPerBlock
&& nLineNumber < nTotalLines; ++i)
{
std::cout << "Start of block..." << std::endl;
for (int j = 0; j < nLinesPerBlock && nLineNumber < nTotalLines; ++j)
{
std::cout << " Number: " << aValues[nLineNumber++] << std::endl;
}
}
return 0;
}
You will need to adapt this code to fit your problem. It is not necessary to use nested loops but to me it seems more logical (you cycle one outer loop for each block and one inner loop for each line).
Another tip: Make use of variables so you don't need to keep typing things like atoi(argv[1]), instead create a variable int name = atoi(argv[1]); and use name wherever you need it.

Related

C++ pattern output

I am working on a project that requires me to have a loop output a pattern into the console.
I have to use a for loop in my code. I've gotten to a point where I can only get half of the pattern onto the screen but the rest does not appear in the console.
My code:
#include <iostream>
using namespace std;
int main()
{
int i, j;
for (i=5; i>=1; i--)
{
for (j=1; j != i; j++)
{
cout << "5";
cout << "#";
cout << endl;
}
}
return 0;
}
So this code outputs:
####5
###5
##5
#5
5
But I need it to output:
####5
###5#
##5##
#5###
5####
How would I change my code to get it to show that output?
I hope that makes sense,
Thank you
your internal loop is the one that tracks moving 5 from right to left
for (i=5; i >= 1; i--) {
for (j=1; j <= 5; j++) {
cout << (( i == j ) ? "5" : "#");
}
cout << endl;
}
removing the fancy things
for (i=5; i >= 1; i--)
{
for (j=1; j <= 5; j++)
{
if( i == j )
cout << "5";
else
cout << "#";
}
cout << endl;
}
This is what you are looking for.
#include <iostream>
using namespace std;
int main()
{
int i,j;
for (i=4; i>=0; i--)
{
for(int z=0; z<5;z++){
if(z==i){
cout <<"5";
}
else{
cout <<"#";
}
}
cout <<"\n";
}
return 0;
}
####5
###5#
##5##
#5###
5####
Chears :-)
Let's be clear: the OP's code is completely wrong and I cannot understand how it works and produces that output, so I wrote it from scratch.
Before_edit:
I can't understand how your code work, so I rewrite that from scratch.
#include <iostream>
void output_sharp(int cnt)
{
while (cnt != 0)
std::cout << "#";
}
int main(int argc, char *argv[])
{
for (int i = 0, j = 4; i != 5; ++i, --j) {
output_sharp(j - i);
std::cout << "5";
output_sharp(4 - j);
}
return 0;
}

Recursively storing integers in an array

I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}
The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}
Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}
Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}

Square Root Code C++ without sqrt()

I have to create a code where the user inputs a number which is a perfect square, and I have to show its root. I've made this code, but I'm getting Segmentation Fault 11 , in this piece: int j = squareRootVector[i];
squareRoot.push_back(j);.
I can't change the code too much, so is there a way that I can do that?
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout <<
"Enter the number:\n";
int input;
int number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
cin >> number;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
cout << number << endl;
squareRootVector.push_back(divider);
}
}
for(int i = 0; i < squareRootVector.size(); i++) {
cout << squareRootVector[i] << " ";
/*******PROBLEM*******/
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
/*********************/
}
int root;
for (int i = 0; squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is: " << root << endl;
return 0;
}
The behaviour on accessing squareRootVector[i+1] with i just one below size (which your loop constaint allows) is undefined.
Consider writing
for (std::size_t i = 1; i < squareRootVector.size(); i++) {
instead, and rebasing the for loop body accordingly. I've also slipped in a change of type for i.
Shortly, the problem is that the last cycle in the last "for":
for(int i = 0; i < squareRootVector.size(); i++)
has the following line in it:
squareRootVector[i] == squareRootVector[i+1];
This is an "out of limits" error: squareRootVector only has squareRootVector.size() elements (let's say n), and the elements are indexed from 0 to n-1.
squareRootVector[i+1] in the last cycle points one element after the last one of squareRootVector, which is undefined behavior.
Using vector::iterator is proper way.
for(vector<int>::iterator it = squareRootVector.begin(); it != squareRootVector.end(); ++it)
{
if( (it+1) == squareRootVector.end() )
{
//what to do if there's no next member???
break;
}
if( *it == *(it+1) )
{
squareRoot.push_back(*it);
}
}
Thanks for the answers, guys. I've ended up with this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Enter the number:\n";
int input = 0;
int number = 0;
cin >> input;
number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
squareRootVector.push_back(divider);
}
}
int vectorSize = squareRootVector.size() - 1;
for(int i = 0; i < vectorSize; i++) {
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
}
int root = 1;
for (int i = 0; i < squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is " << root << endl;
return 0;
}

c++ output of stars using recursion

I am trying to do this exercise.
Write a recursive function to generate a pattern of stars such as the following:
*
**
***
****
****
***
**
*
It seems simple but is giving me a lot of problems. I can only output this
*
**
***
****
using the following code
#include <iostream>
using namespace std;
void outputStars(int);
int main()
{
outputStars(5);
return 0;
}
void outputStars(int num)
{
if (num == 1)
{
return;
}
outputStars(--num);
for (int i = 0; i < num ; i++)
{
cout << "*";
}
cout << endl;
}
You are only printing the stars when you return from the call. Also print it before you call.
I've modified it to take 2 arguments. i specifies number of times * is to be printed in a call
void outputStars(int num,int i)
{
if (i == num)
{
return;
}
for (int j = 0 ;j < i; j++)
{
cout << "*";
}
cout << endl;
outputStars(num,i+1);
for (int j = 0; j < i; j++)
{
cout << "*";
}
cout << endl;
Call it as
outputStars(5,1);
#include <stdio.h>
void rec_fun(int x);
void print_stars(int times, int x);
int main(int argc, char *argv[])
{
rec_fun(5);
return 0;
}
void rec_fun(int x)
{
static int times = x;
if (x <= 0)
return;
print_stars(times, x);
rec_fun(x - 1);
if (x != 1)
print_stars(times, x);
}
void print_stars(int times, int x)
{
int i;
for (i = 0; i < times - x + 1; i++)
printf("*");
printf("\n");
}

Run Time Check failure # 2 - Stack around variable 'ary' was corrupted. Why?

I'm new, don't know what I'm doing.
The compile warnings are on and do not show any warnings. Executable pops up and alerts of Run Time Check Failure #2.
Help would be appreciated as to why this is happening.
#include <iostream>
#include <string>
using namespace std;
class romanType {
public:
string strg;
void inputRoman(int ary[]);
//void CalculateRoman(int ary[]);
//void outputRoman(int total);
};
int main()
{
int M = 1000;
int D = 500;
int C = 100;
int L = 50;
int X = 10;
int V = 5;
int I = 1;
romanType numerals;
int ary[50];
cout << "This is to convert your input of Roman numerals to a positiver integer" << endl;
cout << "When prompted, do as you're told" << endl;
numerals.inputRoman(&ary[50]);
// numerals.CalculateRoman(&input[50]);
return 0;
}
void romanType::inputRoman(int ary[])
{
string strg;
int array_size;
int i;
cout << "Input the an appropriate Roman Numeral value" << endl;
cin >> strg;
array_size = strg.length();
for (i = 0; i < array_size; i++)
{
ary[i] = strg[i];
}
}
/*
void romanType::CalculateRoman(int ary[])
{
int total = 0;
int i;
for (i=0; i < 50 ; i++){
if (ary[i] < (ary[i + 1])){
total = total + (ary[i + 1] - ary[i]);
}
else {
total = total + ary[i];
}
}
cout << "Your conversion should equal " << total << endl;
}
*/`
&ary[50] is the address of 51st element of ary, which means it points just after the last element of ary. Change it to ary:
numerals.inputRoman(ary);