Friday, July 31, 2009

I need help with my c++ compiler...?

i am using dev-c++4 as my compiler and i put this in





// my first program in C++





#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


cout %26lt;%26lt; "Hello World!";


return 0;


}





then i compile it and it says i have no errors. so i push execute and nothing happens. wat am i doing wrong?

I need help with my c++ compiler...?
First, make sure you clicked both compile and build (you can also just click build directly).





Run your program from the command line. If you don’t want to, you can put in a (acceptable for beginners only) kludge by adding cin.get() to the end of main. See Google for the problem of C++ program closing too quickly.





Finally, I want to correct a technical error in your choice of words. But it’s critical you learn to make this distinction. Dev-C++ is what is known as an IDE. It is not a compiler itself. Your compiler is MingW (that’s what Dev-C++ is designed to use). MingW is the windows port of the gcc compiler. Knowing these details will help you with your Googling efforts.
Reply:....


cout %26lt;%26lt; "Hello World!";


cin.get();


....
Reply:Your program did work, it outputs Hello World but it was so fast you couldn't see it. Youre next line after the cout line should be a cin statement. The screen will pause for the cin, and you will see your Hello World. Then when you hit enter, the program will finish executing and exit. Without a line to pause the program (cin), the program executes, displays hello world, finishes executing and closes, fast enough where you didn't think anything happened.
Reply:You're program should compile fine, no errors. Did you start a console project, if so, you should use command line or dos box if on windows to run it.





Take a look on http://www.nextdawn.nl for a great series of C and C++ tutorials (they also explain compiling).

cvs

Plz help with this c++ program?

a. Write a pseudo-code that prompt the user to input number of old items and then receive the sold value for each item, calculate the average value, display the items numbers associated with its values and display also the calculated average value on the screen.





b. write down the C++ code for the previous program.





Well... I tried to solve it and here we go:





* Pseudo-code:


start


get sold items,sold value


average=sold value/sold items


Display sold items,sold value


Display average





* C++:





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


void main()


{


int NumOfSold,SolValue;


float average;


cout%26lt;%26lt;"enter the number of sold items\n";


cin%26gt;%26gt;NumOfSold;


cout%26lt;%26lt;"enter the sold value for each item\n";


cin%26gt;%26gt;SolValue;


average=(float)SolValue/NumOfSold;


cout%26lt;%26lt;NumOfSold%26lt;%26lt;":"%26lt;%26lt;SolValue%26lt;%26lt;endl;


cout%26lt;%26lt;"average:"%26lt;%26lt;average;


}

Plz help with this c++ program?
So, what is the result?
Reply:Did you run it to see if it works? If it works, then it's right, if it doesn't, then you'll have to debug things to make it work.





After looking at it for 2 seconds, it looks right, but that doesn't mean it is. The only way to be sure is to compile it and test it.


I cant' figure whats wrong w/my C++ program!HELP!?

So im supposd to write a program that calculates


the sum of 1/n! (1 divided by n factorial) , n=1 to 100


or n=1 below the Sigma sign, 100 above, 1/n1 on the right of the sigma sign


This is my program:


keep in mund C++





#include %26lt;iostream%26gt;


using namespace std;


int main ()


{


int i,fact=1,sum;





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


{ fact = fact * i;





sum = 1/fact;





cout%26lt;%26lt;sum;


}





return 0;


}





after i compile link it and execute it i get a message saying


Arithmetic Exception (core dumped)


What is that?


Help please who ever is out there.

I cant' figure whats wrong w/my C++ program!HELP!?
This program has a lot of issues


1stly, you should 1st initialize sum to 0 and then use


sum+= 1/fact (because you want the summation and not each of them individually)





the second problem is, that you should be declaring sum as a double and not an int.


int x=1/2 //implies x=0


double x=1.0/2 //implies x=0.5





this brings me to the 3rd problem.


1/fact will always be zero since 1%26lt;fact and both are ints. you need to write that as 1.0/fact





and to wind it up, one last problem, fact(100) is a really large number. it cant be stored as an integer. I am too lazy to try, but I am pretty sure you cant store it as a long either. you will get overflows of numbers (number turning into a negative number), which will skew your results.





I am appending a similar program. see if it makes sense to you


#include %26lt;iostream%26gt;


using namespace std;


int main ()


{


int i,fact=1;


double sum=0; //sum is now double and initialized to 0





for(i=1;i%26lt;=10;i++) //10 and not 100


{


fact *= i;


sum += 1.0/fact; //adding to sum. also 1.0 and not 1


cout%26lt;%26lt;sum%26lt;%26lt;endl; //appending a newline. this helps bufferring the stream and you catch errors better


}


return 0;


}





All the best
Reply:Make sure fact is not 0 at all... I know


you intialied fact before the i loop to one...


but does it stay above 0 all the time in the loop...





usually a arithmetic expcetion means


you try to divide a 0 or...


the division symbol is not the right one..


since it's integer...


remember you are not getting integer result 1/2 is .50





here is what you can do to see what is the probem


take out the sum=1/fact for now and put a


cout %26lt;%26lt; fact %26lt;%26lt; endl; to see if fact is putting out the right numbers... if not than you know..


if it seems right...


put back the sum=1/fact;


but check to see if you are allowed to use / because you are getting a decimal value and you may have to use..


the var real...
Reply:try unsigned long i,fact=1,sum;


instead of int i,fact=1,sum;


C++ programming help???

How do I make my version of C++ program for strcpy(char [] , char [] , int) without using pointers???





can someone help

C++ programming help???
That would involve creating a string class, which would include a member method, or operator that performs the assignment.


C++ Programmers, need help. would you?

I wrote this program and i compiled it successfully, this program runs successfully, but when it retrieves data from user the program get closed. whats the prob?


Here is my program and my compiler is Dev-C++





# include %26lt;iostream%26gt;





using namespace std;


int main ()


{


float grade;


printf ("Please enter your grade : ");


scanf("%d",grade);


if (grade %26gt;10){


printf("You have passed the test...");


}


else


{


printf("You havent passed the test...");


}


cin.get();


cin.ignore();


return 0;


}

C++ Programmers, need help. would you?
There are two problems:





1. In the scanf the %d means the input is an integer, but you declared the variable as a float.





2. Also in the scanf, you need to pass a reference to the variable, not the variable itself.





So change it to scanf("%f",%26amp;grade);





And it will work for you. %f means float, and %26amp;variable means take the address of (pass by reference.)





Alternatively, you can declare grade as an int, and keep the %d.








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


Yes, you're going to have a problem with bogus inputs.





You could check the return value of the scanf call.





if !(scanf("%f", %26amp;grade) {


printf("Rerun the program and try putting in a number this time");


return 1;


}
Reply:I am guessing the enter keystroke you pressed to send your number input to the program zipped you past the cin.get statement and returned (ended). If that´s not the case, you can always through in some trace statements and a few getchar()´s at the end (or step through with a debugger).
Reply:In DEV-C++ you need to add, before your return 0; this linke





"system("PAUSE");"
Reply:cin.get will read a white space because it doesn't expect to read anything from the input. If you run your program from cmd line it won't close automatically after running it (because the cmd session is still active).


The easy way would be to request the user to type in a key to continue, something like...


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


scanf("%c",%26amp;key)..


This will require to store useless data in your program and of course it can be avoided. The alternative would be to "pause" the system until the user decides to end the session manually. Just type


system("PAUSE");


at the end and it will pause the program until the user press a key to exit.
Reply:what is the program trying to do, i am a C++ programmer, you can contact me at srp333@comcast.net for help--------------


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


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


int main()


{


char grade[20];


printf("Please enter your grade: ");


gets(grade);


if(grade %26gt; 10)


{


printf("Your have passed the test.\n");


system("pause");


}


else


{


printf("You havent passed the text");


system("pause");


}


}
Reply:I think it's because the scanf doesn't take the "return" key after the grade : it is still in the buffer, so cin.get() catches it at once, and your program closes without waiting.


In C, you can address the problem in a nasty way by putting a "fflush(stdin);" just after your scanf. There are prettier ways of doing it, but I just can't remember them right now.


I guess if you know the representation of the return key in your system (\n, \r\n, \r), you can make scanf catch it for you at the end of its first parameter (but your code may have portability issues).

gardenia

Dev-C++ problem or not sure!?

I typed this:


// my first program in C++





#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


cout %26lt;%26lt; "Hello World!";


cout %26lt;%26lt; "I am a C++ Program!";


return 0;


}





