Why this loop corrupts the array? - c++

I am posting here because I need your help with this issue. I have been trying to fix it by my own but I had not luck. I really do not understand what is happening. If you look at my code you will notice that I have the following loop :
for (j = 0; j < total_scores; j++)
{
cout << "P is " << p << endl ;
cout << "Enter score : ";
cin >> scores[p];
p++;
}
Well , If I enable this piece of the code , the array that stores the names is corrupt and I obtain a weird result for the position 0 : 4# and one error "Run-Time Check Failure #2 - Stack around the variable 'scores' was corrupted."
I really do not understand why , or how to fix this.Without the loop that ask for scores the loop with the names remains intact. I do not understand what is happening here if they are two separated elements.
Any idea? I really appreciate your time and your attention .
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int total_students= 2 ;
const int scores_students = 1 ;
const int total_scores = scores_students*total_students;
string names[total_students];
double scores[total_scores];
double average[scores_students];
double averages=0.0;
int i;
int j = 0 ;
int k;
int l;
int m;
int p = 0 ;
for (i = 0; i < total_students; i++)
{
cout << "I is " << i << endl;
cout << "Enter name : ";
cin >> names[i];
for (j = 0; j < total_scores; j++)
{
cout << "P is " << p << endl ;
cout << "Enter score : ";
cin >> scores[p];
p++;
}
}
for (m = 0 ; m < total_students ; m++)
{
cout << "\nName : " << names[m] << endl << endl ;
//cout << "Average : " << average[m] << endl;
}
system("pause");
system("pause");
}
What I need is the program to ask for name , and then the test results based on "scores_students" , then the second name and the next scores. And so on
Example of Input that I am looking for :
Name Score1
Peter 20
Mark 100

You have a loop inside a loop, so p can end up being incremented to 4, so you try to access scores[4] when the array size is only 2.
Based on comments, looks like the answer is that the "j loop" should be for (j = 0; j < scores_student; j++) instead of total_scores which causes the overflow mentioned above.

Related

wrong output in common number array program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I need my code to output the common numbers from two arrays but I can't seem to find the issues in my code. Here are some more words so I can fill the quota for stack's post requirement.
Here's the code.
#include <iostream>
using namespace std;
int main()
{
//Variables
int list1[5], list2[5];
cout << "Enter numbers for List No.1" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ":";
cin >> list1[i];
}
cout << "Enter numbers for List No.2" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Enter number " << i << ":";
cin >> list2[i];
}
{
cout << "common elements" << endl;
for (int i = 0; list1; i < i++) {
for (int i = 0; list2; i < i++)
if (list1[i] == list2[i]) {
cout << " " << list1[i];
}
}
}
return 0;
}
You should use different counter for each loop and also your loop has wrong parameters. Do it like:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (list1[i] == list2[j]){
cout<<" "<<list1[i];
}
}
}
Also for initial values start from zero index([0]) as zero index is the first element for each array:
for (int i = 0; i < 5; i++) {
cout << "Enter number " << i << ":";
cin >> list1[i];
}
Another way to do this is by using std::array. It acts very similar to a normal array but it is much better to work with.
for example if you want a char array of length of 10 you can simply write:
std::array<char, 10> My_happy_array.
First please read this to understand why you should not using namespace std. Second consider reading about Range-based for loop
Third, here is the modified version of your program which uses std::array instead of a normal array:
#include <iostream>
#include <array>
int main() {
std::array<int,5> list1;
std::array<int,5> list2;
std::cout << "Enter numbers for List No.1" << std::endl;
for (int i = 0; i < list1.size(); ++i) {
std::cout << "Enter number " << (i+1) << ":";
std::cin >> list1[i];
}
std::cout << "Enter numbers for List No.2" << std::endl;
for (int i = 0; i < list2.size(); ++i) {
std::cout << "Enter number " << (i+1) << ":";
std::cin >> list2[i];
}
for(auto i : list1){
for(auto j : list2){
if(i==j){
std::cout << " " << i;
}
}
}
return 0;
}
Here's fixed code
#include <iostream>
using namespace std;
int main()
{
//Variables
int list1[5] ,list2[5];
cout << "Enter numbers for List No.1" << endl;
for(int i = 0; i < 5; i ++)
{
cout << "Enter number " << i << ":";
cin >> list1[i];
}
cout << "Enter numbers for List No.2" << endl;
for(int i = 0; i < 5; i ++)
{
cout << "Enter number " << i << ":";
cin >> list2[i];
}
cout<<"common elements"<<endl;
for (int i = 0;i<5; i++)
{
for (int j = 0;j<5; j++)
{
if (list1[i] == list2[j])
{
cout<<" "<<list1[i];
}
}
}
return 0;
}
mistakes in code:
you used for loops wrongly whole the time.
array of 5, stores values in index (0,1,2,3,4) not (1,2,3,4,5), so always start loop from 0 and ends before max index (for this case '4' ie. use 'i<5')
while using for loop inside other for loop never use same iterable variable like you used i in both loops use i and j different for each loop,
take a look in my code..
ask me if you get any difficulties.

