I have written a code in C++ for finding largest and second largest element in a array. Code works fine but the problem is location of second largest number is not updated. Although value of second largest number is correct but its location is not correct.
#include<iostream>
using namespace std;
void main()
{
int DATA[10];
int largestNumber, secondLargestNumber, loc1, loc2;
cout << "Enter 10 numbers of array DATA" << endl;
for (int i = 0; i < 10; i++)
{
cin >> DATA[i];
}
largestNumber = DATA[1];
secondLargestNumber = DATA[2];
loc1 = 1;
loc2 = 2;
if (largestNumber < secondLargestNumber)
{
largestNumber = DATA[2];
secondLargestNumber = DATA[1];
}
for (int i = 2; i < 10; i++)
{
if (DATA[i]>largestNumber)
{
secondLargestNumber = largestNumber;
largestNumber = DATA[i];
loc1 = i;
}
else if (DATA[i]>secondLargestNumber)
{
secondLargestNumber = DATA[i];
loc2 = i;
}
}
cout << "Largest Number with location :"<<largestNumber<<" "<<loc1 << endl;
cout << "Second Largest Number location :" << secondLargestNumber<<" "<<loc2 << endl;
cin.get();
cin.get();
}
may I suggest a simpler solution?
#include <functional>
#include <set>
#include <iostream>
int main() {
std::set<int, std::greater<int>> s;
int input;
while(true) { // choose your stopping condition
cin >> input;
s.insert(input);
}
std::cout << (*s.begin()) << (*std::next(s.begin())) << std::endl;
}
if you only keep positions, not values, your code can be significantly simplified:
int largest = 0, second = -1;
for (int i = 1; i < 10; i++) {
if( second == -1 || DATA[i] > DATA[second] ) {
second = i;
if( DATA[second] > DATA[largest] )
std::swap( largest, second );
}
}
use "loc2=loc1" statement at first if block I think it will work ,check this code,
for (int i = 2; i < 10; i++)
{
if (DATA[i]>largestNumber)
{
secondLargestNumber = largestNumber;
loc2=loc1;
largestNumber = DATA[i];
loc1 = i;
}
else if (DATA[i]>secondLargestNumber)
{
secondLargestNumber = DATA[i];
loc2 = i;
}
}
I'm at my wit's end with this code and I am new to c++ so I don't even know where to begin to check for this error. What is causing the segmentation fault in my code and how do I fix it?
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
class Student
{
private:
string name;
int numClasses;
vector<string> classList;
public:
Student (string nameVal, int numClassesVal, string classListArr[]);
Student (string nameVal, int numClassesVal);
Student (string nameVal);
Student ();
void setName(string nameVal);
void setNumClasses(int numClassesVal);
void setClassList(string classListArr[]);
string getName();
int getNumClasses();
vector<string> getClassList();
void input();
void output();
void reset();
};
int main ()
{
Student user;
string answer;
int flag = 1;
while (flag == 1)
{
user.input();
user.output();
cout << "Do you want to enter the new data? (y/n)" << endl;
cin >> answer;
cin.ignore();
if (answer == "n")
{
flag == 0;
}
}
return 0;
}
Student::Student (string nameVal, int numClassesVal, string classListArr[])
: name(nameVal), numClasses(numClassesVal)
{
string test = classListArr[0];
for (int x = 0; x < 10; ++x)
{
if ( (x > 0) && (classListArr[x] == test))
break;
classListArr[x] = classList[x];
}
}
Student::Student (string nameVal, int numClassesVal)
{
name = nameVal;
numClasses = numClassesVal;
for (int x = 0; x < 10; ++x)
{
classList[x] = "";
}
}
Student::Student (string nameVal)
{
name = nameVal;
numClasses = 0;
for (int x = 0; x < 10; ++x)
{
classList[x] = "";
}
}
Student::Student ()
{
name = "";
numClasses = 0;
for (int x = 0; x < 10; ++x)
{
classList[x] = "";
}
}
void Student::setName(string nameVal) {name = nameVal;}
void Student::setNumClasses(int numClassesVal) {numClasses = numClassesVal;}
void Student::setClassList(string classListArr[])
{
string test = classListArr[0];
for (int x = 0; x < 10; ++x)
{
if ( (x > 0) && (classListArr[x] == test))
break;
classListArr[x] = classList[x];
}
}
string Student::getName() {return name;}
int Student::getNumClasses() {return numClasses;}
vector<string> Student::getClassList() {return classList;}
void Student::input()
{
string temp;
int classes;
cout << "Input Student's Name:" << endl;
getline(cin, temp);
name = temp;
cout << "Input Number of Classes:" << endl;
cin >> classes;
cin.ignore();
numClasses = classes;
for (int x = 0; x < 10; ++x)
{
if ( x == 9)
{
cout << "Input Last Class Name (Maximum of 10):";
getline(cin, temp);
classList[9] = temp;
}
else
{
cout << "Input Class Name:";
getline(cin, temp);
classList[x] = temp;
cout << "Do you have any more classes? (y/n):";
getline(cin, temp);
if ( temp == "n")
break;
}
}
}
void Student::output()
{
cout << "Student Name: " << name << "\nNumber of Classes: " << numClasses << endl;
cout << "Names of Classes: " << endl;
for (int x = 0; x < 10; ++x)
{
if ( numClasses == 0 )
break;
if ( x == 0 )
cout << "Names of Classes: \n";
if ( classList[x] == "" )
break;
cout << "(" << x << ") " << classList[x] << "\n";
}
}
void Student::reset()
{
numClasses = 0;
for (int x = 0; x < 10; ++x)
{
classList[x] = "";
}
}
I tried changing the main function from before where I had a goto statement instead of a flag, and that didn't fix it. I think it's the cin.getline() but I am not sure.
You have undefined behavior in this code (and the other constructors):
Student::Student ()
{
name = "";
numClasses = 0;
for (int x = 0; x < 10; ++x)
{
classList[x] = "";
}
}
You never allocated any elements in the classList vector, so the reference to classList[x] is out of bounds. You should use .push_back() to add new elements to the vector:
Student::Student ()
{
name = "";
numClasses = 0;
for (int x = 0; x < 10; ++x)
{
classList.push_back("");
}
}
Or before the loop you could do classList.reserve(10); to make room for 10 elements.
See C++ Tutorial: A Beginner's Guide to std::vector
First, I am a beginner coder and I have tried to tackle and solve parts of my problem for hours and can not figure it out.
I have done all the task except for two tasks:
1.) I can not figure out how to use input and outfile mechanism of ifstream and ofstream to get my .txt file to set my values for my sudoku board.
2.) I cannot seem to figure out how to print out a sudoku board for each "possible values" for each xyposition in the cells.
I am trying to implement a text file that reads:
puzzle.setBoardValue(0,0,1);
puzzle.setBoardValue(1,1,3);
puzzle.setBoardValue(2,2,9);
puzzle.setBoardValue(3,2,6);
puzzle.setBoardValue(4,1,2);
puzzle.setBoardValue(5,0,7);
puzzle.setBoardValue(6,2,5);
puzzle.setBoardValue(7,0,9);
puzzle.setBoardValue(8,1,8);
puzzle.setBoardValue(0,5,6);
puzzle.setBoardValue(1,4,1);
puzzle.setBoardValue(2,3,5);
puzzle.setBoardValue(3,3,3);
puzzle.setBoardValue(4,4,8);
puzzle.setBoardValue(5,5,4);
puzzle.setBoardValue(6,3,9);
puzzle.setBoardValue(8,4,2);
puzzle.setBoardValue(0,6,3);
puzzle.setBoardValue(1,7,4);
puzzle.setBoardValue(2,8,7);
puzzle.setBoardValue(6,8,3);
puzzle.setBoardValue(7,6,1);
puzzle.setBoardValue(8,7,7); `
and basically use that to and automatically direction my program to the function void setBoardValue(); All I have figured out was in my int main(); where I put
cout << "Enter filename:" << endl;
cin >> filename;
in.open(filename);
while(getline(in,line)){
...
Secondly, I just can not figure out how to print all the possible values for each number cells.
Here is my entire program code:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class SudokuPuzzle{
private:
unsigned short board[9][9];
char BlankChar;
bool debug;
void printTracerTryingValue(int xpos, int ypos);
bool solve(int xpos, int ypos);
bool verifyValue(int xpos, int ypos);
public:
SudokuPuzzle();
void print();
void setBoardValue(int xpos, int ypos, int value);
int getBoardValue(int xpos, int ypos);
bool solve();
};
SudokuPuzzle::SudokuPuzzle(){
debug = false;
for (int i = 0; i < 9; ++i){
for (int j = 0; j < 9; ++j){
board[j][i] = 0;
}
}
}
void SudokuPuzzle::print(){
for (int y = 0; y < 9; y++){
if (y % 3 == 0){
cout << "-------------------------------" << endl;
}
for (int x = 0; x < 9; x++){
if (x % 3 == 0){
cout << "|";
}
if (board[x][y] != 0){
cout << " " << board[x][y] << " ";
}
else{
cout << " . ";
}
}
cout << "|" << endl;
}
cout << "-------------------------------" << endl;
}
void SudokuPuzzle::setBoardValue(int xpos, int ypos, int value){
board[xpos][ypos] = value;
}
void SudokuPuzzle::setBoardValue(int xpos, int ypos, int value){
board[xpos][ypos] = value;
}
bool SudokuPuzzle::solve(){
return solve(0,0);
}
void SudokuPuzzle::setBoardValue(int xpos, int ypos, int value){
board[xpos][ypos] = value;
}
bool SudokuPuzzle::solve(){
return solve(0,0);
}
int SudokuPuzzle::getBoardValue(int xpos, int ypos){
return board[xpos][ypos];
}
bool SudokuPuzzle::solve(int xpos, int ypos){
if (board[xpos][ypos] != 0){
if (verifyValue(xpos, ypos)){
if (xpos == 8 && ypos == 8){
return true;
}
int next_x = xpos+1;
int next_y = ypos;
if (next_x >= 9){
next_x = 0;
next_y++;
}
return solve(next_x, next_y);
}
else{
return false;
}
}
for(int value = 1; value < 10; value++){
setBoardValue(xpos, ypos, value);
if (verifyValue(xpos, ypos)){
if (xpos == 8 && ypos == 8){
return true;
}
int next_x = xpos+1;
int next_y = ypos;
if (next_x >= 9){
next_x = 0;
next_y++;
}
if (solve(next_x, next_y)){
return true;
}
}
}
board[xpos][ypos] = 0;
return false;
}
bool SudokuPuzzle::verifyValue(int xpos, int ypos){
printTracerTryingValue(xpos, ypos);
int value = board[xpos][ypos];
for (int x_verify = 0; x_verify < 9; x_verify++){
if (x_verify == xpos){
continue;
}
int verifyValue = board[x_verify][ypos];
if (verifyValue == value){
return false;
}
}
for (int y_verify = 0; y_verify < 9; y_verify++){
if (y_verify == ypos){
continue;
}
int verifyValue = board[xpos][y_verify];
if (verifyValue == value){
return false;
}
}
int box_x = xpos / 3;
int box_y = ypos / 3;
for (int y_verify = box_y * 3; y_verify < box_y * 3 + 3; y_verify++){
for (int x_verify = box_x * 3; x_verify < box_x * 3 + 3; x_verify++){
if (x_verify == xpos && y_verify == ypos){
continue;
}
int verifyValue = board[x_verify][y_verify];
if (verifyValue == value){
return false;
}
}
}
return true;
}
void SudokuPuzzle::printTracerTryingValue(int xpos, int ypos){
if(debug){
for (int i = 0; i < xpos+ypos; i++){
cout << " ";
}
cout << "Trying value " << board[xpos][ypos] << " at board[" << xpos << "][" \
<< ypos <<"]" << endl;
}
}
int main(int argc, char *const argv[]){
SudokuPuzzle puzzle;
string filename;
string line;
ifstream in;
ofstream out;
cout << "Enter filename:" << endl;
cin >> filename;
in.open(filename);
while(getline(in, line)){
puzzle.line.print()
}
cout << endl;
if(puzzle.solve()){
cout << "Solution:" << endl;
puzzle.print();
}
else{
cout << "Puzzle is not solvable.";
}
cout << endl;
return 0;
}
Your question is written a bit confusingly, but I'll try to answer it as I've understood it. Firstly, I hope you don't have the actual function calls in your text file - there's no way to call a function directly like that from a text file.
Also, in your while statement in main(), calling puzzle.line.print() doesn't make sense, because print() is not a method of std::string and your 'line' is not a member of the SudokuPuzzle type.
So, if you're just interested in storing and reading positions on a grid where you expect the input to be regular, you might have a file that simply looks like this:
0 0 1
1 1 3
2 2 9
...(etc)
From there, without concern for input or error checking, we might have some code like this, to read from the file:
std::ifstream readFile("Text.txt"); //construct ifstream object from text file
std::vector<int> vec;
int file_input; //temporary variable to hold input
while(readFile >> file_input)
{
vec.push_back(file_input);
};
readFile.close();
working with filestreams is just like working with std::cin or std::cout; You use the stream operators << and >> to carry information between streams and other data.
Now, we can do whatever processing we need to on the data structure (in this case std::vector but it could be anything).
When we need to write it back, we can use this kind of code:
std::ofstream writeFile("Text.txt"); //overwrites contents!
for(unsigned i = 0; i < vec.size(); ++i)
{
//this is just to format the text output to the same way it came in
writeFile << vec[i] << ' ';
if ((i + 1) % 3 == 0)
writeFile << '\n';
}
writeFile.close();
In the block of code where you format the text for output is where you may want to do something like using characters like | and _ to create some grid pattern. You should have some idea of how to go about that (think about where they need to be inserted, they should come in predictable places).
Here's some example code as well.
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
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);