Then i clicked execute and drop menu appeared i clicked compile and then i clicked run it appeared as command prompt and it flashes up fot about 20 milliseconds and then just closed so why is that and is there a way of making the command prompt windows stay up forever until you click close???

Dev-C++ problem or not sure!?
#include %26lt;iostream%26gt;


#include%26lt;conio%26gt;//add this line and the other at last


using namespace std;





int main ()


{


cout %26lt;%26lt; "Hello World!";


cout %26lt;%26lt; "I am a C++ Program!";


getch();//add these two lines


return 0;


}
Reply:Hi


The program is running so fast that it you cant see it.


Type





System ("Pause"); before your return 0; and the screen will stay there for you to see :)





Im learning this too mate but i knew this answer :)


Hi! everyone!!! i have a code tower of hanoi in c++.can some one plss .help me.?

the code is using recursion. can someone pls tell me how it's working or change the code to normal code without recursion and class or stack. plss help me code is as follows:---








//prog to print the solution of TOWERS OF HANOI





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


#include%26lt;conio.h%26gt; //for clrscr()





void hanoi(int n, char A, char B, char C)


{


if(n%26gt;0)


{


hanoi(n-1,A,C,B);


cout%26lt;%26lt;"\nMove disc " %26lt;%26lt;n%26lt;%26lt;"from tower"%26lt;%26lt; A%26lt;%26lt;"to tower"%26lt;%26lt; B;


hanoi(n-1,C,B,A);


}


return;


}





void main()


{


int n;


clrscr();





cout%26lt;%26lt;"Enter the number of discs : ";


cin%26gt;%26gt;n; //input





cout%26lt;%26lt;"\nThe solution to Tower of Hanoi is:- \n";


hanoi(n,'L','R','C');





getch();


}











pls help me!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...

Hi! everyone!!! i have a code tower of hanoi in c++.can some one plss .help me.?
Tower of hanoi solution involves recursive tasks. That is why most of the implementations are done using recursion.





I works as, we 1st places the the biggest Coin in the destination peg and our remaining task is to place (n-1) Coins on top of the nth one.
Reply:http://www.cut-the-knot.org/recurrence/h...


C++ Errors. Please help?

I got these errors while compiling one of my c++ programs. Can someone explain what it means or how to fix it?








array.cpp: In member function `double Array::GetData(int)':


array.cpp:33: error: ISO C++ forbids comparison between pointer and integer


array.cpp:34: error: invalid types `double*[int*]' for array subscript


array.cpp: In member function `void Array::Resize(int)':


array.cpp:47: error: `sizePtr' was not declared in this scope


array.cpp:49: error: invalid type argument of `unary *'


array.cpp:53: error: ISO C++ forbids comparison between pointer and integer


array.cpp:54: error: invalid type argument of `unary *'


array.cpp:57: error: invalid conversion from `int' to `int*'


array.cpp: In member function `void Array::Output()':


array.cpp:65: error: ISO C++ forbids comparison between pointer and integer


array.cpp: In member function `void Array::Input()':


array.cpp:72: error: ISO C++ forbids comparison between pointer and integer

C++ Errors. Please help?
Not unless you post the source code.


Can i have some help in c++?

i am very new to c++ and programming in general.


i bought a book called c++ all in one desk reference for dummies.


i am a few pages in and im having trouble making words come up into a dos box.





im using a program called dev-c++





#include %26lt;iostream%26gt;


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





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


{


cout %26lt;%26lt; "Hello, i am your computer talking." %26lt;%26lt; endl;


system("PAUSE") ;


return 0;


}








when i enter that, the error box on the bottom of dev-c++ says





line 8 message: cout undeclared (first use this function)





line 8 message: endl undeclared (first use this function)





also, if i delete line 8 of that, it works fine, a dos box pops up and says press any key to continue.





if you could please give me a few tips upon what i might be doing wrong,


please tell me!

Can i have some help in c++?
You need to either change line 8 to read:





std::cout %26lt;%26lt; "Hello..." %26lt;%26lt; std::endl;





Or add:





using namespace std;





After the #include lines.





You have to tell the compiler in what namespace to find cout %26amp; endl; the first does it explicitly, the second makes all names in the std namespace available in your program.





Edit to luv l: No, it's not %26lt;iostream.h%26gt;, it's just %26lt;iostream%26gt;. The standard library does not use .h for its headers; the .h versions are deprecated and should no longer be used, as they do not use the std:: namespace.
Reply:You need to specify that your working with the standard c++ namespace.





type in "using namespace std;" before your 'main' function.





alternatively, you could use std::cout %26lt;%26lt;" blah blah"; instead if you preferred, putting the std:: before every cout/ cin / any other standard function.





Im new to c++ too, sorry if my terminology is a bit worng.
Reply:#include %26lt;iostream%26gt;


using namespace std;





int main()


{


cout %26lt;%26lt; "Hello, i am your computer talking." %26lt;%26lt; endl;


system("PAUSE") ;


return 0;


}
Reply:its not iostream


its iostream.h


try this it will work
Reply:firstly, about the cout thing. (i have dev-c++) change the line #include %26lt;iostream%26gt;


to


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





now you should be aware that a dos box will always pop up (unless you use win32, that's not the case however)


what the system("pause") function does is to display "press nay ...'

aster

Microsoft Visual C++ 2005 Express Edition debug problem?

when i do the debug in the program the cmd appears quickly then close.


to know the code is :


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


int main ()


{


printf ("welcom to c ");


return 0;


}

Microsoft Visual C++ 2005 Express Edition debug problem?
It appears quickly and closes because that's the end of your program. After your printf(), pause for a console input (like Console.ReadLine() or cin %26gt;%26gt;). That will force your user to hit enter to end the program.
Reply:Add the function 'getch()' at the end to cause it to wait for you to press a key.
Reply:Your program is working fine keep on adding to it..


why using Standard (Stdio) not (iostream)


Can any body tell me what's wrong with this c++ function and loop?

1. I am trying to create a function that doesn't allow the input of alphabets... only digits and decimal point. The input is stored in a string and then the value is assigned to a variable which is returned by the function.The problem is that when i press Enter(just like scanf) nothing happens although i have considered this. Take a look at the function:-








double getinput()


{


int n=1000,k,z,c=0;


char N[100];





double x;


for(k=0;k%26lt;=n-1;k++)


{


do


{





N[k]=_getch();





if (N[k]=='\n')


break;


if (N[k]=='.')


{z=k;c++;}


if(('0'%26lt;= N[k] %26amp;%26amp; N[k]%26lt;='9') || N[k]=='.')


printf("%c",N[k]);





}


while((!('0'%26lt;= N[k] %26amp;%26amp; N[k]%26lt;='9')) || (N[k]!='.' %26amp;%26amp; c!=1) || (N[k]!='\n'));


if (N[k]=='\n')


break;


}





for(k=0;k%26lt;=n-1;k++)


{


if(k==z || N[k]=='\n')


continue;


if(k%26lt;z)


x+=(float)N[k]*pow(10.0,z-k-1);


if(k%26gt;z)


x+=(float)N[k]*pow(10.0,z-k);


}


return x;


}


2.Is this infinite?


for(n=low;n%26lt;=up;n+=(1/10)*(up-low))

Can any body tell me what's wrong with this c++ function and loop?
You forgot to reverse the logical operators when you reversed the sense of the tests. Try changing the test in the do/while to:


while((!('0'%26lt;= N[k] %26amp;%26amp; N[k]%26lt;='9')) %26amp;%26amp; (N[k]!='.' %26amp;%26amp; c!=1) %26amp;%26amp; (N[k]!='\n'));


(|| became %26amp;%26amp; in 2 places)


I did not read any farther.





The 2nd question is chopped, but I'll take a guess:


If 'up' is changing as a side effect in the increment portion (or in the body), the loop can become infinite.


Also, if the increment portion is integer and gets truncated to 0 in the calculation, the loop becomes infinite.
Reply:I think you should compare Ascii values rather than comparing string letter explicitly.





It will make your work easier too





Hope this helps


Cheers:)