I got infinite loop while practicing array in C++ to find reversed number

Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.

Not reading C++ input

I have only a little experience in C++. I'm trying to write a program to print each element of the 'sales' array:
#include <iostream>
#include <iomanip>
using namespace std;
void printArray(int, int);
int main()
{
char chips[5][50] = {"mild", "medium", "sweet", "hot", "zesty"};
int sales[5] = {0};
int tempSales, counter;
const int i = 5;
for (counter = 0; counter < i; counter++)
{
cout << "Please enter in the sales for " << chips[counter] << ": ";
cin >> tempSales;
tempSales >> sales[counter][5];
}
cout << "{";
for (int counter = 0; counter < i; counter++)
{
cout << chips[counter] << ", ";
}
cout << "}" << endl;
cout << "{";
for (int counter = 0; counter < i; counter++)
{
cout << sales[counter] << ", ";
}
cout << "}" << endl;
return 0;
}
To solve this problem, I need to have the same commands and keywords I still have, and it can't be any advanced or weird syntax. For some reason, my input from the:
cin >> tempSales
Is not functioning. Here are the results:
{mild, medium, sweet, hot, zesty, }
{0,0,0,0,0, }
Whereas I just want to see 1, 2, 3, 4, and 5 for the second array. Why is it only print 0 and not reading my input? Please help!
Like rranjik stated, you shouldn't need a 2D array if you're only listing the number of sales, which it appears you're doing from what you provided, is this not the case?
Is it necessary for you to use the bitshift operator >> for your assignment? For a simple integer assignment it isn't really necessary, and you could do:
int sales[5] = {0}; Change the array to a simple array instead of 2D.
sales[counter] = tempSales; Use standard assignment for the integer on line 19
cout << sales[counter] << ", "; Change your output accordingly.
Hope this helps!
I don't think you need a 2D array for sales. Try cout << sales[counter][5] << ", "; or change int sales[5][6] = {0}; to int sales[5] = {0};. As Luke mentioned, use standard assignment sales[counter] = tempSales;.

Creating a Table of Powers with C++

I'm working on a project to print out a table of exponential numbers using nested for-loops. Users specify the number of rows to print and the number of powers. For example, if the users specifies 2 rows and 3 powers, the program should print 1,1,1 and 2,4,9 (2^1,2,3 etc). I should note this is for class and we aren't allowed to use cmath, otherwise I would use pow(). I can't seem to figure out the correct function in a nested for loop that can change both values of the base and the exponent. Here's what I have so far. Thanks for your help!
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
for (int q = 1; q <= i; q++)
{
a = (q * q); //This only works for static numbers...
cout << setw(8) << a;
}
cout << endl;
}
}
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
int a = 1;
for (int q = 1; q <= r; q++)
{
a = (a * i);
cout << setw(8) << a;
}
cout << endl;
}
Several things to note. First, you can compute the powers by maintaining the variable a and multiplying it by i for each power. Also, I think you want the upper bound on your second loop to be r and not i.
You need couple to change the way accumulate the values of raising a number to a power.
Also, you are using the wrong variable to end the loop in the inner for-loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.\nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
a = 1; // Start with 1
for (int q = 1; q <= p; q++) // That needs to <= p, not <= i
{
a *= i; // Multiply it by i get the value of i^q
cout << setw(8) << a;
}
cout << endl;
}
}

Result not showing as I want to (C++ code)

I'm a novice in C++ so don't really know much but I want to learn and practice. I've written a code where the user will state how many persons he/she wants to write the names, and the names will be in char. I will then have to sort this using insertion to see which name is well sorted Alphabetically.
#include <iostream>
using namespace std;
class Name{
public:
void sortInsertion(int, char* );
};
void Name::sortInsertion(int size, char *c){
for (int i = 1; i < size - 1; i++){
int j;
j = i;
while (j > 0 && c[j] < c[j - 1]){
swap(c[j], c[j - 1]);
j = j - 1;
}
}
}
int main(){
Name n;
char* name;
name = new char[30];
int* in;
int size = 0;
in = new int[size];
cout << "How many people?: ";
cin >> size;
for (int i = 0; i < size; i++){
cout << "Person " << i+1 <<": "<< endl;
cout << "Full Name: ";
cin.ignore();
cin.getline(name,29);
cout << endl;
}
n.sortInsertion(size, name);
for (int i = 0; i < size; i++){
cout << "Person " << i + 1 << ": " << endl;
cout << "Full Name: ";
cout << name << endl;
}
system("pause");
}
this is my code. It doesn't show the result as I want it to show, the output misses the first letter of the name and only repeats the printing of the last user input given.
Could you please tell me what's wrong? Any help and tip is really appreciated :)