hi im new to c++ so i apologize for any stupidly obvious mistakes. im trying count the amount of times a certain number appears in an array ive had a go from what ive seen in other posts but i dont think im even close heres the code so far:
#include <iostream>
using namespace std;
int main()
{
int mark, i;
int count = 0;
int numbers[14]={0,1,2,3,4,5,6,4,4,7,7,7,8,8};
cout<<"please enter the mark you need to count";
cin>> mark;
for (i = 0; i < count++;)
{
if (numbers[i] = mark)
{
++i;
}
1. Your for loop should loop from i = 0 to i = 14, not count, because your count is 0 so the for loop is not working.
It should be for(int i=0;i<14;++i)
2. should be '==' instead of '=' for comparison instead of assignment
3. use count++ instead of ++i.
your code means you check the 3rd element and jumped 2nd element if your 1st element is same as your input, not counting the occurence.
if (numbers[i] = mark)
should be if (numbers[i] == mark)
because the
=
operator means that you asign that value to numbers[i] and then if numbers[i] is equal with 0 the if statement will return false otherwise it will return true and the
for (i = 0; i <14; i++);
should be for (i = 0; i <14; i++)
remove the ';' because now it increases 'i' 14 times and then it checks the if statement 1 time
in the future instead of declaring 'i' in the beginning simply use for (int i = 0; i <14; i++) so it's best performance and you avoid these bugs
there's a run-time error now which says the variable 'i' is being used without being initialized. and there are errors when i remove any semi colons.
heres the code ive got now:
#include <iostream>
using namespace std;
int main()
{
int mark,i ;
int count = 0;
int numbers[14]={0,1,2,3,4,5,6,4,4,7,7,7,8,8};
cout<<"please enter the mark you need to count\n";
cin>> mark;
for (int i = 0; i <14; i++);
{
if (numbers[i] == mark)
{
count++;
}