Monday, May 24, 2010

Very Basic C++ Question About Float!?

I've just started a C++ class and we have to write a program that asks for 5 grades from the user and then calculates the average. I almost have the whole thing down and it compiles and runs smoothly, but then my teacher reminded us that the answers could turn out to be decimals, of course. I know that float is used for decimals but we haven't done any examples with this type of variable. I'm guessing that I'll just have to do something in this section:





#include%26lt;iostream%26gt;


using namespace std;





int main ()


{


string username;


int grade1;


int grade2;


int grade3;


int grade4;


int grade5;


int avg = 0;


int sum = 0;





Thanks in advance!

Very Basic C++ Question About Float!?
in above programs or hints do a s\mall change that is


avg=float(sum)/5.0;


or


avg=float(grade1+grade2+grade3+grade4+...
Reply:not sure about c++, but try to do this





float avg = 0.0;





sum = grade1 + grade2 + grade3 + grade4 + grade5 ;


avg = sum / 5.0 ;





note the last line is over 5.0 not over 5, since i think over 5 will just round the actual average before assigning it to avg
Reply:Ok. floats are just like ints but can do decimals. So just change your average variable into a float like this:





float avg = 0;





That's it!
Reply:A float is used to store a value corresponding to a single-precision real number ( a decimal number ). Since you are trying to calculate the average, you have to change the line:





int avg = 0;





to





float avg = 0.0;





Then you can calculate the average using:





avg = (grade1 + grade2 + grade3 + grade4 + grade5)/(5.0);





or, if you prefer: avg = sum/(5.0);





I hope this helps you.


C++ string question?

OK! Just to let everyone know...this project has already been turned in--I just need to know what I could've done to make the program take str2 as a string of characters and erase all of them. I could not get the for loop to keep searching/ finding anything past the first occurrence. I need to know for a coming final in c++ in 2 weeks. thanks





#include%26lt;iostream%26gt;





#include%26lt;string%26gt;





using namespace std;





int main()





{





string str1, str2, ans;





do{





cout%26lt;%26lt;"Please enter a string (40 characters max)--%26gt;"%26lt;%26lt;endl;


getline(cin, str1);





cout%26lt;%26lt;"Please enter the characters to be removed(20 characters max) --%26gt;"%26lt;%26lt;endl;


getline(cin, str2);





for(int i=0; i%26lt;=40; i++);


{





string::size_type loc=str1.find(str2, 0);


(loc!=string::npos);


{


str1.erase(loc, +1);





cout%26lt;%26lt;"First string with characters removed --%26gt;"%26lt;%26lt;str1%26lt;%26lt;endl;





}


}








cout%26lt;%26lt;"Would you like to do another(y or n)?"%26lt;%26lt;endl;


getline(cin, ans);


}


while(ans[0]=='y'||ans[0]=='Y');


return 0;


}

C++ string question?
One reason your 'for' loop doesn't work is the semi-colon at the end of it:


for(int i=0; i%26lt;=40; i++);





Another problem is this statement, that looks like you wanted it to be an 'if' statement:


(loc!=string::npos);





Your compiler should have told you this statement has no effect.





Even with that, there are problems with the code. There is no need to hardcode 40 in your for loop, or prompt for a max of 40 or 20 characters. Also, with this: str1.erase(loc, +1) you'll only erase str2 if its length is 1. Also, to be more efficient, you don't need to repeatedly start your search at str1[0].





So, implementing all those suggestions, my improved version of your code looks like this:





int main(int argc, char *argv[]) {


string str1, str2, ans;


string::size_type loc = 0;





do {


cout%26lt;%26lt;"Please enter a string --%26gt; ";


getline(cin, str1);


cout%26lt;%26lt;"Please enter the characters to be removed --%26gt; ";


getline(cin, str2);


do {


if ((loc = str1.find(str2, loc)) != string::npos) {


str1.erase(loc, str2.length());


cout %26lt;%26lt; "First string with characters removed --%26gt;" %26lt;%26lt; str1 %26lt;%26lt; endl;


}


} while (loc != string::npos);


cout %26lt;%26lt; "Would you like to do another(y or n)?";


getline(cin, ans);


} while (ans[0]=='y' || ans[0]=='Y');


return 0;


}





One other thing I might do for a production version of the program would be to move the 'cout' outside of the 'for' loop, so you just display the final result. As it is, though, it's nice to watch the progress as occurrences of str2 are removed.





EDIT: it just occurred to me that str2 probably isn't a substring to be removed, but a list of characters to be removed. If so, you were missing something for this as well. Check out the code below. I think this is the solution you're looking for:





int main(int argc, char *argv[]) {


string str1, str2, ans;


string::size_type loc = 0;





do {


cout%26lt;%26lt;"Please enter a string --%26gt; ";


getline(cin, str1);


cout%26lt;%26lt;"Please enter the characters to be removed --%26gt; ";


getline(cin, str2);


if ((str1.length() %26gt; 0) %26amp;%26amp; (str2.length() %26gt; 0)) {


do {


while ((loc = str1.find(str2[0], 0)) != string::npos) {


str1.erase(loc, 1);


}


str2.erase(0,1);


} while (str2.length() %26gt; 0);


cout %26lt;%26lt; "First string with characters removed --%26gt;" %26lt;%26lt; str1 %26lt;%26lt; endl;


}


cout %26lt;%26lt; "Would you like to do another(y or n)?";


getline(cin, ans);


} while (ans[0]=='y' || ans[0]=='Y');


return 0;


}

geranium

C++ run-time failure. please help?

I got this message using visual studi c++:


Run-Time Check Failure #2 - Stack around the variable 'temp' was corrupted.





here is my function:


void highscore(int score)


{


int indexes=0,temp[5];


ifstream infile;


infile.open("filesout.txt");


if (infile.is_open())


{


while (!infile.eof())


{


infile%26gt;%26gt;temp[indexes++];


}


}


else


cerr %26lt;%26lt;"error occured when opening file";


infile. close();





int a=1,k=0,s;


temp[5]=score;


while (k%26lt;6)


{


for (int m=a;m%26lt;6;m++)


{


if (temp[m]%26gt;temp[k])


{


s=temp[k];


temp[k]=temp[m];


temp[m]=s;


}


}


k=k+1;


a=a+1;


}


for (int y=0;y%26lt;5;y++)


cout %26lt;%26lt;temp[y]%26lt;%26lt; endl;





ofstream outfile;


outfile.open("filesout.txt");


for (int x=0;x%26lt;6;x++)


outfile %26lt;%26lt;temp[x]%26lt;%26lt;endl;


outfile.close();


}





what the function do is put the input extracted from a file "filesout.txt" and reorder from highest to lowest


can anyone check the error please. thank you

C++ run-time failure. please help?
One obvious error is the dimension on temp and the loop variables. Note how your dimension on temp is 5; however, you specifically reference temp[5] in your "for(int m=a" loop. All references into your temp array should only be 0 to 4 with a dimension of 5.





i.e. any reference to "var%26lt;6" then "temp[var]" will throw an error.


C++ Leap Year Program with error C2659: '=' : function as left operand problem?

Okay here is my program, it has only two compiles errors: C2659: '=' : function as left operand. I'm new to C++ and get confused by this error, can anyone correct my program? Thanks. Here is the program:





#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;





using namespace std;





int getYear();


bool isLeap(int year);


char moreData();





int main()


{


int year;


char carryOn='y';





while(carryOn=='y'||carryOn=='Y'){


year=getYear();





if(isLeap(year)){


cout%26lt;%26lt;" is a leap year\n";


}else{


cout%26lt;%26lt;" is not a leap year\n";


}


carryOn=moreData();


}


system("pause");


}


int getYear(){


int year;


cout%26lt;%26lt;"Enter a year: ";


cin%26gt;%26gt;year;


return year;


}


bool isLeap(int year){


if(year%4==0){


if (year%100!=0){


isLeap=true;


}else if (year%400==0){


isLeap=true;


}


//return isLeap;


}}


char moreData(){


char carryOn;


cout%26lt;%26lt;"Do you want to enter more data? (y/n) ";


return carryOn;


}

C++ Leap Year Program with error C2659: '=' : function as left operand problem?
in your isLeap() function.. you are assigning isLeap=true.... which cannot be done.. because isLeap is the pointer to the function isLeap().. dont worry if you dont understand that..... But you can use the statement


return (true);


instead of


isLeap=true;


and use the statement


return(false);


at the end of the isLeap function just before the closing flower brace.. that will make the program work...
Reply:I think your





isLeap=true;





statements need to be





return true;





instead!


Reading text files in C++?

How can you read text and integers from a file in C++ and store them as strings and varibles for use in the program. The text file formated like string, string, string, int, int, int, int over serveral lines like below.





Word1 Word2 Word3 Int Int Int


Word1 Word2 Word3 Int Int Int





and so on...

Reading text files in C++?
fscanf()? http://www.cplusplus.com/reference/clibr...


HELP ME (C++!!), PROGRAM INSIDE!!?

#include%26lt;iostream%26gt;


int main()


using namespace std;


{


int x=12;


cout%26lt;%26lt;hex%26lt;%26lt;x;


return 0;


}


__________________________________


The result is "C", but i need it to display "00000C", i thought of doing it with IF statements and other variables, but that would slow down the program...

HELP ME (C++!!), PROGRAM INSIDE!!?
cout %26lt;%26lt; setfill ('0') %26lt;%26lt; setw (6);


cout %26lt;%26lt; hex %26lt;%26lt; 12 %26lt;%26lt; endl;





I'm not an expert on cout

sweet pea

Can someone please help me with some C++ (programming) questions?

24. In testing code having an if or an if-else clause, describe how to construct test data. Give an example based on:





if (x %26gt; y)


statement1;


else


if (u %26gt; v)


statement2;


else


statement3;





25. Answer the question at the end of this code.





const int x = 1.23456789;


int f(int y)


{


int z;


//body of function: int f(int)


}


const int w = 9.987654321;


int g(double u)


{


int v;


// body of function: int g(double)


}


int main ()


{


int m;


double nn;


// body of function main()


m = g(nn);


// ...


m = f(x);


return 0;


}





In which functions can each variable be accessed?





a)x e) w


