Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have defined a strudent as:
struct student{
char name[50];
int roll;
int marks;
};
And I'm trying to print the student in s who has the highest marks field:
struct student s[5];
int i;
cout << "Enter information of students : " << endl;
for(i=0;i<3;++i)
{
cout <<"Enter roll no : ";
cin>>s[i].roll;
cout << "Enter name : ";
cin >> s[i].name;
cout << endl << "Enter marks : ";
cin >> s[i].marks;
cout << endl;
}
for(int j=0;j<3;j++)
{
if(s[j].marks>60)
{
cout<<s[j].roll<<" "<<s[j].name<<" = "<<s[j].marks<<" is Passed"<<endl;
}
else
{
cout<<s[j].roll<<" "<<s[j].name<<" = "<<s[j].marks<<" is Failed"<< endl;
}
}
cout<<endl;
cout<<endl;
int max=s[0].marks;
for(int k=0; k<3; k++)
{
if(s[k].marks>max)
{
max=s[k].marks;
}
cout<<s[k].roll<<" "<<s[k].name<<" "<<max<<" is top in the class:"<<endl;
}
Right now my prints all the students! I just want the name and roll no of the student who has top marks among all. What am I doing wrong?
You say you: Want the name and roll of the student who has top marks among all the students
To get that you need to find the index of the student with the highest marks. But before I give you an example of how to do that, I'll need the whole s array to be initialized. This means:
Your initialization loop needs to run the size of your array (for(i = 0; i < sizeof(s) / sizeof(s[0]); ++i))
Or your array size needs to match your loop (student s[3])
Once that's done you can effectively use max_element to find your student with the top marks:
const auto it = max_element(cbegin(s), cend(s), [](const auto& lhs, const auto& rhs){ return lhs.marks < rhs.marks; });
it now points to your student with the highest marks, you can print it like this:
cout << it->roll << ' ' << it->name << ' ' << it->marks << " is top in the class\n";
You can see a live example of this here: http://ideone.com/JcPQMI
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 months ago.
Improve this question
I had declared a static variable "id" which is incremented with static function but in the output it is displaying same value everytime. I have attached the output image .
`
class student
{
public:
string name;
static int id;
char sec;
student()
{
sec = 'A';
}
static int st_id()
{
id++;
return id;
}
void st_name()
{
cout << "Enter student name:";
cin >> name;
}
};
int student ::id = 0;
int main()
{
int num, i;
cout << "Enter the no. of students in class :";
cin >> num;
student *p = new student[num];
for (i = 0; i < num; i++)
{
p[i].st_name();
}
cout << endl
<< " NAME ID SEC" << endl;
for (i = 0; i < num; i++)
{
cout << i + 1 << ")"
<< " " << p[i].name << " " << p[i].st_id << " " << p[i].sec << endl;
}
}
`
Output image :
When you write, << p[i].st_id, it doesn't call the function; instead, it prints the member function pointer. To call it, you need << p[i].st_id().
I'm still relatively new to coding and a recent assignment I had has been stumping me quite a bit.
I have two arrays that are essentially linked to one another. 0 on one side must be 0 on the other, and I need to find the easiest way to sort the one with the numbers into descending order while doing the same to the other side.
int main()
{
/// Declare Variables
int studentNum, j;
int studentGrade[20];
string studentName[20];
/// Prompt the user for the number of loops that will be required
cout << "How many students are in the class? ";
cin >> studentNum;
cout << endl;
/// Enter a for loop
for(int i=0;i<studentNum;i++)
{
/// Prompt the user to enter the names of each student in the array, as well as their respective grade.
cout << "Enter the student's name: ";
cin >> studentName[i];
cout << "Enter the student's grade (0-100): ";
cin >> studentGrade[i];
}
cout << endl << endl;
cout << setw(25) << left << "Student's Name" << setw(25)<< "Test Score" << endl;
///********Sorting block required*********
/// Enter another for loop, this time to show the array to the screen
for (int i=0;i<studentNum;i++)
{
cout << setw(25) << studentName[i] << setw(25) << studentGrade[i] << endl;
}
return 0;
}
I've looked up as many answers to this question as I can, but haven't been able to find something that would work for me. Does anyone know something I could do here? I have to keep these as two separate arrays. If possible as well, I'd like to try not using sort().
You could sort the arrays like this in a double for loop:
for(int j=0 ; j<studentNum ; j++)
for(int i=0 ; i<studentNum-1 ; i++){
if(studentGrade[i] < studentGrade[i+1]){ //swapping condition
string temp = studentName[i];
studentName[i] = studentName[i+1];
studentName[i+1] = temp;
int x = studentGrade[i];
studentGrade[i] = studentGrade[i+1];
studentGrade[i+1] = x;
}
}
If the grade of a student in the array is lower than the grade of the student next to him in the array then you could swap them and also swap their names respectively
it doesn't matter what sorting algorithm you choose, you just need to go through one of the arrays and whenever you change a cell's index you do it to the same cell index in the other array
for example:
for (int i = 0; i < size; i++){
if(arr[i]<arr[i+1]){
temp=arr[i];
temp2=arr2[i];
arr[i]=arr[i+1];
arr2[i]=arr2[i+1];
arr[i+1]=temp;
arr2[i+1]=temp2;
}
}
Use the C++ STL conventions, vector, pair and sort
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
vector<pair<string, int> > students;
cin >> n;
// Input name and grade of all students
while (n--) {
string name;
int grade;
cin >> name >> grade;
students.push_back(make_pair(name, grade));
}
// Sort students based on their grades descending
sort(students.begin(), students.end(),
[](const auto & a, const auto & b) -> bool {
return a.second > b.second;
});
// Output students' name and grade
for (auto & s : students) {
cout << setw(25) << s.first << setw(25) << s.second << endl;
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a program that prompts a user to enter a value. Each value that the user enters gets placed into a vector 'other' which is there only for validation. If a duplicate value has been entered, the user will get a prompt until they enter a unique value.
The main problem I am facing is that for some reason when running the code and printing out the results of the vector, there appears to be a duplicate entry. Could anyone please tell me why that is?
See below for my code:
// prompt to continue
cout << "Would you like to continue? [Y]es, [N]o: ";
cin >> toContinue;
while (toContinue == 'Y')
{
bool isDuplicate = 0;
// prompt for product no.
cout << "Please enter product number: ";
cin >> productB;
// Validation check for duplicate entries
for (size_t i = 0; i < other.size(); i++)
{
if (productB == other[i])
isDuplicate = 1;
while (isDuplicate == 1)
{
cout << "You have already entered this product number!" << endl;
cout << "Please enter correct product number: ";
cin >> productB;
if (productB != other[i])
other.push_back(productB);
isDuplicate = 0;
}
}
// prompt to continue
cout << "Would you like to continue? [Y]es, [N]o: ";
cin >> toContinue;
}
While its common to use std::set for unique elements, if you function must return a vector for some reasons, I used such approach:
std::set<int> my_set;
my_set.insert(1);
my_set.insert(2);
my_set.insert(1);
// ... insert more
std::vector<int> my_vector(my_set.size());
std::copy(my_set.begin(), my_set.end(), my_vector.begin());
assert(my_vector.size()==2);
Note that the vector my_vector will be sorted.
Once you enter a duplicate, you let the user re-enter a number; then you check only if the new entered number is the same as the duplicate entered before; but you do not check if the user entered a different but still duplicate value.
Generally, you mix user input with program logic; unbundling this makes the code more readable and less error prone. See, for example, the following fragments showing how one could separate these concerns:
bool isContained(const vector<int> &v, int value) {
// your code to check for duplicates goes here
}
int main() {
...
while (toContinue == 'Y') {
// prompt for product no.
cout << "Please enter product number: ";
cin >> productB;
if (isContained(other, productB)) {
cout << "You have already entered this product number!" << endl;
}
else {
other.push_back(productB);
}
// prompt to continue
cout << "Would you like to continue? [Y]es, [N]o: ";
cin >> toContinue;
}
}
Also a general hint: using appropriate data structures can also help to avoid unnecessary lines of codes; A container avoiding duplicates, for example, is std::set.
You can help yourself a great deal by breaking up the components of your logic into smaller functions.
Most of what I have done here is tidy up, but note the encapsulation of the contains function.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool contains(std::vector<int> const& vals, int val)
{
return std::count(std::begin(vals), std::end(vals), val) != 0;
}
bool shouldContinue()
{
char toContinue;
cout << "Would you like to continue? [Y]es, [N]o: ";
cin >> toContinue;
return toContinue == 'Y';
}
int getProduct(bool again)
{
int productB;
if (again)
{
cout << "You have already entered this product number!" << endl;
}
cout << "Please enter correct product number: ";
cin >> productB;
return productB;
}
void printProducts(std::vector<int> const& vals)
{
std::cout << "You have selected:";
const char* sep = " ";
for(int p : vals)
{
std::cout << sep << p;
sep = ", ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> other;
while (shouldContinue())
{
int productB = getProduct(false);
while(contains(other, productB))
{
productB = getProduct(true);
}
other.push_back(productB);
}
printProducts(other);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
/*This code creates two text files : Mokiniai.txt and Vidurkiai.txt
In Mokiniai.txt there are stored each students grades, in Vidurkiai there
should be calculated each students average grade*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int n, k, isvisopazymiu, i, pazymiai;
double vidurkis; //average grade
ofstream myfile;
myfile.open("Mokiniai.txt");
cout << "parasykite kiek mokiniu yra" << endl; cin >> n; //how many students
myfile << n << endl;
cout << "parasykite kiek yra mokiniu pazymiu"; cin >> isvisopazymiu; // how many grades one student has
for (k = 1; k <= n; k++) {
for (i = 1; i <= isvisopazymiu; i++) {
cout << "Parasykite kokie yra mokiniu pazymiai "; cin >> pazymiai; // what are students grades
myfile << " " << pazymiai;
}
myfile << endl;
}
myfile.close();
myfile.open("Vidurkiai.txt"); //trying to calculate average students grades on different file
for (k = 1; k <= n; k++) {
vidurkis = pazymiai / isvisopazymiu; //calculating students grades
myfile << k << " " << vidurkis << endl;
}
myfile.close();
return 0;
}
My problem is that: There is something wrong in vidurkiai.txt file, but I don't know what is wrong.
For example: first students grades are : 7 8 9 7 8, and average grade should be 7,8, but after coding it, in vidurkiai.txt file it shows, that average grade is 1.
The reason why it does not show the grades as expected is because you are not adding up the values.While taking the average over all the grades variable
'pazymiai' stores just the last entered variable. In order to complete the job you can use an 'array' to stores sum of grades in each array element .
cin>>pazymiai;
a[k]+=pazymiai;
where as while calculating grades use
vidurkis = a[k] / isvisopazymiu;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I get the error:
'_sleep': This function or variable has been superceded by newer
library or operating system functionality. Consider using Sleep
instead. See online help for details.
Can you guys and/or girls tell me what library is causing this error?
Code:
// A program to keep track of points and time and to give a random letter for the game scattergories
#include<iostream>
#include<ctime>
#include<string>
using std::cout;
using std::cin;
using std::string;
using std::getline;
void ltr() //gives a random letter
{
srand(time(NULL)); //gives a differant pattern every time
char letter;
letter = rand() % 27 + 64; //assigns a random letter in ascii code to a char (resulting in a random letter)
cout << "The letter is " << letter << "\n";
}
void timer()
{
cout << "You got 1.5 minutes to finish\n";
for (int i = 90; i > 0; i--)
{
if (i % 5 == 0)
cout << i << "\n";
_sleep(1000);
}
cout << "DING DONG!!! DING DONG!!! Time's up!!!\n";
}
void table()
{
int plr, ctr;
string lst[5][20]; //first dimantion: how many players. second dimantion: how many catagories, third dimantion(if added) will be the round
cin >> plr >> ctr; //parameters for later
cin.ignore(); //To avoid the "getline" reading the last input
for (int x = 0; x<plr; x++) //the player changes only after the previus player finishes
{
timer();
for (int i = 0; i<ctr; i++) //changing catagory
{
getline(cin, lst[x][i]);
}
system("cls");
cout << "Next player\n";
}
for (int x = 0; x<plr; x++) //this part (the whole "for" loop) is for confirming
{
cout << "Player number " << x + 1 << ": ";
for (int i = 0; i<ctr; i++)
{
cout << lst[x][i] << " ";
}
cout << "\n";
}
_sleep(5000);
}
int points() //points per round
{
int a, b, c, sum;
cout << "How many sections only you got?\n"; //worth 15 points
cin >> a;
cout << "How many words only you got?\n"; //worth 10 points
cin >> b;
cout << "How many words you and another person got?\n"; //worth 5 points
cin >> c;
sum = a * 15 + b * 10 + c * 5;
return sum; //Note: It doesn't matter how many sections there are.
}
int act()
{
int Points;
ltr();
table();
Points = points();
cout << "You have earned " << Points << " this round\n\n";
return Points;
}
int main()
{
int Points;
cout << "Starting in five seconds\n";
_sleep(5000);
Points = act();
for (;;) //inf loop
{
int ph;
cout << "Press 1 to continue or anything else to stop\n";
cin >> ph;
if (ph == 1)
{
Points += act();
}
else
{
break;
}
}
cout << "You have earned a total of " << Points << " great job!";
_sleep(5000); //time to read the last text
return 0;
}
/* To do list:
*Convert to arduino
*Make timer work in background of of table
*Check if words in the table (for differant players) are the same and give points accordingly
*Check if words are actual words (connect an online dictonary?)
*Make interface? (if possible and I have time to learn how)
*Think of what to do with Hardwear
*Comment rest of the code
*/
For using Sleep() function you need
#include <windows.h>