I need help using the if statement in my C program?

hey i need to put if and else statement into this program....#include%26lt;stdio.h%26gt;





int main()


{


float a, b, c;


printf(" *** WAGE CALCULATOR ***\n\n\n");


scanf("c");





printf("How many hours have you worked this week? Hit enter\n");


scanf("%f",%26amp;a);





printf("what is your hourly rate? Hit enter\n");


scanf("%f",%26amp;b);





c=a*b;


printf("your gross salary is: $%f\n",c);


getc(stdin);


return 0;


}


i need two if statements.i need one to follow ....printf("How many hours have you worked this week? Hit enter\n");


scanf("%f",%26amp;a); ....when someone types in a value over 40 it has to say "ERROR value over 40 not accepted" and if under 40 the program needs to continue.





my second if statement needs to follow.....printf("what is your hourly rate? Hit enter\n");


scanf("%f",%26amp;b);...............and if the value is less then 6.75 it has to say"ERROR value under minimum wage not accepted" and if over 6.75 program needs to continue. email me if u need more info. thanks alot

I need help using the if statement in my C program?
I didn't compile this, but it should be pretty close. The "else" statement does not need to be explicitly defined in this case. It is implied.





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





int main()


{


float a, b, c;


printf(" *** WAGE CALCULATOR ***\n\n\n");


scanf("c");





printf("How many hours have you worked this week? Hit enter\n");


scanf("%f",%26amp;a);





if (a %26gt; 40) {


printf("ERROR value over 40 not accepted\n");


return 1;


}





printf("what is your hourly rate? Hit enter\n");


scanf("%f",%26amp;b);





if (b %26lt; 6.75) {


printf("ERROR value under minimum wage not accepted\n");


return 1;


}





c=a*b;


printf("your gross salary is: $%f\n",c);


getc(stdin);


return 0;


}
Reply:so


if(a %26gt; 40)


{


printf("Sorry we don't believe people actually work without clock watching");


return;


}





and


if(b %26lt; 6.75)