b)f f) g


c)y h) v


d)z i) m


j)nn





26. Why not make all variables non-constant global variables, and avoid the bother of parameters for functions?





27. Describe the similarity and difference between a function's parameters and function's local variables.

Can someone please help me with some C++ (programming) questions?
Do we get to share your class grade too? You at least should try to answerthem and then ask if your answers make sense.


How can I convert this program(in c++) to Prolog (winprolog or ..) ?

I've written the program in c++ but I can't convert it to Prolog .


main()


{


int x,y,bound;


cout%26lt;%26lt; "Enter 2 num to find the path";


cin %26gt;%26gt;x;


cin%26lt;%26lt; y;


bound=y-x;


while ( bound!=0)


{


if (bound%26gt;=100)


{


x+=100;


cout %26lt;%26lt; "----%26gt; + 100" %26lt;%26lt;x;


bound=y-x;


}


else if (bound%26gt;=10)


{


//like actions in previous if


}


else if (bound%26gt;=1)


{


//like actions in previous if


}


else if(bound%26lt;=-100)


{


x-=100;


bound=y-x;


}


....


}


ofcourse it is not the complete code .


I 'm new in prolog


especialy I want to know how can I use while loop , in prolog.


please help me !


thanks in advance.

How can I convert this program(in c++) to Prolog (winprolog or ..) ?
Why are you using Prolog? Taking an AI class or something?


HELP!! Lost on homework C++ (dogsafire)?

dogsafire,


I haven't got far. We just got this and didn't get much info. I am in a C++ programing class and the teacher just reads from power point. Last semester only two people passed, now I see why.


I have the highest score in the class and stll don't know what the heck I am doing till we are about 3 weeks past it.





This is our first assn in arrays, we are using Walter Savitch's 6th Edition. I am just trying to get started on this prob. I am having a hard time understanding how to translate the prob into:


const int MAX = 10;


void outputA (int a[], int size);


int main () {


int a[MAX];


int i;


int x;


for (i=0;i%26lt;MAX;i++)


a[i]=0;


cout %26lt;%26lt; "Input grades ending with -1 "; // Has to be an int for this situation like(-1)


cin %26gt;%26gt; x;


i = 0;


while (x%26gt;=0 %26amp;%26amp; i%26lt;MAX){


a[i] = x;


i++;


cout %26lt;%26lt; "next: ";


cin %26gt;%26gt; x;}


for (i=0;i%26lt;MAX;i++)


cout %26lt;%26lt; a[i] %26lt;%26lt; endl;return 0;


outputA(a,i);


}


void outputA (int a[], int size){


int i;


for (i=0;i%26lt;size;i++)


cout %26lt;%26lt; a[i] %26lt;%26lt; endl;


}

HELP!! Lost on homework C++ (dogsafire)?
If you are still stuck with your homework may be you can post it at homework help website like http://homeworkhelp.co.in/ .
Reply:Your code isn't bad, you don't appear to be lost. My comments are inlined below. Is there something in particular you're confused about?





const int MAX = 10;





// void outputA (int a[], int size);


// recommend const pointer, const data for int[] arg


void outputA(const int * const, int);





int main () {


int a[MAX] = {0}; // see comment below


int i;


int x;





#if 0


for (i=0;i%26lt;MAX;i++) // don't need this...


a[i]=0; // init on declaration (above)


#endif





cout %26lt;%26lt; "Input grades ending with -1: ";


cin %26gt;%26gt; x;


i = 0;


#if 0


while (x%26gt;=0 %26amp;%26amp; i%26lt;MAX){


a[i] = x;


i++;


cout %26lt;%26lt; "next: ";


cin %26gt;%26gt; x;


}


#else


// do something like this so you don't


// get the prompt for grade MAX+1


while (x %26gt;= 0) {


a[i++] = x;


if (i == MAX) break;


cout %26lt;%26lt; "next: ";


cin %26gt;%26gt; x;


}


#endif





#if 0


for (i=0;i%26lt;MAX;i++) // after this loop i=10, so


cout %26lt;%26lt; a[i] %26lt;%26lt; endl; // the call to outputA will


// return 0; ??? // print it all again


#endif





outputA(a,i);


}





// void outputA (int a[], int size){


void outputA(const int * const a, int size){


int i;


for (i=0;i%26lt;size;i++)


cout %26lt;%26lt; a[i] %26lt;%26lt; endl;


}


How to find "limits.h" header file exists in turbo c or not?i want to use "showbits" fn in c pgm.

Here is the c pgm:


#include%26lt;stdio.h%26gt;


#include%26lt;limits.h%26gt;


void main()


{


int i=128;


showbits(i);


getch();


}





"when i compile this pgm, i didn't get any error. but when i tried to run i get this error " undefined symbol showbits". plz give me a solution.thanks in advance.

How to find "limits.h" header file exists in turbo c or not?i want to use "showbits" fn in c pgm.
header work perfectly but wats showbits() function is it being use corre3ctly check that
Reply:no compiler error usually == headers are OK.





I don's see anything called showbits in the limits.h. What are you trying to do here with this code?
Reply:Go to folder where your C or C++ is installed. Then go to TC folder. In that go to HEADER folder. There you should find it.





If its there then in your TC.exe file set the appropriate directory path.





I hope I answered your query successfully...

rose

C++ Error message?

Thanks for your previous answers. They've been eye-openers. I have a quick question. The program is to read from a file containing codes for vehicle types(perform the necessary conversions) and use the weights to perform calculations(multiplying by the user-entered tax values). Each line of the file contains the code and the weight. The weights should be integer values between 100 and 99000. Here's my input file








c 4000


t 20500


5 9000


m 500


b 10550


c 2500.8








I have a slight problem displaying the error message when a non-int value is encountered. I have tried several things with little success....Here is my output..











Enter the tax rate for MOTORCYCLES(0.01-0.99)


.25


Enter the tax rate for CARS(0.01-0.99)


45


Warning: entry invalid, rate must be between 0.01 and 0.99


Enter the tax rate for CARS(0.01-0.99)


.14


Enter the tax rate for BUSES(0.01-0.99)


89


Warning: entry invalid, rate must be between 0.01 and 0.99


Enter the tax rate for BUSES(0.01-0.99)


.28


Enter the tax rate for TRUCKS(0.01-0.99)


.26


ROAD TAX REPORT


Vehicle Type: Weight: Rate: Tax Due:





CAR 4000 0.14 560.00


TRUCK 20500 0.26 5330.00


5 9000 Error:Invalid Vehicle Code


MOTORCYCLE 500 0.25 125.00


BUS 10550 0.28 2954.00


CAR 2500 0.14 350.00


. 8 Error:Invalid Vehicle Code





It's made up of four columns(neatly arranged). As you can see, everything runs fine except for the last line. The desired output on the last row would be:


CAR 2500.8 Error: Invalid weight(non-integer)











Here is my program:














//Sample program to read input file and perform calculations with interactive values.


//Print out a table with input and calculated values.


#include%26lt;iostream%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;


#include%26lt;cstring%26gt;


using namespace std;








void GetRates(float%26amp;, float%26amp;, float%26amp;, float%26amp;);





enum Vehicles{ERROR,MOTORCYCLE, CAR, BUS, TRUCK};











int main()





{


float cycleRate;


float carRate;


float busRate;


float truckRate;


char code;


int weight;


ifstream inFile;


Vehicles typeCode;














inFile.open("file1.dat");


if(!inFile)


{


cout%26lt;%26lt;"Unable to open input file, program abnormally ended"%26lt;%26lt;endl;


return 1;


}


GetRates(cycleRate, carRate, busRate, truckRate);


cout%26lt;%26lt;setw(40)%26lt;%26lt;" ROAD TAX REPORT"%26lt;%26lt;endl;


cout%26lt;%26lt;setw(2)%26lt;%26lt;"Vehicle Type:"%26lt;%26lt;setw(15)%26lt;%26lt;" Weight:"%26lt;%26lt;setw(15)%26lt;%26lt;" Rate:"%26lt;%26lt;setw(20)%26lt;%26lt;" Tax Due:"%26lt;%26lt;endl%26lt;%26lt;endl;





inFile%26gt;%26gt;code%26gt;%26gt;weight;


while(inFile)


{


{


if(!inFile)


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;... Error:Invalid weight(non-integer)"%26lt;%26lt;endl; "Error: invalid weight(non-integer)";


}


{


if(code=='m')


typeCode=MOTORCYCLE;


else if(code=='c')


typeCode=CAR;


else if(code=='b')


typeCode=BUS;


else if(code=='t')


typeCode=TRUCK;


else


typeCode=ERROR;





}








switch(typeCode)


{


case MOTORCYCLE:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setpr...


break;


case CAR:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision...


break;


case BUS:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision...


break;


case TRUCK:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecisi...


break;


case ERROR:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecisi... Error:Invalid Vehicle Code"%26lt;%26lt;endl;





}








inFile%26gt;%26gt;code%26gt;%26gt;weight;





}





cout%26lt;%26lt;endl;


cout%26lt;%26lt;"End of Report"%26lt;%26lt;endl;


return 0;


}























void GetRates(/*out*/ float%26amp; motorcycleRate,


/*out*/ float%26amp; carsRate,


/*out*/ float%26amp; busesRate,


/*out*/ float%26amp; trucksRate)


{








bool invalidData;


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for MOTORCYCLES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;motorcycleRate;





{





if(0.009%26lt;=motorcycleRate%26amp;%26amp;motorcycleRate...


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for CARS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;carsRate;


{


if(0.009%26lt;=carsRate%26amp;%26amp;carsRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for BUSES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;busesRate;


{





if(0.009%26lt;=busesRate%26amp;%26amp;busesRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for TRUCKS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;trucksRate;


{





if(0.009%26lt;=trucksRate%26amp;%26amp;trucksRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}








}





}














THANKS for your time!!

C++ Error message?
Your program is working fine, it is doing exactly what you want it to do.





The problem is that you are asking it to do the wrong thing.





The line with the problem is your input line.


inFile%26gt;%26gt;code%26gt;%26gt;weight





inFile knows that weight is a declared integer, so it is only reading an integer - that is, up to the decimal place. It is then processing that input.





When it returns again, it reads the ".8" as the code variable and returning the TypeCode Error.





You need to rethink the input statement in two ways: (1) you don't want to tell the input stream that it "weight" an integer, because that is all it will get; and (2) you want to check how code gets input so it only reads in one character.





I am not going to solve it for you - but that is where the problem is.
Reply:too long still thanks for the two points
Reply:I can't tell you what isn't working, but I can point out a prolem that may help you find it. When programming a structured or procedural (same thing, different names) program in any language one of the main goals is to make the code clear, readable, compact and well documented. I'm not able to see what delineations you've made between functions, count the functions or even trace the code effectively at this point. Do yourself a favor, take a break, relax and then look at the code you've written again and clean it up. You'll likely find your own problem in the clean up effort. It'll likely be a forehead smacker.


Help with C++ code.?

can any1 help me figure the code out to this question?


I'm stuck. Make it in c++.





The Question:


Write a function allValid that takes an array of integer grades and the size of the array as parameters. The function returns the index of the first value that is negative or over 100. If this is not true of any of the values, they are all valid, and the function returns the size of the array.


Write a driver to test this function. A driver in this context is code that controls other code. A test driver is a main() that calls the other code to test if it produces the correct result.





My code so far:


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





void allValid(int, int);





int main()


{


int grades[] = {100, 90, 85, 76, 71};


const int DATA_SIZE = 5;





for(int x = 0; x %26lt; DATA_SIZE; x++)


}


void allValid(int grades[], int size[])


{


for(int x = 0; x %26lt; 0 %26amp;%26amp; x %26gt; 100; x = invalid)


if(x %26gt;= 0 || x %26lt;= 100);


}





Please try to help.





Thanks in advance.

Help with C++ code.?
You have a number of problems:





1. You never call your allValid subroutine in main().





2. You don't understand the for(;;) construct. Until you get some more experience with it, limit yourself the the vanilla :


for(%26lt;initialize the loop counter%26gt;; %26lt;condition necessary to do another pass%26gt;, %26lt;increment counter%26gt;)





3. A for statement executes the next statement after the for.


If you have multiple lines of code, you need to make a compound statement by enclosing those lines in braces.


If fact get in the habit of using braces every time you write a for, while or do-while loop. It makes it more obvious to code readers what is going on.


Braces are inexpensive. I usually buy them in bulk lots of 50kg.





4. You can't return a value if the return value of your subroutine is void. Actually you can, but that's beyond what you're attempting to do here.





5. Most programmers reserve i,j,k,l,m,n for loop counters. It's something that goes back to the days of FORTRAN





6. It's a good practice to start your loops at 0 and set the cut off at N where N is the size of your array. That way your counter will always be a valid index into the array.





Here is what I came up with:








#include %26lt;iostream%26gt;


#include %26lt;string%26gt;








int allValid(int[], int);





int main()


{


int grades[] = {100, 90, 85, 76, 71};


const int DATA_SIZE = 5;





int returnValue = allValid(grades, DATA_SIZE);





return 0;


}











int allValid(int grades[], int size)


{


for(int i = 0; i %26lt; size; i++)


{


if(grades[i] %26lt; 0 || 100 %26lt; grades[i])


{


return grades[i];


}


}





//Fall through if all are OK





return size;





}








One other thing you can do:





const int DATA_SIZE = sizeof(grades)/sizeof(int);





That way if you add to the array of grades, you don't have to count them to get DATA_SIZE.





sizeof(grades) gives you the number of bytes in the array grades[], sizeof(int) gives you the number of bytes in int.


They are computed by the compiler so they can be used to set the value of a const variable.


Can anyone convert the below c program to c++ program or just tell how to find the biggest no among the n no?

#include%26lt;stdio.h%26gt;


int max(int[],int,int);


main()


{


int a[100],i,n,temp,big;


clrscr();


printf("enter how many numbers:");


scanf("%d",%26amp;n);


printf("enter the element");


for(i=0;i%26lt;n;i++)


scanf("%d",%26amp;a[i]);


big=a[0];


printf("the biggest no is",biggest(a,n,big));


getch


}


int max(int a[],int n,int big)


{


if(n==0)


return big;


else


n--;


if(a[n]%26gt;big)


big=a[n];


return (max(a,n,big));


}


reply soon only in c++ program. Thank u

Can anyone convert the below c program to c++ program or just tell how to find the biggest no among the n no?
Save as your file with extension CPP and replace header file stdio.h with iostream.h and also add conio.h for clrscr() and getch().





now replace all scanf() with cin%26gt;%26gt;num and you have no need to specify format characters(%d or %c) and also printf () with cout%26lt;%26lt; num without any format specfiers..
Reply:replace stdio by iostream in header


replace scanf("%d",%26amp;n) by cin%26gt;%26gt;n and so on


replace printf("...................",d,g,h) by cout%26lt;%26lt;".........."%26lt;%26lt;d%26lt;%26lt;g%26lt;%26lt;h; and so on


it will work
Reply:that also works in C++ no need to convert except for the libraries i think getch() is in stdlib.h and also use cin and cout instead of printf and scanf in the ipstream.h
Reply:This sounds like homework. What is the class?


HELP!! Lost on ......C++ (dogsafire)?

dogsafire,


I haven't got far. We just got this and didn't get much info. I am in a C++ programing class and the teacher just reads from power point. Last semester only two people passed, now I see why.


I have the highest score in the class and stll don't know what the heck I am doing till we are about 3 weeks past it.





This is our first assn in arrays, we are using Walter Savitch's 6th Edition. I am just trying to get started on this prob. I am having a hard time understanding how to translate the prob into:


const int MAX = 10;


void outputA (int a[], int size);


int main () {


int a[MAX];


int i;


int x;


for (i=0;i%26lt;MAX;i++)


a[i]=0;


cout %26lt;%26lt; "Input grades ending with -1 "; // Has to be an int for this situation like(-1)


cin %26gt;%26gt; x;


i = 0;


while (x%26gt;=0 %26amp;%26amp; i%26lt;MAX){


a[i] = x;


i++;


cout %26lt;%26lt; "next: ";


cin %26gt;%26gt; x;}


for (i=0;i%26lt;MAX;i++)


cout %26lt;%26lt; a[i] %26lt;%26lt; endl;return 0;


outputA(a,i);


}


void outputA (int a[], int size){


int i;


for (i=0;i%26lt;size;i++)


cout %26lt;%26lt; a[i] %26lt;%26lt; endl;


}

HELP!! Lost on ......C++ (dogsafire)?
wat the heck is that?

flowering plum

How to use variant tyeps in c++ ?

hi there


how can i use variant types in c++ as a function argument?





for example foo(variant x){


....





}





int a;


foo (a);


float b;





foo(b)

How to use variant tyeps in c++ ?
A template function will do what you want. Here's a simple example:





#include %26lt;iostream%26gt;





using namespace std;





template %26lt;typename T%26gt;


void foo(T x) {


cout %26lt;%26lt; x %26lt;%26lt; endl;


}





int main(int argc, char *argv[]) {


int i = 1;


float f = 2.2;





foo%26lt;int%26gt;(i);


foo%26lt;float%26gt;(f);


return 0;


}


Using pointers in data structures in C?

If I create a data structure (in C) with a pointer in it, then a pointer of that structure's type:





struct data {


int a;


int *ptr;


}





struct data *info;





How do I initialize that pointer? Specifically, I'm trying to use malloc to allocate storage space for the pointer to point to.





I tried all of these:


info.*ptr = (int *)malloc(sizeof(int)*4);


*info.*ptr = (int *)malloc(sizeof(int)*4);


info.ptr = (int *)malloc(sizeof(int)*4);


*info.ptr = (int *)malloc(sizeof(int)*4);





But nothing seems to work. What am I doing wrong?

Using pointers in data structures in C?
Since you declared info as a pointer you first need to allocate the memory for that object with:





info=(struct data *)malloc(sizeof(data));





then





info-%26gt;ptr=(int*)malloc(sizeof(int)*4);





This will basically create an array in ptr that can be referenced with info-%26gt;ptr[0], info-%26gt;ptr[1], etc.





Make sure you free both sets of allocated memory when you are done with it.





Note that (*info).ptr will also work to reference that item.


Question in C?

Program keeps crashing any suggestions????





int craps()


{


int roll = pairOfDice();


int flag = 0;


int bet;


char count;


int dummy;








//prompt user for bet


printf("How many chips would you like to bet?");


scanf("%d", %26amp;bet);


printf("\n");





if(bet %26lt; getChips())// player has enough chips?


{


if(bet != 0)


{


setChips(getChips() - bet);


}


}











printf("Press 'r' and hit enter for your first roll.\n");


scanf("%d%c", dummy, count);





if(count = 'r')


{


printf("You rolled a %d. \n", roll);


if(roll == 7)


return 1;


else if(roll == 11)


return 1;


else


k +=roll; // adds roll to counter


}














while(flag == 0)


{





int count1 = 0;


printf("Press 'r' and hit enter for your first roll.\n");


scanf("%c", count1);


if(count1 == 1)


{


roll = pairOfDice();


printf("You r

Question in C?
This line,





scanf("%d%c", dummy, count);





change to


count = getchar();


flush(stdin);





Anywhere you need a single character input


use getchar() with fflush(stdin) after it to remove excess input.


getchar() requires the user to press enter after input.


Alternatively, if you include conio.h


getch() will get your user input. This function will return any key pressed by user. If user presses function keys and arrow keys, getch() will return 0 then scan code on next call.
Reply:scanf("%d%c", dummy, count); would cause the problem.





scanf("%d%c", %26amp;dummy, %26amp;count); will stop crash, but it won't fix the program.





You must pass the address of the integer or address of the character to the scanf function if you expect scanf to be able to change the value of the integer or character.
Reply:hmm, is this your homework...


C coding...wats wrong with this Code... regarding inline function?

C coding...


I heard that C99 standard support inline functions in C...


But the following code is not getting compiled...


wats wrong with this...


plz someone help





#include %26lt;stdio.h%26gt;





inline int func(int i);





int main()


{


int i=5;





printf("\nBefore inline func...");





func(i);





printf("\nAfter inline func...\n\n");





return 0;


}





inline int func(int i)


{


printf("\nIn inline function...");





return i;


}

C coding...wats wrong with this Code... regarding inline function?
what compiler are you using, and what is the compiler error message?





if you're using a microsoft compiler you need to use the new style: __inline





also, make func() return void instead of int, since you aren't using the return value.

nil

What are the problems with these C++ (cpp) codes?

I am new to C++ (migrate from Java). I am asked to say what is the problem with these pieces of code?





Q:





struct MyStruct


{


int *p;


MyStruct(int n) { p = new int; *p = n; }


~MyStruct() { delete p; }


};





--------------------------------------...


Q:





int *array(int n)


{


return new int(n);


}





int main()


{


int *p = array(10);


for( int i = 0; i %26lt; 10; i++ )


{


p[i] = 0;


}


printf( "%d\n", p[0] );


p = array(10);


printf( "%d\n", p[0] );


return 0;


}








--------------------------------------...


Q:








class A { public: int a, b; };


class B


{


public:


const A a;


B() :a() { }


};





int main()


{


B b;


printf( "%d %d\n", b.a.a, b.a.b );


return 0;


}





Is there a C++ guru that can help?





Thanks

What are the problems with these C++ (cpp) codes?
First:








struct MyStruct


{


int *p;


MyStruct(int n) { p = new int; *p = n; }


~MyStruct() { delete p; }


};


Nothing wrong here, far as I can tell...





An initializer like:


MyStruct bob(4);


ought to work just fine.


When bob goes out of scope, it ought to de-allocate the byte for *p.





Compiles fine.





As for the second:





int *array(int n)


{


return new int(n);


}





int main()


{


int *p = array(10);


for( int i = 0; i %26lt; 10; i++ )


{


p[i] = 0;


}


printf( "%d\n", p[0] );


p = array(10);


printf( "%d\n", p[0] );


return 0;


}





Here's the deal. The


new operator in the array function is declared locally to the array function. As soon as we hit the }, the array will go out of scope and be de-allocated immediately. You're going to be writing to an indeterminate location in memory subsequent to the array() call.


Better to just call the new operator in the same scope as where you're going to be using it, or declare your array() as a macro.








As for the third:





What the heck are you trying to do here?








As for the previous answerer who brought into question the difference between C and c++, I gotta say: "Every C program IS a c++ program!"


C++ is an extension to c.


C is C++!





Question: What is the difference between:


class bob


{


public:


int b;


};


and


struct bob


{


int b;


};


??





NOTHING! A struct is just a class that defaults to public.


Try it.


class just defaults to private.





---EDIT---


structs %26gt;%26gt;can%26lt;%26lt; have methods in c++
Reply:Q1,





structs don't have methods. Well, not that I know of.





Q2.





If I'm correct, the call was made to the array function which returned an int, not an integer array. Hence you can't loop through it.





Q3.





I dunno what this is. B() :a() { }


Also, there weren't any values assigned to "a", "b".





b declared by class B is still null.


a declared by const A is still null.


C++ problem?

I wrote this program, it does successfully compile but when running it hangs. and i think the prob must be something like wrong use of function.





#include %26lt;stdio.h%26gt;


#include %26lt;iostream%26gt;





void sp_to_dash(char *str);


char s;


int main(void){


printf("Please Enter a expression: \n");


scanf("%c",s);


sp_to_dash("s");


system("pause");


}


void sp_to_dash(char *str){


while (*str)


{


if (*str==' ') printf("%c",'_');


else printf("%c",*str);


str++;


}


}

C++ problem?
sp_to_dash("s");





You are passing the literal value string "S" to the function, BTW... probably not your intention. try sp_to_dash(s).





also, you really don't have anything to terminate your loop. Especially when sending in a literal. The program will just happily keep skipping through memory until it randomly and accidentally runs into a NULL somewhere.





You need to fix the parameter pass as well as add code to make sure that your input string is ALWAYS null terminated...or else check for the str = length of str also in your loop control.
Reply:"s" is defined as a single character, so when you go into the sp_to_dash() routine, you send the address of "s". then you do something then increment the pointer. the problem is the next address location is just garbage because you are only dealing with 1 character. also the line" while(*str) seems to me to be an infinite loop.
Reply:while (*str)





This condition may never be false if str is not null-terminated.
Reply:Why are you passing "s" to your function? Shouldn't you be passing your string you just got from scanf?


C++ fractal program?

This is supposed to be a C++ program that is for (8,0). It prints out the fractal using *'s. Why isn't it working? This is what I have so far:





#include %26lt;iostream%26gt;


#include %26lt;cmath%26gt;


using namespace::std;





using std::cout;





void pattern(int nstars, int startcol);





int main()


{





const int nstars = 8;


int startcol = 0;


pattern (nstars - 32, startcol);


for (int i = 0; i %26lt;= startcol; i ++)


{


cout %26lt;%26lt; " ";


}


for (int j = 0; j %26lt;= nstars; j++)


{


cout %26lt;%26lt; "* ";


}


cout %26lt;%26lt; endl;





}





void pattern (int nstars, int startcol)


{


if(nstars != 0);


}








Please Help!

C++ fractal program?
Look at the code for your pattern function. It doesn't do anything.





You've got for loops elsewhere that look like they should be inside of the pattern function. Why not try moving them, and see if you have better luck.





I suspect you've written too much code at once. Why not start over, and build the code up one step at a time. For example, can you write a version of pattern() that just prints n stars, where n is a function parameter? Once you've done this, it should be easy to expand the code to solve the complete problem.


C# Questions - Please Help ASAP!?

i am having some difficulty with these C# questions! i will give you the questions and 4 possible answers, please can you provide me with the correct answer and please explain how you got that answer.... thanks in advance





1. What does the following algorithm produce when n is 3?


set sum to 10.


set i to 1.


input n.


while i is less than or equal to n do


{


take i from sum.


increment i.


}


output sum.





a. 9


b. 7


c. 4


d. 1





2. What would be output by the following section of code ?


int A[4] = {1 , 2, 3, 4};


int i;


for (i=0; i%26lt;4; i++)


{


A[i] = A[i] + A[i];


}





Console.WriteLine (A[i] );





a. 4


b. 0


c. 8


d. 6





3. Given the following method (you may assume it has all compiled correctly so there are no syntax errors), what will be output?





public static void printloop()


{


int i;


for (i=1; i%26lt;9; i++) ;


if (i%2 = = 0) ;


Console.WriteLine (i + " ");


}





a. 2 4 6 8


b. 8


c. Nothing is output.


d. 2 4 6

C# Questions - Please Help ASAP!?
First problem the answer is 4.


Second problem the answer is 8


Third problem the answer is 2, 4, 6, 8.





Why?





1st Problem:





sum 10


i 1


n 3





while i%26lt;=n


{


sum = sum -1


}


output sum





10 - 6 = 4, thats the output of sum





Second problem:





You end up having the value of 4+4 which is 8.





And for the last problem, the only numbers that will give you %2==0 are 2, 4, 6, 8

sp

C program based on AI reasoning for Bioinformatics data processing?

I am getting the error below when i try to compile my source file in C using visual c++ 2008





------ Build started: Project: Biodata_main, Configuration: Debug Win32 ------


Compiling...


Biodata_main.c


d:\documents and settings\olawale\my documents\visual studio 2008\projects\biodata\biodata_main.c(131... : error C2065: '__argc' : undeclared identifier


d:\documents and settings\olawale\my documents\visual studio 2008\projects\biodata\biodata_main.c(131... : error C2065: '__argv' : undeclared identifier


d:\documents and settings\olawale\my documents\visual studio 2008\projects\biodata\biodata_main.c(131... : warning C4047: 'function' : 'const char **' differs in levels of indirection from 'int'


d:\documents and settings\olawale\my documents\visual studio 2008\projects\biodata\biodata_main.c(131... : warning C4024: 'mclRunMain' : different types for formal and actual parameter 3


Biodata_main - 2 error(s), 2 warning(s)


========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

C program based on AI reasoning for Bioinformatics data processing?
int main(int argc, char* argv[])


C++ program help?

I am trying to write a program that asks for two integers and then finds the greatest common factor between them. IN C++


I copy paste it and it doesn’t work? PLZz HELP


Thank you





......................................





#include %26lt;iostream%26gt;


using namespace std;


int factor(int a, int b);





int main()


{


int x, y;





cout %26lt;%26lt; "This program allows calculating the factor\n";


cout %26lt;%26lt; "Value 1: ";


cin %26gt;%26gt; x;


cout %26lt;%26lt; "Value 2: ";


cin %26gt;%26gt; y;





cout %26lt;%26lt; "\nThe Greatest Common factor of "


%26lt;%26lt; x %26lt;%26lt; " and " %26lt;%26lt; y %26lt;%26lt; " is " %26lt;%26lt; factor(x, y) %26lt;%26lt; endl;





return 0;


}





int factor(int a, int b)


{


while( 1 )


{


a = a / b;


if( a == 0 )


return b;


b = b / a;


if( b == 0 )


return a;


}


}

C++ program help?
Hi your main() functions good and the idea behind how you work out the greatest common factor is also fine but you need to make sure when you do the division that the larger of the 2 numbers is divded by the other.





A simple check if a is greater than b allows you to know when to to divide a/b or b/a. The case where they are both equal to each other can be handled by either.





int factor(int a, int b)


{


int ret_val=0;





/* CASE 1 a %26gt; b */


if (a %26gt; b)


{


ret_val = a/b;


}


else /* CASE 2 b %26gt;= a */


{


ret_val = b/a;


}





return (ret_val);


}





Things to note include:





- I have removed the forever loop while(1) as it wasnt doing anything because you would return from the function.





- avoid returns in the middle of a function, to get around this I have a return value, ret_val, that only returns on the end of the function.





- I would add a check for 0 when the values are read in to make sure that you dont do a divide by 0.





Good luck.
Reply:You have to include math.h





So add this at the top of your program:





#include %26lt;math.h%26gt;


Simple addition program in C++?

here is my code





#include %26lt;iostream.h%26gt;


#include %26lt;math.h%26gt;


#include %26lt;ctype.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





class calculator


{


public:


calculator() {}


void input();


void addition();


private:


};


void input() // This function will get the two integers


{


int num1 = 0;


int num2 = 0;


cout %26lt;%26lt; "Enter the 1st number: ";


cin %26gt;%26gt; num1;


cout %26lt;%26lt; "Enter the 2nd number: ";


cin %26gt;%26gt; num2;


}





void addition() // This function will perform the operation


{


int num1 = 0;


int num2 = 0;


int result = 0;


result = num1 + num2;


cout %26lt;%26lt; "The result is " %26lt;%26lt; result;


}





void main()


{


calculator c;


c.input();


c.addition();


}





I'm getting errors, can someone assist me

Simple addition program in C++?
I'm not totally clear on what you're trying to do, but I have corrected your code a bit:








#include %26lt;iostream.h%26gt;


#include %26lt;math.h%26gt;


#include %26lt;ctype.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





class calculator


{


public:


calculator() {}


void input();


void addition();


private:


int num1,num2;


};


void calculator::input() // This function will get the two integers


{


cout %26lt;%26lt; "Enter the 1st number: ";


cin %26gt;%26gt; num1;


cout %26lt;%26lt; "Enter the 2nd number: ";


cin %26gt;%26gt; num2;


}





void calculator::addition() // This function will perform the operation


{


int result = 0;


result = num1 + num2;


cout %26lt;%26lt; "The result is " %26lt;%26lt; result;


}





void main()


{


calculator c;


c.input();


c.addition();


}
Reply:First and foremost, there is a HUGE LOGICAL ERROR. Even if you get the program to work, it will still give you always zero because you are resetting the num1 and num2 variables RIGHT before you add them. What happens to the value you input??? They become zero and then you add them and display the answer which will always be zero.





Second, why do your libraries at the top end with .h?





Why are you writing the program like this? Why do you have all these subroutines? Are you supposed to practicing in creating subroutines and then passing values from one subroutine to another? You need to declare the variables as global variables so that their values can pass from one function to another. There are a lot of other things that don't make sense. I can't even write them all here.





First try doing it all only in the main function. And why is your main voided. Make it return zero at the end. The return zero is there for a reason.
Reply:You need to declare num1 and num2 class level variables for them to keep their values across method calls. Also, Cin object only accepts a character string. You then cast the string as a number.





Include the proper headers





class calculator


{


private:


int num1;


int num2;


public:


calculator() {}


void input();


void addition();


private:


};


void input() // This function will get the two integers


{


string tmp1;


string tmp2;


cout %26lt;%26lt; "Enter the 1st number: ";


cin %26gt;%26gt; tmp1;


cout %26lt;%26lt; "Enter the 2nd number: ";


cin %26gt;%26gt; tmp2;





num1=(int)tmp1;


num2=(int)tmp2;


}





void addition() // This function will perform the operation


{


cout %26lt;%26lt; "The result is " %26lt;%26lt; num1+num2;


}





void main()


{


calculator c;


c.input();


c.addition();


}











Can you also include the output of the debugger
Reply:I think you have a logic error here - you don't need to - in fact should not - assign the zero values to the 'num1' and 'num2' variables in the 'addition' method; the answer will always be 0. You need to remove the first 2 lines of code in the addition method. Also, you need to include properties for the num1 and num2 variables if you want to use them throughout the program. Either that or declare them as global variables. The way you have it now, they are in local scope in the input and addition methods, so once you take them out of the addition method, they will be out of scope when you call it in the main method.
Reply:I don't know anything about c++, but your variables num1 and num2 are local the way you have them in input() and addition().


You should probably have them as private members of the calculator class.


[C++] Why the result of my programme is "烫烫烫烫烫烫烫烫"?

my C++ code:








#include %26lt;windows.h%26gt;


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


using namespace std;





int main()


{


char a[128]="**** the truth!";


cout%26lt;%26lt;a%26lt;%26lt;endl;





ofstream outfile("temp.txt",ios::out);


for(int i=0;i%26lt;=127;i++)


{if(a[i]!=NULL)outfile%26lt;%26lt;a[i];}


outfile.close();





char b[128];


ifstream infile("temp.txt",ios::in);


for(int j=0;j%26lt;=127;j++)


{infile%26gt;%26gt;b[i];}


cout%26lt;%26lt;b%26lt;%26lt;endl;


infile.close();





return 0;


}











result:


**** the truth!


烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫!烫烫...


烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫蘁

[C++] Why the result of my programme is "烫烫烫烫烫烫烫烫"?
Probably because of this code





for(int j=0;j%26lt;=127;j++)


{infile%26gt;%26gt;b[i];}





Your for loop increments j but in the loop you are using b[i].


i should have a value of 127 or rubbish if it is out of scope.

radiata

Finding x-int, vertical and horizontal asymptotes of a rational function...???

To find y-int plug a 0 into the rational function.


How to find x-int, vertical and horizontal asymptotes?


x-int: find roots of numerator. (huh? roots?)


Hor.asym.: find roots of denominator. (huh? roots?)


vert.asym.:


a) if n%26lt;m then the x-axis is HA


b) if n%26gt;m there is no HA


c) if n=m then y=an/bn is HA


n? m? y=an/bn?


PLEASE HELP!!!

Finding x-int, vertical and horizontal asymptotes of a rational function...???
Consider the equation y= a (x^n) / b (x^m) where n and m are the highest powers of the variable x found AFTER factoring and reducing the numerator and denominator to the products of the smallest polynomials posible. The situation may be that n or m may be zero, and that's OK.


The y intercept is found when x=0. The x intercept is found when the factors of the numerator are set = to zero; i.e. if y= x^2 + 3x + 2 = (x+2) (x+1), then x=-2 and x=-1 are conditions that yield y=0, and -2 and -1 are the roots of the numerator and are the y intercepts.


The vertical asymptotes are when Y becomes infinite, i.e the denominator becomes zero. Take each of the factors in the denominator, set them equal to zero, and solve for the corresponding values of x. For an equation y = 6 / (x-2) (x+3), set each denominator factor equal to zero, and the conditions are for two vertical asymptotes, one at x=2, and the other at x= -3.


For the horizontal asymptotes go back to , y= (a (x^n)) / (b (x^m)). If n%26gt;m there is no HA. If n%26lt;m, such as y= x / ((x^2)+1), the HA is the x axis. If n=m the HA is an/bn, or just a/b.


Try this. I hope I didn't make any typo mistakes


How to change from c to c++?

Please, can anyone help switch this to c++?


I will be very grateful!





#include %26lt;stdio.h%26gt;


/* Computes the length of Collatz sequences */


unsigned int step (unsigned int x)


{


if (x % 2 == 0)


{


return (x / 2);


}


else


{


return (3 * x + 1);


}


}





unsigned int nseq (unsigned int x0)


{


unsigned int i = 1, x;


if (x0 == 1 || x0 == 0)


return i;


x = step (x0);


while (x != 1 %26amp;%26amp; x != 0)


{


x = step (x);


i++;


}


return i;


}





int main (void)


{


unsigned int i, m = 0, im = 0;


for (i = 1; i %26lt; 500000; i++)


{


unsigned int k = nseq (i);


if (k %26gt; m)


{


m = k;


im = i;


printf ("sequence length = %u for %u\n", m, im);


}


}


return 0;


}

How to change from c to c++?
if u know c++


then change few input output statement and techniques of programming
Reply:You have the pseudo code and the C code from this and other posts I see. You should be able to do this. Your degree will mean nothing if you dont know how to program! Now put your nose to the grind and learn!
Reply:Or else you may contact a C++ expert at websites like http://oktutorial.com/


The form of the partial fraction decomposition of a rational function is given below...find A, B, and C?

((–1x^2–2x–14)/(x+5)(x^2+4)) = ((A)/(x+5)) + ((Bx+C)/(x^2+4))





Now evaluate the indefinite integral.


*int* ((–1x^2–2x–14)/((x+5)(x^2+4))dx





If you can give me the answer to the integral as well as A,B,and C please?!

The form of the partial fraction decomposition of a rational function is given below...find A, B, and C?
A(x^2 + 4) + (Bx + C)(x + 5) = - x^2 - 2x -14





Putting x = - 5:


29A = - 25 + 10 - 14


A = - 1





Equating absolute terms:


- 4 + 5C = - 14


C = - 2





Equating coefficients of x:


- 2 + 5B = - 2


B = 0





int[ (–1x^2–2x–14)/((x+5)(x^2+4))dx


= int[ - 1 / (x + 5) - 2 / (x^2 + 4) ] dx


= - ln | x + 5 | - arctan(x / 2) + c.


Convert current c++ project to visual studios express?

i just learned some c++. i dont remember my original program, but when i try to import a perfect (in the other c++ program) to visual studios express, a different c++ program, i got many errors. i tried to understand them, but couldnt, though i think that different c+++ programs are slightly differnt in language.





can someone plz tell me the differences between my old program and express? and how to modify my old code so it works in express?





i dont know the name of the program but this is the code:





#include %26lt;iostream%26gt;


int main()





char grid [3][3];





void gridprint()


{


for (int y = 0; y %26lt; 3; y ++)


{


for (int z = 0; z %26lt; 3; z++)


{


cout %26lt;%26lt;grid [y][z];


}


cout %26lt;%26lt; endl;


}


}


int main()


{





cout %26lt;%26lt; "TICTACTOE \n \n " %26lt;%26lt; endl;





char x = 'X';


char o = 'O';


int y;


int z;


bool win = false;


int turns = 0;


char player = o;





// making empty spaces -'s


for (y = 0; y %26lt;3; y++)


{


for(z=0; z %26lt; 3; z++)


{


thx in advanc

Convert current c++ project to visual studios express?
Can you state the exact error that visual express is complaining about? That would kind of help.





I do see one problem in the code. cout and cin are in the namespace "std", theofore you can't just use them like global variables without declaring using the the "std" namespace. This is commonly done by adding "using namespace std;" before any use of cout or cin like so.





#include %26lt;iostream%26gt;





using namespace std; //declaring use of namespace





int main()


{


int example;


cin%26gt;%26gt;example; //now you can use cin and cout like


cout%26lt;%26lt;example%26lt;%26lt;endl; //this





return 0;


}
Reply:For getting project assignment help there are better websites like http://getafreelnacer.com/
Reply:Your gridprint function is not declaring the local variables x, y, z it is using. Your program wouldn't compile under any compiler. It's not a Visual Studio problem.
Reply:First, never ever post large blocks of unformatted code. When there is no way of posting formatted code, use a pastebin like http://www.rafb.net/paste/ (or just google for other pastebins / nopaste sites).





Second, C++ is a language. Not a program. It’s a standard language too, so there isn’t really a Visual C++ vs g++ C++ vs Comeau. Assume your code is broken. Now try to fix it. If you don’t know how, as I said, post the code on a nopaste site, so we can see it properly formatted. Then try compiling it, with all warnings on (compiler flag /W4 ), and post these warnings/errors on a nopaste site as well.

medium

Can you help me debug this c++ program [update a file]?

#include "stdafx.h"


#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;ctype.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;string.h%26gt;





struct book


{


char bookID[6];


char title[31];


char author[31];


char copyright[5];


}bookrec;





FILE *bookfile;





int main()


{


bookfile= fopen("BOOK.DAT", "rb");





if(bookfile==NULL)


{


printf("File does not exist, press any key..");


getch();


}


else


{


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);


if(feof(bookfile))


{


printf("File is empty, press any key..");


getch();


}


else


searchNupdate();


}


fclose (bookfile);





return 0;


}





void displayTitle(void)


{


printf("\n\t\t==UPDATE A FILE==\n");


printf("\t\t==BOOK==\n");


printf("UPDATE RECORDS:\n\n");


}





void dispRec(void)


{


printf("%s%s%s%s\n",bookrec.bookID,bo...


}





void displayRecord(void)


{


int lineCounter=0;





while(!feof(bookfile))


{


displayTitle();





while(lineCounter%26lt;10 %26amp;%26amp; !feof(bookfile))


{


dispRec();


lineCounter++;


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);


}


if(!feof(bookfile))


{


printf("Press any key to continue..");


getch();


}


else


printf("End of file, press any key..");


getch();


}


}





void updateRecord(void)


{


char nBookid[6];


char nTitle[31];


char nAuthor[31];


char nCopyright[5];


int field;


char rep;





do


{


printf("Which field to update[1-4]? :");


scanf("%d", %26amp;field);





while(field%26gt;4)





if(field==1)


{


printf("Input new book ID:");


gets(nBookid);


}


else if(field==2)


{


printf("Input new book title:");


gets(nTitle);


}


else if(field==3)


{


printf("Input new book author:");


gets(nAuthor);


}


else


{


printf("Input new copyright:");


gets(nCopyright);


}





do


{


printf("Update another field(Y/N)? :");


scanf("%c", %26amp;rep);


}


while(tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');





} while(rep=='y')


fseek(bookfile, 1, 0);


fwrite(%26amp;bookrec, sizeof(bookrec), 1, (bookfile));


fclose(bookfile);


}





void search(int target[6],int found, int size)


{


int found=0, i;


int count=0;


int field=0;





bookfile= fopen("BOOK.DAT", "r+");


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);





while(!feof(bookfile) %26amp;%26amp; found!=0)


{


if(target[i]==field)


{


found=1;


}


else


{


count++;


fread(%26amp;bookrec, sizeof(bookrec), 1, bookfile);


}


}


size= count * sizeof(%26amp;bookrec);


}





void searchNupdate(void)


{


char rep, target[6];


int size=0;


int found=0;





displayTitle();


do


{


printf("Input book ID to be updated:");


gets(target);





search(target,%26amp;found,size);





if(!found)


{


printf("Record is not found\n");


}


else


{


displayRecord();


}


do


{


printf("Update (Y/N)? :");


scanf("%c", %26amp;rep);


}


while(tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');


if(rep=='y')


{


updateRecord(%26amp;size);


}


do


{


printf("Update another (Y/N)? :");


fflush(stdin);


scanf("%c", %26amp;rep);


}while(tolower(rep)!='y' %26amp;%26amp; tolower(rep)!='n');


}


while(rep=='y');


fclose(bookfile);


}

Can you help me debug this c++ program [update a file]?
Can you give a hint on what function the error occurred?


C++ building a class with 2 dimensional vectors?

I'm trying to get some framework off the ground for a project involving drawing a game board using 2D vectors. This is an early framework....All I want is to get something to compile. Let's just say for now I want a 5 X 5 matrix. I can't quite get the call part to work so it will compile. Can someone who is good with C++ look at this code and tell me whats wrong. Thanks.





#include%26lt;iostream%26gt;


#include%26lt;vector%26gt;


using namespace std;





class georgeClass


{


private:


vector%26lt;vector%26lt;int%26gt; %26gt; myVec;//sets up multi D vector


public:


georgeClass(int);


void printRow(int);


};





georgeClass::georgeClass(int x)


{


vector %26lt;int%26gt; row(x,0);


for(int i=0;i%26lt;x;i++)


myVec.push_back(row);


for(int j=0;j%26lt;x;j++)


myVec[i][j]=i+j;


}


void georgeClass::printRow(int r)


{


for(int i=0;i%26lt;myVec[r].size();i++)


cout%26lt;%26lt;myVec[r][i]%26lt;%26lt;endl;//I don't what it fills up with for now


}


int main()


{int x=5;// should tell constructor to make a 5X5 matrix


georgeClass vec(x);


int r;


cout%26lt;%26lt; vec.printRow(r);//%26lt;-----something wrong here???????????????





}

C++ building a class with 2 dimensional vectors?
The problem is PrintRow() returns void. You're trying to put void into cout, and that object definitely won't have overloaded the %26lt;%26lt; operator to take void.





Your PrintRow() functions prints out the row internally. Change "cout%26lt;%26lt; vec.printRow(r);" to "vec.printRow(r);".





Hope this helps. I haven't checked for any other errors, so it may still fail to compile.
Reply:First, without the errors it's hard to tell what's wrong. Why don't you use a 2D array instead.. or use a single Vector thats (height * width) long, and index the item you want by using J*width+i or similar.


String manipulation C++?

Hi i am working on a small program where a user enters a string which should be more than 8 characters. Then once they have entered a string, the program should do the following:


1) output the size of the sentence


2) output the 1st 3rd 5th and 7th letter and append it to the end of the inputted sentence.





This is what i have done so far but i am getting errors and i am new to c++:





#include %26lt;iostream%26gt;


#include %26lt;string.h%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int main()


{


int iQuit;


char str[7];


cout%26lt;%26lt; "Enter sentence \n";


getline(cin,str);


cout%26lt;%26lt; "Size of the sentence" %26lt;%26lt; str.length() %26lt;%26lt; endl;


cin %26gt;%26gt; iQuit;


return 0;


}





Can someone help on this and the second part please? i could probably do this in java but i need to do in C++.





I would appreciate it if someone can help me on tell me they have done in such a way?

String manipulation C++?
There are two main kinds of string in C++, the null terminated strings inherited from C and the C++ string object. Using the latter makes your assignment a cinch. Unless you are instructed otherwise you should begin to use string objects and move away from null terminated strings whenever possible.








#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main()


{


string input;





while (input.length() %26lt;= 8)


{


cout%26lt;%26lt; "Enter sentence at least 8 characters in length\n";





getline(cin, input);


}





cout%26lt;%26lt; "Size of the sentence = " %26lt;%26lt; input.length() %26lt;%26lt; endl;





input += input[2];


input += input[4];


input += input[6];





cout %26lt;%26lt; "appended sentence is: " %26lt;%26lt; input %26lt;%26lt; endl;





return(0);


}
Reply:Try this code for starters. Can you spot the changes?





#include %26lt;iostream%26gt;


#include %26lt;string.h%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int main()


{


int iQuit;


string input;


cout%26lt;%26lt; "Enter sentence \n";


getline(cin, input);


cout%26lt;%26lt; "Size of the sentence " %26lt;%26lt; input.length() %26lt;%26lt; endl;


cin %26gt;%26gt; iQuit;


return 0;


}
Reply:You can't say str.length(). You have to use the function strlen(), like this:





cout%26lt;%26lt; "Size of the sentence" %26lt;%26lt; strlen(str) %26lt;%26lt; endl;





To output the 1st, 3rd, 5th and 7th letters you have to access them from the string/character-array. This is done like so: str[0] is the 1st. str[2] is the 3rd letter, etc.





Appending is easy. Just make a new character array that is bigger, copy the inputted string to it (using the strcpy function) and then assign the letters that you want to the new string.


C++ Programmers!! help!!?

there's an error in this code... can you help me repair it?!








#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;string.h%26gt;





void initval();





int chars[255];





int main()


{


FILE *file_r;


int ferr = 0, i;


char filename[50];


while (ferr == 0)


{


system("cls");


printf("Enter file name: ");


gets(filename);


file_r = fopen(filename, "r");


if (file_r == 0)


{


printf("Error! File does not exist!");


getch();


}


else


{


ferr = 1;


}


}


char *r;


char c, ctr = 0;





while ((c = getc(file_r)) != EOF)


{


ctr++;


}





fclose(file_r);


file_r = fopen(filename, "r");





char string[ctr];





i = -1;


while ((c = getc(file_r)) != EOF)


{


i++;


string[i] = c;


}





printf("\n%s", string);





printf("\n\n%s\n\n", strrev(string));





//tig-ihap





for (i = 0; i %26lt; strlen(string); i++)


{


chars[string[i]]++;


}





for (i = 0; i %26lt; 256; i++)


{


if (chars[i] != 0)


{


printf("%c = %d\n", i, chars[i]);


}


}





getch();





fclose(file_r);


return 0;


}





void initval()


{


int i;


for (i = 0; i %26lt; 256; i++)


{


chars[i] = 0;


}


}

C++ Programmers!! help!!?
do this:





char [] string = new char [ctr];








and don't forget





delete [] string





at the end to free up the memory
Reply:from the code you provided i copy and paste it on my system and i recieved no error messages and the program ran fine most likely it has to do with your compiler in my unix based system it didn't recongize the conio.h header file try using a different compiler
Reply:you cant declare a char string that way (char string[ctr]). the length of the string has to be a constant size such as "char string[20];". as the other person said, you could also do this "char [] string = new char [ctr];"
Reply:The code you're using isn't C++, it's just C. It'd help if you listed the error.

cvs