{


printf("Sorry we think all employers are responsible and respect the law you mus be some crazy illegal immigrant, we will not help you);


return;


}





i guess the returns will help you.


How do you run this simple C code?

Determine the order of execution of operations in the code below. Determine the sequence actively.





{ int A=9,B=3,C=1;


Printf(“%d %d %d %d”, A++,--B,C++,A*B*C);


}





Nothing I put in front of it or after it will make it run. I don't care about the answer, my professor keeps saying to run to verify what it says. I don't know what he wants! ahh!

How do you run this simple C code?
#include %26lt;stdio.h%26gt;


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





main ()


{


int a=9, b=3 , c=1;


printf ("%d %d %d %d",A++,--B,C++,A*B*C);





getch()











OUTPUT WILL BE


10 2 2 27





}
Reply:Define int A


Assign 9 to A


Define int B


Assign 3 to B


Define int C


Assign 1 to C





Subtract 1 from B


Print A


Print B


Print C


Calculate A*B*C


Print result of calculate


Add 1 to A


Add 1 to C
Reply:Did you compile it? You need to compile it in order to run it. Try getting the free Borland compiler. I would recommend this guide on how to compile it. http://computerprogramming.suite101.com/...





If it compiles unsuccessfully, the compiler will point out errors and then you should fix those and it should compile right.


-If it compiles properly, run it by using a command prompt window by going to the directory with cd c:\...


then run Filename.exe or it you wont see the result.

marigold

Convert code from C# to VB?

Namespace yahoo


{


Class Program


{


public static int Main(string[] args)


{


TextHelper textHelper = new TextHelper();


SayHello(textHelper);


char[] output = textHelper.GetHelloArray();


foreach (char c in output)


{


System.Console.WriteLine(c);


}


string outputString = textHelper.HelloWorldProperty;


for (int x = 0; x %26lt; outputString.Length; x++)


{


System.Console.WriteLine(outputString[...


}


System.Console.WriteLine(textHelper.Ge...


System.Console.WriteLine();


int input;


do


{


input = System.Console.Read();


} while (input != textHelper.GetKeyForContine());


ExerciseSwitch(1);


ExerciseSwitch(2);


ExerciseSwitch(3);


ExerciseSwitch(Square(2));


return 0;


}


private static void SayHello(TextHelper textHelper)


{


System.Console.WriteLine(textHelper.He...


}


private static long Square(int x)


{


return x * x;


}


private static void ExerciseSwitch(long y)


{


switch (y)


{


case 1: System.Console.WriteLine("2");


goto case 2;


case 2:


System.Console.WriteLine("1 or 2");

Convert code from C# to VB?
Try this site..





http://converter.telerik.com/





There are a few other sites as well.





Most of them work about 80% correctly and the rest you have to do yourself.





Good Luck


C++ little problem?

I'm having problem with this piece of code:





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





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











void main( )





{





int y=0, r=0, c=8;





do{





clrscr( );





printf(“value:”); scanf(“%d ”, %26amp;y);





if (y = = 0)





r = r+1;





}while(y%26lt;=100);





printf(“ r = %d”, r);





}





****


ok, now my question is:


does this determine:


a) counts the number of zeros entered in n numbers that are lower than 101


b) counts the number of zeros entered in n numbers that are lower than 100





really having trouble with this, already did many tests but can't get to a conclusion, any help would be greatly appreciated.

C++ little problem?
Look at this from your program:





while(y%26lt;=100);





What this means is that the code in the loop will execute when the condition is true. In this case, the condition is that y is less than or equal to 100. So, when y is 100 the loop will still execute. But that is it. It will not work past 100. That means that it will count the numbers until it gets to 100 -100 will be counted.





So a) is the correct answer.
Reply:Choice a is the answer.
Reply:Entering in 100 would not get counted but the loop continues.





Entering 101 would not get counted and the loop would stop.





I would say both answers are correct. But, to stop the loop A would be the answer.





bad question though...if they are trying to teach while loop condition stops. Bad bad....


I need help with programming the binomial coefficient in to C++? See my program below, what is not correct?

#include "stdafx.h" #include %26lt;iostream%26gt; using namespace std ; int binomial (int n, int k) ; // function prototype int main ()


{ int n, k ; // parameters for the binomial number int result ;


cout %26lt;%26lt; endl ; // read in n %26amp; k cout %26lt;%26lt; "Enter n (positive integer) : " ;


cin %26gt;%26gt; n ; cout %26lt;%26lt; "Enter k (positive integer) : " ; cin %26gt;%26gt; k ;


result = binomial (n,k); cout %26lt;%26lt; "Binomial number " %26lt;%26lt; n %26lt;%26lt; "C" %26lt;%26lt; k %26lt;%26lt; " = " %26lt;%26lt; result %26lt;%26lt; endl; return (0); }


int binomial (int n, int k)


Computes the binomial coefficient nCk


Inputes: n, k (integers)


Output: binomial coefficient nCk ( integer)


{ int numerator , denominator ;


int i ; // needed to compute numerator %26amp; denominator


if (n %26lt; k) { return (0) ; } else { denominator = k*(i+1) ; // initial value for (i=0; i%26lt;k+1; i++) denominator = i * denominator ;


numerator = n*(n-(k+i)) ; // initial value


for (numerator = 1 ; numerator %26lt; n ; numerator = n-(k+(i++)))


numerator =numerator*(n-k+(i++)) ; return (numerator / denominator) ; } // else }

I need help with programming the binomial coefficient in to C++? See my program below, what is not correct?
at least what wrong I can see are the following points:





1) if (n %26lt; k) { return (0) ; } else { denominator = k*(i+1)


You have not initialized i. So It can take any value and it gives you the wrong answer.


2) for (i=0; i%26lt;k+1; i++) denominator = i * denominator ;


When i = 0, denominator will be 0, and it remains 0 through out the loop!


3) numerator = n*(n-(k+i)) ; // initial value


After the loop above, i = k+1. Is it the right value that you want for the initial value of numerator?


What does this c code output? Really simple and Easy!?

Determine the order of execution of operations in the code below. Determine the sequence actively.





{ int A=9,B=3,C=1;


printf(“%d %d %d %d”, A++,--B,C++,A*B*C);


}








nothing I try working for me on this prob! =(

What does this c code output? Really simple and Easy!?
offhand, I believe its..





9 2 1 27





not sure if i'm right though





edit: I just ran it, I'm right, that is what it is. But if you're in a programing class, this is something you do need to figure out for yourself

dracaena

Help !!what is the problem with this program? (C++)?

I am trying to write a program to give me the divitions of a number but it doesn't work!


can you find the problem?





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


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


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


int main ()


{


clrscr ();


int a,b,m ;


float c;





cin%26gt;%26gt;a;


b=1;


while (a%26lt;b)


{


c=a%b;


if(c==0)


{


cout%26lt;%26lt;b;


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


}


++b;


}


getch();


}

Help !!what is the problem with this program? (C++)?
The problem is that your while statement is wrong. It should be a%26gt;b instead of a%26lt;b.





Second, you shouldn't declare all your variables at the top of your program. This is old C style. In C++, it's better to declare variables as close to where you use them as possible.





Third, you declare but never use m.





Fourth, c is declared as a float, but it should really be an int. But even better, get rid of it altogether. Just put a % b inside the if statement conditional.





instead of:


c = a%b


if (c==0)





just do:


if (a%b==0)





Edit: The above poster is wrong. Although c should not be declared as a float, the modulus operator will always return an integer value.
Reply:I've taken their examples and optimized your code to work with all types of compilers and cleaned up your code a bit.


Enjoy.





#include %26lt;iostream%26gt;


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


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


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





using namespace std;





int main ()


{


system("cls");


int a,b;





cin %26gt;%26gt; a;





b = 1;





while (a %26gt; b)


{


if( a%b == 0 )


{


cout %26lt;%26lt; b %26lt;%26lt; "_";


}


++b;


}


getch();


}
Reply:I think you want the while line to say


while (a %26gt; b)


otherwise it exits immediately


Help with Opening file in C.?

Im having a problem here. I have a little project to do but having some problems. The question simply asks me to prompt the user for a filename. after i get that i need to open the file and read in the information line by line and add the values of some numbers.





This is what I have





#define MAX 30


FILE *ifp;





int main(){





int num;





int scores;


char filename[MAX],c;





printf("Please enter filename to open\n");


scanf("%s",%26amp;filename);





ifp = fopen("filename","r");





fscanf(ifp,"%d",%26amp;num);





while(num!=0)


{





fscanf(ifp, "%d",%26amp;scores);


scores+=scores;


}


printf("scores are: %d\n",scores);











fclose(ifp);








return 0;


}








everytime i try it it shows 0 when printed out onscreen. the file i have only have the number below in that order.





500


345


323

Help with Opening file in C.?
scanf(%s, filename); // yah, you can remove the %26amp;





ifp=fopen(filename,"r"); // remove quotes from filename





fscanf(ifp,"%d",%26amp;num); // if the first num is 500 in your file, you will spin in the loop forever, i.e.





while(num!=0) // no way to get out of this since num == 500
Reply:You should remove the %26amp; character *only* from:


scanf("%s",%26amp;filename);





The while loop will go forever, since you read into num only one time and then it never gets modified.





Replace it with this loop:


while(num!=0)


{


scores+=num;


fscanf(ifp, "%d",%26amp;num);


}


So you keep reading into num, but adding its value to scores, which you have to initialize to 0, so the nums don't get added to some random value that scores may have upon declaration.


int scores = 0;





Oh, and you should read a new num, after you have added the first num read before entering the loop, otherwise you will lose the first value.





That should work. Good luck!





LATER EDIT: check back since I did some mistakes myself!
Reply:You should use


scanf("%s",filename);





You don't need the "%26amp;" because it is already a pointer.





Any array is already a pointer and char is no exception.





I don't see any other problems in there except that you should check ifp after you do the fopen and if it is null then warn that the file was not opened.

morning glory

Fellow c programmers i need HELP!!! with my program?

i need to remove the return statements from my if statment and make the program not continue after the error message. i also need to make else statements that just continue the program.....thank you





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


int main( )


{


float a,b,c,d,e,f;


d=40;


e=1;


f=6.75;


printf("***WAGE CALCULATOR***\n\n") ;


printf("How many hours did you work this week?: ") ;


scanf("%f",%26amp;a);


if (a%26gt;d) {


printf("\nError more then 40 hour.\n",a);


return 0;


}


printf("\nWhat is your hourly wage?: ") ;


scanf("%f",%26amp;b);


if (b%26lt;f) {


printf("\n ERROR value under 6.75 not accepted");


return 1;


}


c=a*b;


printf("\nyour gross salary is: $%f\n",c);











return ( );





}

Fellow c programmers i need HELP!!! with my program?
PROGRAMMING TIP...





WrItE yOuR cODE sO iT Is eASy tO rEaD!!!





Thus changes to be made are all that much easier.





The tab format is lost in the edit box here,


so just align the { } brackets to see the nested if-else statements.


Basic C++ Programming help?

1. 2 * 6 - 5 + 8 % 5


2. 3 * 5 - 19 + 7 % 4


3. 5 * 5 - 19 - 6 % 7


4. 3 * 5 - 12





also, what output will this give me?


int a = 5, b = 4, c = 1 ; if ( a %26lt; b + 1 ) {


printf("Tea, Earl Grey, Hot!\n") ; }


else if ( a %26gt; b + c )


{ printf("Ahead warp factor 9. Engage!\n") ; }


else if ( a % b %26gt;= c )


{ printf("Warp core breach in 20 seconds!\n") ; }


else { printf("I sense a lot of anxiety in this room.\n") ; }





Wrap core break in 20 seconds??





Please help and be so kind to explain if u can. Thanks.

Basic C++ Programming help?
Well, for the first four questions you just have to do the math, and perform the operations in order. The modulus operation (%) returns the remainder in a division problem- for example, 3%2=1 because if you divide 3 by 2 you are left with a remainder of 1.





For the next section, you are correct in that it would print "Warp core break in 20 seconds" since 5%4=1, which makes the statement (5%4%26lt;=1) true in the last else if statement.





Hope that helped!


Dev-C++ Execution Termination?

________________________________________...


Compiler: Default compiler


Building Makefile: "C:\Dev-Cpp\Makefile.win"


Executing make...


make.exe -f "C:\Dev-Cpp\Makefile.win" all


g++.exe -c "Hello code.cpp" -o "Hello code.o" -I"C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/incl... -I"C:/Dev-Cpp/include/c++/3.4.2/backward... -I"C:/Dev-Cpp/include/c++/3.4.2/mingw32" -I"C:/Dev-Cpp/include/c++/3.4.2" -I"C:/Dev-Cpp/include"





g++.exe "Hello code.o" -o "Hello World.exe" -L"C:/Dev-Cpp/lib" -mwindows





g++.exe "Hello code.o" -o "Hello World.exe" -L"C:/Dev-Cpp/lib" -mwindows





Execution terminated


Compilation successful


______________________________________...


That's the compile log.


here is the code.


______________________________________...


// my first program in C++





#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


cout %26lt;%26lt; "Hello World!";


return 0;


}


______________________________________...


What's the problem?

Dev-C++ Execution Termination?
put this code after: cout %26lt;%26lt; "Hello World!"





for example:








#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


cout %26lt;%26lt; "Hello World!";


cin.ignore(256, '\n');


cout %26lt;%26lt; "Press ENTER to continue..." %26lt;%26lt; endl;


cin.get();


return 0;


}





tested on DEV-C++
Reply:TRY THIS:





#include %26lt;iostream%26gt;


using namespace std;





int main ()


{


cout %26lt;%26lt; "Hello World!";


system ("pause");


return 0;


} Report It

Reply:there doesn't appear to be ANY problem. Execution terminated just means that it is finished doing what it is doing. note that it says "Compilation successful" after that. it means it worked. try running the program. it should work just fine.
Reply:Well, FER has the solution and I have the 2 possible explanations.





1. When you ran the program ( Execute / Run ) it probably popped open the DOS box and then closed it so fast that the human eye couldn't see it. It would do this since the line 'return 0;' in main does just that and Windows (being ever so tidy!) cleans it off the screen immediately.





2. On occasion, I've forgotten that I have to actually run it after I compile it!





The fix above holds the DOS box open until you hit a key, any key. Then it will close.


What is the C File Function to delete a letter say, 'A' in a File. Anything like fgetc, fputc etc?

I have developed a program for Bitstuffing. It scans for characters from a file, and if it encounters five 1's continuously, it will append a '0' after it and write to a new file. This concept is called Bit Stuffing. Now, I need to know how to remove that '0' in the file I wrote.


==##CODE ##==


FILE *fp1,*fp2; //Couple of File pointers


int i=0; //Counter


char c; //variable to get char from File


fp1=fopen("bit.txt","r"); //Open file in Read mode


fp2=fopen("b1.txt","w");//Open file in Write mode


while(!feof(fp1))


{


c=fgetc(fp1); //scan char by char till EOF


if(c=='1') i+=1;


else if(c=='0') i=0;


fputc(c,fp2);


if(i==5)


{


fputc('0',fp2); //append 0 after five 1s and reset i


i=0;


}


fclose(fp1);


fclose(fp2);


==## END OF CODE ##==


bit.txt content: 111111


b1.txt content: 1111101





How to remove that 0?





Help would be much appreciaited.

What is the C File Function to delete a letter say, 'A' in a File. Anything like fgetc, fputc etc?
Try this method:


1) Read b1.txt


2) Check for five 1's write the contents of b1.txt into a new file temp.txt


3) Once you have written it . delete b1.txt


4) rename temp.txt as b1.txt





Program


fp3=fopen("temp.txt","w");


rewind(fp2);


i=0;


while(!feof(fp2))


{


if (i%26lt;=5)


{


c=fgetc(fp2);


fputc(c,fp3);


if (c==1)


i++;


if(i==5)


i=0;


}


}


fclose(fp2);


fclose(fp3);


remove("b1.txt");


rename("temp.txt","b1.txt");
Reply:you are most welcome...why dont you send that program to my mail. Its ibndawood@gmail.com. Thanks in advance Happy Programming! Report It

Reply:Or else you may contact a C expert. Check websites like http://getafreelnacer.com/


C++ How do I use a char as a sentinel value when all other inputs are integers? I want the while loop to check

..for the user inputting 'q' or "Q". However, all my other inputs (A, B and C) are integers. I run into a problem when trying to compare them.





#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;cmath%26gt;


using namespace std;





int main()


{


float A, B, C;


float discriminant, denominator, numerator, plusSolution, minusSolution, root;


char SENTINEL = 0;


A = 1;


B = 5;


C = 1;





cout %26lt;%26lt; "This program uses the quadratic formula to solve a quadratic equation.\n"


%26lt;%26lt; "Enter Q to quit.\n";





while (SENTINEL= ('Q' || 'q')) //start sentinel


{


cout %26lt;%26lt; "Please input the A coefficient.\n";


cin %26gt;%26gt; A;


if (A == 0)


{


cout %26lt;%26lt; "Zero Divide.\n";


break;


}


denominator = A * 2;


cout %26lt;%26lt; "Please input the B coefficient.\n";


cin %26gt;%26gt; B;


cout %26lt;%26lt; "Please input the C coefficient.\n";


//to be continued

C++ How do I use a char as a sentinel value when all other inputs are integers? I want the while loop to check
/* I think this should do the trick */


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;cmath%26gt;


using namespace std;





int main()


{


float A, B, C;


float discriminant, denominator, numerator, plusSolution, minusSolution, root;


char SENTINEL;


bool loop = true;


A = 1;


B = 5;


C = 1;


do{


beginloop:





cout %26lt;%26lt; "This program uses the quadratic formula to solve a quadratic equation.\n"


%26lt;%26lt; "Enter Q to quit or C to continue."%26lt;%26lt;endl;


cin%26gt;%26gt;SENTINEL;


if(SENTINEL == 'C' || SENTINEL == 'c'){


/************/


cout %26lt;%26lt; "Please input the A coefficient.\n";


cin %26gt;%26gt; A;


if (A == 0)


{


cout %26lt;%26lt; "Zero Divide.\n";


break;


}


denominator = A * 2;


cout %26lt;%26lt; "Please input the B coefficient.\n";


cin %26gt;%26gt; B;


cout %26lt;%26lt; "Please input the C coefficient.\n";


cin %26gt;%26gt; C;


discriminant = ((B*B) - 4*A*C);





if (discriminant %26lt; 0)


{


cout %26lt;%26lt; "No real roots.\n";


// break; Continue the program. Break gets you out of the While/Do loop


goto beginloop;


}


else if (discriminant %26gt;= 0)


{


root = sqrt(discriminant);


plusSolution = (-B + root)/denominator;


minusSolution = (-B - root)/denominator;


cout %26lt;%26lt; "The solutions are:\n"


%26lt;%26lt; plusSolution %26lt;%26lt; "\n"


%26lt;%26lt; minusSolution %26lt;%26lt; "\n\n";


}


}else{


if( SENTINEL == 'Q' || SENTINEL == 'q') loop = false;else{ goto beginloop;}


}


}while( loop );


/************/


cout%26lt;%26lt; "Press any alpha or numerical key and then the enter key to exit." %26lt;%26lt; endl;


char *pause;


cin%26gt;%26gt;pause;


// system("PAUSE");


return 0;


} //end main function


/* You want to check for the Q or q key before you continue to your main program .... then if it isnt the Q or q check for the */





http://en.wikipedia.org/wiki/Quadratic_e...


C++ increment question?

This program is supposed to create the complete amortization table for a loan given a payment amount, interest rate and number of payments to make. The formula used to calculate this comes out correct when I do it by hand but when I run the program, it gives me the same balance over and over again until the number of payments runs out. I think the problem lies in the incrementing of "e" to go back into the formula.


#include %26lt;iostream%26gt;


#include %26lt;cmath%26gt;


using namespace std;





int main ()


{


double a, b, c, d, e, bm, y;





cout %26lt;%26lt; "Enter payment amount:" %26lt;%26lt; flush;


cin %26gt;%26gt; a;


cout %26lt;%26lt; "Enter interest rate (9% as 0.09):" %26lt;%26lt; flush;


cin %26gt;%26gt; b;


cout %26lt;%26lt; "Enter number of payments:" %26lt;%26lt; flush;


cin %26gt;%26gt; c;





bm = b/12;


y = pow (( 1 + bm ), (e - c));


d = a * (1 - y) / bm;





for (e = 1; e %26lt;= c; e++)





cout %26lt;%26lt; "After payment #" %26lt;%26lt; e %26lt;%26lt; " the balance on the loan is $" %26lt;%26lt; d %26lt;%26lt; endl;


return 0;


}

C++ increment question?
you need the equations inside the for loop.





try it like this:





for (e = 1; e %26lt;= c; e++)


bm = b/12;


y = pow (( 1 + bm ), (e - c));


d = a * (1 - y) / bm;





cout %26lt;%26lt; "After payment #" %26lt;%26lt; e %26lt;%26lt; " the balance on the loan is $" %26lt;%26lt; d %26lt;%26lt; endl;


}
Reply:you are not changing d in the for loop, so it prints the same amount always

sweet pea

C C C C C C C C C C C C C C C c?

I'm using a Xp and turbo c++ compiler and now


void main()


{


int i = 1,j = 2;


printf("%d %d");


getch();


}


when i run the above program the output is





2 1


why??

C C C C C C C C C C C C C C C c?
The program invokes undefined behaviour, anything could happen.





My guess is that what is happening in this case is that as both i and j are local variables they are being created on the stack and when printf is called a pointer to the format string is also created on the stack then the printf function is passed a pointer to that entry.





Now printf is a varargs function and it reads the first argument as requiring two further integers, which it is expecting to find on the stack, but (Because they were not created at function call time (but printf has no way to know that)), it pops the first two available arguments off the stack and prints them.





However this is not required behavious and in fact the behaviour may even change from one run to the next.





Regards, Dan.
Reply:Because you're formatting as a double instead of an integer seems the most logical answer. It's been a long time for me and I never liked C but I had Turbo C once.
Reply:ur program shd be like that


void main()


{


int i=1,j=2;


printf("%d %d",j ,i);


getch();


}


then o/p is like that:-


2 1


else in my thinking there shd be no o/p
Reply:This code will print two random integers on the stdout. printf("%d %d",i,j) will print 1 2 and printf("%d %d",j,i) will print 2 1(simply because this is the output you requested!).
Reply:Compiler dependent...
Reply:You need to tell it which variables you want it to print i.e %i or %j
Reply:You should be getting 19.


A baffling (and probably simple) error in C?

I am compiling my int main, of which the top portion looks like this:


int main()


{


FILE *sourceFile;


sourceFile = fopen("biodata.dat", "r");





if(sourceFile == NULL)


{


printf("Invalid input file.");


system("PAUSE%26gt;NUL");


return 0;


}








int sizeget = 0;


fscanf(sizeget);


const int SIZE = sizeget;





char type[SIZE];


double sum = 0;


int count = 0;


double test = 0;


double temp[SIZE];


char date[12];





... etc etc....





}





Whenever I compile it, I get this error:





C:\Program Files\Miracle C\none.c: line 19: Parse Error, expecting `'}''


'int sizeget = 0'


aborting compile.








If I just insert a random } above it, I get this error message:





C:\Program Files\Miracle C\none.c: line 20: cannot redeclare function


'fscanf(sizeget)'


aborting compile








No idea what's going on... is there some glaring error in my code that I am missing? Any help is appreciated!

A baffling (and probably simple) error in C?
syntax fscanf





fscanf( sourcefile, "%d", %26amp;sizeget);





// hope this helps
Reply:Some compilers don't permit declaring variables in anywhere but immediately after an opening brace '{'.


(C++) How can I get the size of an object from a pointer to a base class?

class Class{


public:


int Something;


};





class DerClass : public Class{


public:


int Array[256];


};





main()


{


Class*C = new DerClass;


sizeof(*C); // = 4


sizeof(DerClass); // = 1028


}





// How can I get 1028 from pointer C?

(C++) How can I get the size of an object from a pointer to a base class?
As far as I know, in c++ it is impossible to get the size of an object just from the base class and sizeof function. One way to get around this is to use dynamic_cast as follows.








struct A {


int a;


virtual ~A() {}


};





struct B : public A {


int b[128];


virtual ~B() {}


};





struct C : public A {


int c[256];


virtual ~C() {}


};





size_t sizeofA(A* a) {


if (dynamic_cast%26lt;C*%26gt;(a))


return sizeof(C);


else if (dynamic_cast%26lt;B*%26gt;(a))


return sizeof(B);


else


return sizeof(A);


}
Reply:sizeof() hard codes size of objects into the program at compile time. Allocated (ie: 'new') memory block sizes are unknown until run time, making sizeof() hopeless to help.





So, don't think it can be done via pointer.


Help in C regarding in filtering?

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





main()


{


int a=0, b=0, c, d, e;





clrscr();


for (c=1; c%26lt;=10; c++)


{


printf("%d + %d = ", c, c);


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








e=c+c;








if (d==e)


{





printf("Right!\n");


a++;


}


else


{


printf("Sorry your answer is wrong. The answer is %d\n", e);


b++;


}


}





printf("\nThe total right answer(s) is %d", a);


printf("\nThe total wrong answer(s) is %d", b);


getch();


}





this program add numbers up to 10...


how can i add a filter that will end the program if i type an alphabet ???


tnx C masters!!!

Help in C regarding in filtering?
This question is an exact duplicate of the question below.

rose

Help in C regarding in filtering?

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





main()


{


int a=0, b=0, c, d, e;





clrscr();


for (c=1; c%26lt;=10; c++)


{


printf("%d + %d = ", c, c);


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








e=c+c;








if (d==e)


{





printf("Right!\n");


a++;


}


else


{


printf("Sorry your answer is wrong. The answer is %d\n", e);


b++;


}


}





printf("\nThe total right answer(s) is %d", a);


printf("\nThe total wrong answer(s) is %d", b);


getch();


}





this program add numbers up to 10...


how can i add a filter that will end the program if i type an alphabet ???


tnx C masters!!!

Help in C regarding in filtering?
The scanf() function returns the number of items it was able to match up, so if it returns 0, then it was unable to match the input to a number.





if ( scanf("%d", %26amp;d) == 0 ) {


// not a number, do something


}


Question in C on structs?

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














typedef struct fccdev


{


int a1;


int b1;





}m8260;














typedef struct fccchan


{


int a;


int b;





m8260 *d;


constint *c;





}m8260chan;














main()


{





m8260 temp,temp1[2];


m8260chan temp23;





printf("\n test \n ");





temp23.a=9;


temp23.b=9;


temp23.c=8;


temp23.d=7;


temp23.d-%26gt;a1=7;








}





/what is the error in this program

Question in C on structs?
temp23.d=7;





here u r assigning the pointer d a value of 7, so this pointer is now pointing to the memory address 7





temp23.d-%26gt;a1=7;





u r trying to access the memory address 7 here, so the program crashes, why? cause u r not allowed to access that location, it is reserved and protected by the oprating system..





in general, assigning literal values to pointers is very dangerous and will mostly crash ur program.
Reply:You can't assign temp23.d to 7, unless 7 is a pointer to a m8260 structure, which it most certainly is not. The d-%26gt;a1=7 statement will crash.
Reply:WHAT! is this a CADD question?
Reply:you can also post you question at http://www.tekpool.com/forums to get answers from a better suited community
Reply:to begin with you don't know proper convention of variable delcaration and function.


C++ problems?

I am trying to brush up on C++, which I haven't used in 5 years. I am having problems with the following. Does anyone see the problem in this code? ("sqr(x) is defined in macro.h)





#include "stdafx.h"


#include "macro.h"


#include %26lt;iostream%26gt;


#include %26lt;cmath%26gt;





using namespace std;





int main()


{


float a, b, c, result;


char side;





cout%26lt;%26lt;"For which side are you trying to solve - a, b, or c? \n";


cin%26gt;%26gt;side;


if (side == 'a')


{


cout %26lt;%26lt; " b = ";


cin %26gt;%26gt; b;


cout %26lt;%26lt; " c = ";


cin %26gt;%26gt; c;


cout %26lt;%26lt; endl;





result = sqrt((sqr(c))-(sqr(b)));


cout %26lt;%26lt; "Side a = "%26lt;%26lt;result%26lt;%26lt;endl;


}





else if (side == 'b')


{


cout %26lt;%26lt; " a = ";


cin %26gt;%26gt; a;


cout %26lt;%26lt; " c = ";


cin %26gt;%26gt; c;


cout %26lt;%26lt; endl;





result = sqrt((sqr(c))-(sqr(a)));


cout %26lt;%26lt; "Side a = "%26lt;%26lt;result%26lt;%26lt;endl;


}


else


{


cout %26lt;%26lt; " a = ";


cin%26gt;%26gt;a;


cout %26lt;%26lt; " b = ";


cin%26gt;%26gt;b;


cout %26lt;%26lt; endl;





result = sqrt((sqr(a))+(sqr(b)));


cout %26lt;%26lt; "Side b = "%26lt;%26lt;result%26lt;%26lt;endl;





}





return 0

C++ problems?
Your parentheses are all messed up.





All three lines of result need to be fixed...or maybe just 2.





You don't need to define a method to do "sqr"





#include %26lt;iostream%26gt;


#include %26lt;cmath%26gt;





using namespace std;





int main()


{


float a, b, c, result;


char side;





cout%26lt;%26lt;"For which side are you trying to solve - a, b, or c? \n";


cin%26gt;%26gt;side;


if (side == 'a')


{


cout %26lt;%26lt; " b = ";


cin %26gt;%26gt; b;


cout %26lt;%26lt; " c = ";


cin %26gt;%26gt; c;


cout %26lt;%26lt; endl;





result = sqrt((c*c)-(b*b));


cout %26lt;%26lt; "Side a = "%26lt;%26lt;result%26lt;%26lt;endl;


}





else if (side == 'b')


{


cout %26lt;%26lt; " a = ";


cin %26gt;%26gt; a;


cout %26lt;%26lt; " c = ";


cin %26gt;%26gt; c;


cout %26lt;%26lt; endl;





result = sqrt((c*c)-(a*a));


cout %26lt;%26lt; "Side a = "%26lt;%26lt;result%26lt;%26lt;endl;


}


else


{


cout %26lt;%26lt; " a = ";


cin%26gt;%26gt;a;


cout %26lt;%26lt; " b = ";


cin%26gt;%26gt;b;


cout %26lt;%26lt; endl;





result = sqrt((a*a)+(b*b));


cout %26lt;%26lt; "Side b = "%26lt;%26lt;result%26lt;%26lt;endl;





}





return 0;


}


C for beginners problem....supposed to determine output of relational operators?

My homework asks "What is the output of the following?" and i'm thinking something is horribly wrong with this code or they skipped this in class.





the only thing vaguely tickling my brain is the true/false (1 or 0) thing. but if that's so, i didn't realize you could assign 1 or 0 to integers using true / false tests.





int main()


{


int a = 3, b = -1, c = 0, i, j, k, n;


i = a || b || c;


j = a %26amp;%26amp; b %26amp;%26amp; c;


k = a || b %26amp;%26amp; c;


n = a %26amp;%26amp; !(b || c);


printf("\ni = %d, j = %d, k = $d, n = %d\n", i, j, k, n);


}

C for beginners problem....supposed to determine output of relational operators?
Actually, this code prints out 1, 0, "$d", and 1 (k's value after "n ="), because you have "k = $d" instead of "%d". The output is:





i = 1, j = 0, k = $d, n = 1





Unless that's your typo, maybe you are being taught the value of matching up printf arguments. :-)





If you meant "%d", it's:





i = 1, j = 0, k = 1, n = 0
Reply:C treats anything other than 0 as true even negative values as true.


so if you write anything like i=2%26amp;%26amp;5 it sets value of i to 1.


so i=1 bcoz a and b are true, but j=0 boz of c which is zero means false.


%26amp;%26amp; operator has higher precedence than || so it is true again and hence k=1.


not operator has highest precedence. b||c=true as b is non zero


!(b||c) is false which when anded with a gives false setting n to 0


hence


your result is


i=1


j=0


k=1


n=0
Reply:C has no real concept of true and false. 0 is false and everything else is true. As a matter of fact and (%26amp;%26amp;) is an operator that says if either operand is 0 then return 0 otherwise return 1. Or (||) is an operator that says if either operand is not zero then return 1 else return 0.





This is the concept your teacher is testing you on with this question.
Reply:i = true


j, k, n = false





I think, just by looking at it.





Now, integers can be booleans; %26lt;= 0 is false (example, 0 and -1 are false, anything 0 or below)


And a true integer is anything above 0.

flowering plum

Help with c/c++?

I have a project in which I have to answer what is wrong with these pieces of code? I am new to C/C++ (know Java)





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;


}





I would like some help on these please.





Thanks,

Help with c/c++?
#1 - should be a class instead of a struct. structs can't have methods defined.





#2 - should be new int [ n ] instead of new int ( n ) - as it is, it allocates one int with value of n, rather than n ints.





#3 - Class A's constructor is not defined.
Reply:Question 1:





The implementation is stupid, but correct. It is wasteful to allocate a int dynamically.





Also, in VC6 the code would be bad because the return from operator new wasn't checked for NULL. VC7 and up conform to the C++ standard which requires new to throw on bad alloc.





Question 2:





This code leaks memory. The allocated arrays are never deleted. Also, the second printf will output a "random" value.





Question 3:





A::a and A::b are never initialized.


Helping with C++ program to compare the value of two letters. please!?

The Question: What does the following statement print?(All variable are of type int.)





- this is in Visual C++ as well





My code so far:





#include %26lt;iostream%26gt;


using namespace std;





int main ()





{


int j;


int k;





if(j %26lt; k)





if (k %26lt; j)


cout %26lt;%26lt;1;


else


cout %26lt;%26lt;2;





else


if (j %26lt; k)


cout %26lt;%26lt; 3;


else


cout %26lt;%26lt;4;





return 0;


}





It keeps returning to me initialized local variables for j and k. When I use char j and char k, it works fine, but I have to compare them as int. It should print 2 if j %26lt; k and 4 otherwise...





Any help please? I have searched around and can't find anything.





Thank you!








In C++ each letter has a numerical value that goes with it, ex j = 56 and k = 57. So my program needs to compare the letters as integers(to compare there numerical value to see which is larger). but I am not supposed to set there values, and I am not supposed to use type char. Does anyone have any idea?





Thanks in advance.

Helping with C++ program to compare the value of two letters. please!?
The cin fstream object only accepts a character array, so cast them as characters frist. Once they're read from the stream, cast them as numerical then compare.





if ((float)j %26lt; (float)k)


{


cout%26lt;%26lt;3;


}


else


{


cout%26lt;%26lt;4;


}


Output of a C++ program?

#include %26lt;iostream%26gt;


using namespace std;


int main()


{


int a = 6, b = 6, c = 20;





if (a++ %26lt;= --b %26amp;%26amp; c != b)


c += 5;


else if (a %26gt;= ++b)


c = a++ * b-- + 3;


else


c += 50;





c = a + b + c - 10;





cout %26lt;%26lt; "a = " %26lt;%26lt; a %26lt;%26lt; endl;


cout %26lt;%26lt; "b = " %26lt;%26lt; b %26lt;%26lt; endl;


cout %26lt;%26lt; "c = " %26lt;%26lt; c %26lt;%26lt; endl;





return 0;


}





Can someone explain to me why the output of a,b, and c is 8,5,and 48 respectively?

Output of a C++ program?
we come to


if (a++ %26lt;= --b %26amp;%26amp; c != b)





first b is pre-decremented


now a=6 b=5 c=20





now the "if" expression is evaluated, which, translates to


(6 %26lt;= 5 %26amp;%26amp; 20 != 5)


which evaluates to false





now the post-increment on a is applied


now a=7 b=5 c=20





since the "if" evaluated false, we now evalutate the "else if"...





first b is pre-incremented


now a=7 b=6 c=20





now the expression is evaluated, which, translates to


(7 %26gt;= 6)


which is true, so we execute the line of code


c = a++ * b-- + 3;


which translates too


c = 7*6+3


now a=7 b=6 c=45


now the post-increment on a is applied, and, the post-decrement on b is applied.


now a=8 b=5 c=45





the "else" is skipped





now c = a + b + c - 10 is executed, which, translates to


c = 8 + 5 + 45 - 10


now a=8 b=5 c=48


How do you obtain the length of a character string in c++?

I'm trying to determine the length of a character string in C++:





char str[ ] = "Hello, world!";


int lengthOfString;


lengthofString = str.length();





doesn't work -- my compiler says that the left side of ".length" requires a class/struct/union type.





What's the correct way to determine the length of a character string in C++?

How do you obtain the length of a character string in c++?
Hi,





Ok. There are two ways of doing what you're doing. First is the one that uses simple character strings.





%26lt;Modified Code -- Start%26gt;


#include %26lt;string.h%26gt; // do this in the start of the file





char str[] = "Hello, world!";


int lengthOfString;


lengthOfString = strlen(str); // this function will return string length of any null-terminated character array


%26lt;Modified Code -- End %26gt;





Second case you've been informed of in previous answers, and they're accurate, so noo need to pass on redundant info :)





Hope this helps. Plus, you need to get a good book on C/C++.
Reply:You are REALLY confused. you are mixing c strings with c++. if you are using a c string(an array of characters), then you need to do things the C way not the c++ way..





your code should be:





#include %26lt;string%26gt;





int main(int argc, char** argv)


{


std::string str="Hello, world!";


int lengthOfString=str.length();


};





the char type just allocates one byte for each element in the array. It is not a class and it does not have any methods. If you need any c++ help(and i assume you do),feel very free to contact me at(iammisc@gmail.com).
Reply:wrong string class


there are C string and C++ string and you're trying to use a C++ string function when you are using a C string.





=======


string str = "Hello, world!";


int lengthOfString;


lengthOfString = str.length();

nil

How to write this specific program in C#?

I'd like to write a C# program in console application.


int starts with value 0


Loops 1000 times and each time it loops, add 2 two to the value.


Can anyone help me out.

How to write this specific program in C#?
for(int i=0;i%26lt;=1000;i=i+2)


{


//Your code here


}





but above programe not run 1000 times


you want 1000 loops use this





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


{


//Your code here


}
Reply:try this code:





int num = 0; //number to be incremented by 2





for (int i=0; i%26lt;1000; i++, num+=2) {





}


Int a[20];?

int a[20];


int b[20]; //Assume a and b have been initialized by


float c[20]; //non-zero values





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


{


c[i]=(b[i+1]-b[i])/(a[i+1...


}





now if i get %26lt;1 solutions for the above operation then c gets stored with 0 for that value. but it is float so it should store 0.4 or 0.5 etc....





using c[i]=float((b[i+1]-b[i])/... dosen't work


but if a and b are declared as float, then the problem is solved and i get decimal values less than one stored in it.





Can anyone explain why?

Int a[20];?
The reason is this, a/b is an integer result if a and b are integers.





Your proposed cast is (float) (a/b) - in this case, you still have the integer division, you have not changed anything.





Try this instead: (float) a / b. In this case a is cast to be a float BEFORE the division, and dividing a float by an integer will be a float division.





Hope this helps.


Numerical question in C code?

A student writes the following C code.


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


int main()


{


float a=1.000002, b=1.000001, result;


result=1./((a-b)*(a-b));


printf("Result = %g\n",result);


return 0;


}


When the code is run the ouput is as follows.


Result = 8.6875e+11





What should the correct result be? Briefly explain why the result produced by the code is so inaccurate. Suggest a way in which the code might be improved.





Is this because there is an underflow error as (a-b)*(a-b) is so small?

Numerical question in C code?
Correct answer is 1e+12





You can rewrite the first line as :





float a=1+(2e-6), b=1+(1e-6), result;





because 2e-6 = 2 * (10^-6) = 2 / (10^6) = 0.000002





so a-b = 1e-6 so (a-b) * (a-b) = 1e-12





Finally 1/((a-b)*(a-b)) = 1e+12





You can check this easily by changing the first line





float a=1.000002, b=1.000001, result;





to





double a=1.000002, b=1.000001, result;





This question is highly dependent on the platform, but assuming that the platform has a more precise double than float then here is your explanation:





The size of the floating point value does not contain enough bits to retain the precision for the calculation so the division ends up using truncated values and the result is not accurate.





Floating point values in general are less precise than double precision values. This is because they use less bits to hold the exponent and the significant part of the number than a double does.





A real easy way to see how precise your platform is :





Keep changing the precision of the numbers on the first line.





So start with





float a=1.2, b=1.1, result;





So far so good - the floating point value has enough bits to containing the required precision of the calculation.





now keep going until you get to the original code:





float a=1.02, b=1.01, result;


float a=1.002, b=1.001, result;


float a=1.0002, b=1.0001, result;


float a=1.00002, b=1.00001, result;





You can see the floating point value result is gradually losing precision because it does not use enough bits to retain the accuracy for the calculation.





In general the size of a double %26gt;= size of a float which normally means a double uses more bits for its calculations and is therefore more precise.





So the improvement is to use double instead of float.


What is the output of C++ pointer variables with cout?

Consider the following program:





#include %26lt;iostream%26gt;





using namespace std;





void f(char* %26amp;c);


void g(char* myString);





int main()


{


char myString[10] = "Midterm";


char *tempPtr;





tempPtr=myString;


cout %26lt;%26lt; myString %26lt;%26lt; endl;


cout %26lt;%26lt; tempPtr %26lt;%26lt; endl;


g(myString);


g(tempPtr);


f(tempPtr);


cout %26lt;%26lt; myString %26lt;%26lt; endl;


cout %26lt;%26lt; tempPtr %26lt;%26lt; endl;


return 0;


}





void f(char* %26amp;s)


{


s=s+3;


cout %26lt;%26lt; s %26lt;%26lt; endl;


}





void g(char* myString)


{


myString=myString+5;


cout %26lt;%26lt; myString %26lt;%26lt; endl;


}





On gnu compilers, this is the output:





Midterm


Midterm


rm


rm


term


Midterm


term





Now, my question is, are there any implementations of C++ that only output what the pointer variable is pointing to? (i.e. not including the the following characters of the array?)





For example, are there any implementations that would make this be the output:





Midterm


M


rm


r


t


Midterm


t





Any light on how pointer variables are output will be appreciated!!!

What is the output of C++ pointer variables with cout?
No, cout will always print all the characters of char*'s until it hits a null.





You need to dereference the char* to an individual character before cout'ing it to get what you want:





char str[10] = "Midterm";


cout %26lt;%26lt; *(str+3) %26lt;%26lt; endl; // This outputs 't'
Reply:No.





And while cout function is included with most compilers it is NOT part of the language, but just a library of standard code people find useful to use.


(eg I can use c/c++ to code for my nokia phone but as there a gui and no commandline there no cout function provided in the dev kit!)





You need to change your code not the compiler of course!!! Just tested and MS Compiler gives same results, as you should expect!





C/C++ work with null terminated strings. And arrays are treated in many ways as little more than your tempPtr pointer.





So you reserved 10 bytes for your string, the first 7 chars are the letters then theres a 0/null byte, and the next 2 bytes are uninitilised(we cant be sure what values they could take at runtme.





Now cout treats any pointer to or array of chars the same it output the charaters in the order it finds them until it comes to a null valued byte. if we initialse out array as say {M','i','d','t','e','r','m'} we'd need to add a ,0 or cout would just keep going through memory writing what if finds until it eventually finds a zero or the program crashes(the OS should throw an exception if tries to read outside the part of memory given to your program)





If given a char though not a pointer to a char then it'll give just that char.





Eg.


cout *(myString+1);


prints only the letter "i"


and


cout %26amp;myString;


shows the memory address used for myString.





Remember the referencing and dereferencing operators?





Wait - but for more than one char to be output but not the whoile string you need a suitably sized buffer(the final substring size + 1 char for the null) and would memcopy the bytes into it and the set a null at the end before sending it to cout.

sp