answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

What is the difference between c and c plus plus and c minus minus?

The main difference between the two is that C++ is an object oriented programming language while C is a structured programming language. Although C++ is derived from C, they are in fact completely separate languages that share a common syntax. However, C++ is backwardly compatible with C so while you may include C-style code within C++ programs, you cannot include C++ code in C programs.

Write a C program for the following Create a structure employee and accept its data members such as employee name and gender and age and martial status and no of children from the key board and write?

#include
#include
#include

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::toupper;


struct Employee
{
string getFullName()
{
return (firstName + " " + lastName);

}


string getGender()
{
if (toupper(gender) == 'M')
{
return ("Male");

}
else if (toupper(gender) == 'F')
{
return ("Female");

}
else
{
return ("Gender was not specified");

}

}



int getAge()
{
return age;

}


string getMartialStatus()
{
if (toupper(martial_status) == 'M')
{
return ("Married");

}

else if (toupper(martial_status) == 'S')
{
return ("Single");

}

else
{
return ("Martial status is not defined!");

}

}


int getNumberOfChildren()
{
return numberOfChildren;

}



string firstName;
string lastName;
char gender;
int age;
char martial_status;
int numberOfChildren;

};

int main()
{
Employee newEmployee;

cout << endl << "Enter first name: ";
getline(cin, newEmployee.firstName);

cout << endl << "Enter last name: ";
getline(cin, newEmployee.lastName);

cout << endl << "Enter gender (M for Male and F for Female): ";
cin >> newEmployee.gender;

cout << endl << "Enter age: ";
cin >> newEmployee.age;

cout << endl << "Enter martial status (M for married and S for single): ";
cin >> newEmployee.martial_status;

cout << endl << "Enter number of children: ";
cin >> newEmployee.numberOfChildren;

cout << endl << "Employee's full name: " << newEmployee.getFullName()
<< endl << "Gender: " << newEmployee.getGender()
<< endl << "Age: " << newEmployee.getAge()
<< endl << "Martial status: " << newEmployee.getMartialStatus()
<< endl << "Children: " << newEmployee.getNumberOfChildren()
<< endl;

system("PAUSE");
return 0;

}

Ask the user to input the radius and compute of the area of circle given the pie equals 3.14 in dev-c plus plus?

#include <iostream>

// Required to calculate pi more accurately:

//#include <math.h>

int main()

{

const double pi = 3.14;

// To calculate pi more accurately, use:

// const double pi = 4*atan(1.0);

double r;

while( 1 )

{

printf( "Calculate the area of a circle.\n" );

printf( "Enter 0 to exit.\n" );

printf( "Enter the circle's radius: " );

if( std::cin >> r )

{

if( !r )

{

printf( "\n" );

break;

}

printf( "Area of circle is: %.2f\n\n", pi * r * r );

}

else

{

printf( "Invalid input. Please try again.\n\n" );

std::cin.clear();

while( std::cin.get() != '\n' ) ;

}

}

return( 0 );

}

Write a program that takes a five digit binary number from user and prints the number with inverted bits?

#include<iostream>

#include<string>

int main()

{

std::string input, invert;

bool ok = false;

while (!ok)

{

std::cout << "Enter a 5-digit binary number:";

std::getline (std::cin, input);

if (input.size()==5)

{

invert = input;

ok = true;

for (auto c = invert.begin(); c!=invert.end(); ++c)

{

switch (*c)

{

case ('1'): *c = '0'; break;

case ('0'): *c = '1'; break;

default: ok = false;

}

}

}

if (!ok)

{

std::cout << "Bad input\n";

invert.clear();

input.clear();

}

}

std::cout << "Input:\t" << input << std::endl;

std::cout << "Invert:\t" << invert << std::endl;

}

What is the difference between character '1' and integer 1 in terms of C plus plus?

Characters and integers are two different types: 'char' is an 8-bit unsigned integer (normally), while 'int' is a 16, 32 or 64-bit signed integer.

Ints and chars are both integer numbers internally, but their numeric values are interpreted differently: The numeric value of the integer 1 is 1 (reasonably enough :), while the numeric value of the character '1' is 49.

Characters are represented in computers by using a table mapping from integers to characters. The most common mapping is ASCII, and in the ASCII table the character 1 happens to have the numeric value 49. (I assume they didn't put it on 1 because all the values below 32 were reserved for system commands like 'bell' and 'escape'.)

See related link for the ASCII table.

How do you make a division problem in c programming go into a decimal?

When dividing one integer with another, there's a high probability that the answer will not be an integer. To deal with this, you must cast the numerator or denominator to a floating point type (float or double). By way of an example, consider the following code snippet:

int x=5, y=2;

int z = x/y;

float f1 = x/y;

float f2 = ( float ) x/y;

float f3 = x/( float ) y;

printf( "x=%d, y=%d, z=%d, f1=%f, f2=%f, f3=%f\n", x, y, z, f1, f2, f3 );

Output:

x=5, y=2, z=2, f1=2.000000, f2=2.500000, f3=2.500000

Clearly the correct answer is shown by f2 and f3. This is because we explicitly cast the numerator or denominator in each case. So long as we cast one or the other (or both), the result will be correct. If we don't cast either, then we're effectively only converting the result of the integer division, which is effectively the same as casting z to a float, as shown by f1.

See the related links section for in-depth information on floating point arithmetic in C/C++.

When the destructor may be invoked in c?

C is not an object-oriented language -- there are no destructors.

In C++, however, an object's destructor is invoked automatically when the object falls from scope. The destructor can also be invoked by manually deleting a raw pointer to the object (or one of its base classes), however you should only ever use the delete operator if the object was instantiated with the new operator, and only after all references or pointers to the object have fallen from scope. The safest way to manage raw pointers is to use a resource handle or smart pointer.

Is it necessary to include stdioh header file in a C compiler if you use printf function in your code?

### posted by Pulkit and Puneet from D.Y.Patil college/pune The ans is NO......... bcoz c compiler already contains the basic functions of STDIO.H in its code segment. ok guys..... ### posted by Pulkit and Puneet from D.Y.Patil college/pune The ans is NO......... bcoz c compiler already contains the basic functions of STDIO.H in its code segment. ok guys.....

How do you write a program in C plus plus for slugging percentage?

#include

#include

#include

using namespace std;

string ask(string prompt)

{

string input;

cout<

getline(cin, input);

return(input);

}

int ask_for_int(string prompt)

{

int input;

while(1)

{

string response = ask(prompt);

stringstream s(response);

if(s>>input)

return(input);

cout<<"Invalid input."<

}

}

int main()

{

cout<<"Slugging percentage calculator\n"<

while(1)

{

int at_bats = ask_for_int("How many at bats? ");

int singles = ask_for_int("How many singles? ");

int doubles = ask_for_int("How many doubles? ");

int triples = ask_for_int("How many triples? ");

int home_runs = ask_for_int("How many home runs? ");

int total_hits = singles + doubles + triples + home_runs;

if( total_hits <= at_bats )

{

double slg = ((double)( singles+(2*doubles)+(3*triples)+(4*home_runs)))/at_bats;

cout<<"\nSLG = "<

break;

}

cout<<"Invalid input.\nReason: the total hits exceeds the at bats."<

cout<<"Please re-enter data."<

}

}

Output

Slugging percentage calculator

How many at bats? 458

How many singles? 73

How many doubles? 36

How many triples? 9

How many home runs? 54

SLG = 0.847162

How do you take input in graphics mode in c plus plus?

C++ has no graphics ability whatsoever. C++ is a machine-independent programming language, but graphics are machine-dependent. To use graphics in C++ you must use an appropriate library. If you need cross-platform support, you must use a generic library. Each library has its own specific methods for accepting input thus you must consult the library documentation for more information on this aspect.

Write a program in c plus plus to read 2 numbers and an operator then calculate result defined of this operator?

#include<iostream>

#include<string>

#include<sstream>

unsigned input_num (std::string prompt)

{

unsigned id = 0;

while (1)

{

std::cout<<prompt<<": ";

std::string input="";

getline (std::cin, input);

std::stringstream ss (input);

if (ss>>id)

break;

std::cout<<"Invalid input.\n";

}

return (id);

}

char input_op (std::string ops)

{

char op = 0;

while (1)

{

std::cout<<"Enter an operator ("<<ops<<"): ";

std::string input="";

getline (std::cin, input);

std::stringstream ss (input);

if (ss>>op && ops.find (op) != std::string::npos)

break;

std::cout<<"Invalid input.\n";

}

return (op);

}

int main()

{

unsigned num1 = input_num ("Enter a number");

unsigned num2 = input_num ("Enter another number");

// division is invalid if num2 is zero

char op = input_op (num2?"+-*/":"+-*");

unsigned result = 0;

switch (op)

{

case ('+'): result = num1+num2; break;

case ('-'): result = num1-num2; break;

case ('*'): result = num1*num2; break;

case ('/'): result = num1/num2;

}

std::cout<<num1<<op<<num2<<'='<<result<<std::endl;

}

What accurately describes the grammar of a conditional-statement in c plus plus?

if (conditional_statement) {

//Code to execute if true

}

if (conditional_statement) {

//Code to execute if true

} else {

//Code to execute if false

}

if (conditional_statement) {

//Code to execute if true

} else if (another_conditional_statement) {

//Code to execute of the second conditional statement is true

} else {

//Code to execute if neither statement is true

}

There are a few things to note about if statements that might be helpful:

  • You can have as many 'else if' declarations in an 'if' statement as you want (These are called stacked if's)
  • You can specify an if statement without the curly braces ('{' and '}') if there is only one line of code. For example:

    if (x > 10) x = 0;

    This will set x back to 0 if it is greater than 10, just like a normal 'if' statement but without the curly braces.

  • As a result of this, 'else if', to the compiler, is not special at all. An 'if/else-if/else' statement is actually just two 'if/else' statements stacked on top of one another, where the 'else' doesn't have curly braces (hence the term "stacked if statement").

    To demonstrate, the following two if statements are actually interpreted exactly the same by the compiler:

    if (x -10) {

    x = 0;

    } else {

    x++; //Increment x;

    }

    }

How do you program a vending machine using c plus plus?

Assuming you are taking an object-oriented approach (which I recommend), first identify the various objects involved (for example, "CoinSlot", "ProductRow", "ProductSelectButton", etc.) Then, for each of those, identify their attributes and methods. For example, an attribute of CoinSlot might be CoinAmountInserted and methods might include CoinInserted and CollectCoins.

C plus plus class of rational numbers in which multiplication and division occur?

The following program implements a user-defined class for rational numbers, including operator overloads for all arithmetic operations (+, -, * and /).

Note that the class does not handle 0/n fractions properly because the reciprocal of 0/n is n/0 which is an invalid fraction with undefined value. The problem is that 0/n fractions are perfectly valid (1/2 - 1/2 = 0/2) so you need to cater for them (they simplify to zero), but you cannot divide by them. It is left as an exercise for the reader to provide handlers to cater for this type of exception.

#include<iostream>

#include<string>

#include<sstream>

// GCF: greatest common factor (AKA: GCD, greatest common divisor)

int gcf (int a, int b)

{

// Recursive Euclid algorithm.

return (b != 0 ) ? gcf (b, a % b) : a;

}

// LCM: least common multiple

int lcm(int a, int b)

{

return (b / gcf (a, b)) * a;

}

// Class to store rational numbers (fractions).

class rational

{

friend std::ostream& operator<< (std::ostream&, const rational&);

private:

int m_p;

int m_q;

public:

rational (const int = 1, const int = 1);

rational (const rational&);

rational (const std::string& str);

rational (const char* c_str);

rational& operator= (const rational&);

rational& operator= (const std::string&);

rational& operator= (const char*);

rational& operator-= (const rational&);

rational& operator*= (const rational&);

rational& operator/= (const rational&);

rational& operator+= (const rational&);

rational operator- (const rational&);

rational operator* (const rational&);

rational operator/ (const rational&);

rational operator+ (const rational&);

rational reciprocal() const;

rational& simplify ();

rational& unsimplify (int multiple);

bool operator slash_pos)

{

std::string p = str.substr (0, slash_pos++);

std::string q = str.substr (slash_pos, str.size()-slash_pos);

std::stringstream ssp (p);

std::stringstream ssq (q);

int ip;

int iq;

if (ssp >> ip && ssq >> iq && iq != 0)

{

m_p = ip;

m_q = iq;

return *this;

}

}

}

return *this;

}

// Equality operator.

bool rational::operator== (const rational& other) const

{

// Simplify both fractions before comparing.

rational copy (*this);

rational temp (other);

copy.simplify();

temp.simplify();

return copy.m_p==temp.m_p && copy.m_q==temp.m_q;

}

// Return the reciprocal by value (swap numerator/denominator)

rational rational::reciprocal() const

{

return rational (m_q, m_p);

}

// Simplifies the fraction.

rational& rational::simplify()

{

// Simplify the sign.

if (m_q<0)

{

m_p *= -1;

m_q *= -1;

}

int factor = gcf (this->m_p, this->m_q);

this->m_p /= factor;

this->m_q /= factor;

return *this;

}

// Usimplifies the fraction (use given denominator)

rational& rational::unsimplify (int denominator)

{

this->m_p *= denominator / m_q;

this->m_q = denominator;

return *this;

}

// Test drive the rational class.

int main()

{

// Test arithmetic.

rational a = "1/2";

rational b (2, 5); // e.g., "2/5"

std::cout << a << " + " << b << " = " << a + b << std::endl;

std::cout << a << " - " << b << " = " << a - b << std::endl;

std::cout << a << " * " << b << " = " << a * b << std::endl;

std::cout << a << " / " << b << " = " << a / b << std::endl;

// Test simplifier on negatives and integers.

rational c (2, -5); // -2/5

rational d (-2, -5); // 2/5

rational e (3, -1); // -3

std::cout << c << " simplified is ";

std::cout << c.simplify() << std::endl;

std::cout << d << " simplified is ";

std::cout << d.simplify() << std::endl;

std::cout << e << " simplified is ";

std::cout << e.simplify() << std::endl;

}

What if -1 is assigned to a unsigned variable in C plus plus?

If you assign -1 to a unsigned variable it will contain the biggest number its able to hold.

For example if you assign -1 to a unsigned int it will be 4294967295 as its the biggest number a unsigned int can hold.

What is the difference between an integer and a Boolean variable?

An integer stores a whole number. The exact range depends on the language; in Java, "int" stores whole numbers in a range of approximately minus 2 billion to plus to billion.

A boolean variable, on the other hand, stores only one of two values - these are often called "true" and "false" (as in Java). Boolean variables are often used to keep track of information that can be thought of as a reply to a "yes/no" question. For example, to mark whether a certain item is active or not you have only two choices, so it makes sense to use a boolean variable.

What is pre increment and post increment in c language?

Short Answer

The short answer is that both the prefix increment and postfix increment operators will increment the operand. The difference is not so much the operation but the evaluation of the operation. Prefix increment evaluates as a reference to the operand itself, after it is incremented. Postfix increment evaluates to a reference to the operand (or its value) before it was incremented. The same principal applies to prefix decrement and postfix decrement operators.

Long Answer

The first thing to bear in mind is that operators not only perform an operation upon one or more operands, the expression must also be evaluated. In other words, the expression must return a value to the caller, even if we choose to ignore that value (by not storing it).

Consider the following increment expressions which both ignore the evaluation:

int x = 1, int y = 1;

++x; // prefix increment.

y++; // postfix increment.

Both x and y are incremented, as you would rightly expect, so they are both 2 when the expressions are evaluated. But by ignoring the result of those evaluations it's impossible to actually see any difference between these two expressions. So let's re-evaluate these expressions:

int x = 1, int y = 1;

int eval_x = ++x;

int eval_y = y++;

Now the evaluations cannot be ignored because we've immediately assigned them to the variables eval_x and eval_y. Both x and y are still incremented, just as before, but while eval_x is assigned the value 2 (the new value of x), eval_y is assigned the value 1 (the old value of y).

Clearly the two expressions perform exactly the same operation upon x and y (incrementing them), but they evaluate quite differently.

The prefix increment operator is the easiest of the two to understand. The evaluation of any prefix increment upon any operand is always a reference to the operand itself. Since the operand is incremented by the operator, assigning the evaluation of the operator to another variable (by reference) effectively assigns the incremented value to that variable.

This is really no different to saying eval_x = ( x = x + 1 ). It looks complicated but its really simple if we evaluate it as the computer evaluates it, from right to left. If x is 1 then x + 1 evaluates to 1 + 1 which evaluates to 2. Thus the equation reduces to eval_x = ( x = 2 ). x = 2 is an assignment not only gives x the value 2, it evaluates as a reference to x. Thus the final expression is eval_x = x, thus eval_x is assigned the value of x, which is 2. We can safely ignore the fact eval_x = x evaluates as a reference to eval_x, as the expression is now fully evaluated. The upshot is that eval_x 2.

Still with me?

The postfix increment operator is more complex. It cannot be evaluated in the same way because the evaluation of y++ requires that y be incremented (y = y + 1), but the evaluation of y++ cannot be a reference to y because we are not remotely interested in the incremented value of y, we're interested in what it was before being incremented. To achieve this we need to imagine there's a temporary variable involved:

int y=1;

int temp = y;

y = y + 1;

int eval_y = temp;

Although this is a fair representation, it is not an accurate one. It would be too easy to assume that postfix increment incurs a penalty by virtue of the temporary variable. But while it is certainly true that postfix operators on an object (an instance of a class) will incur a performance penalty, the same is not true of primitive data types such as int. This is simply because primitive data types do not require temporary variables to perform a postfix operation.

To understand why, remember that the CPU has several registers available for processing and for storing return values (which could be an address or an actual value). The compiler can generate code that will store the current value of y in a return register and operate upon a reference to y in another register. The evaluation is already pre-empted because it already exists in the return register, so no temporary is actually required, and therefore no penalty incurred.

In other words, y++ is no slower or faster than ++x when x and y are both primitives.

Classes are a different matter altogether. We cannot use CPU trickery to optimise a postfix operator upon an object (we'd need a hugely dynamic register model which is impossible to implement in hardware -- but I live in hope :-), so we are forced to make a copy. And since classes are generally larger than primitive data types, that can be an expensive hobby if we're in the habit of using postfix operators upon primitives. If the return value (the evaluation) is of no consequence, it's far too easy to use postfix operators in for() loops and such like. But it's a hard habit to break and you end up using postfix for just about everything, whether you want the previous value or not, resulting in objects being copied but never actually used. If you can get into the habit of using prefix operators at all times, even for primitives, and use postfix only when you actually need the previous value, your code will be that little bit more spritely. If you can't break the habit, or choose not to, put simple traces in your copy constructors. I guarantee you'll be prefixing by default in no time.

To finish off, here's a simple class that implements prefix and postfix increment operators. Note how both implementations actually employ prefix operators but, more importantly, that the postfix operator must make a temporary copy of the current instance (with a tell-tale tracer in the copy constructor). Finally, note that both operators return references, not values. Despite the advice given elsewhere (you know who you are!), never return an object by value unless you absolutely must. Many sites will advise that postfix operators should "always" return by value. But if you do this, you will not only pay a penalty for making a temporary copy (which is unavoidable in non-primitives), you pay the penalty twice over by copying the temporary copy!

#include

class cNum

{

public:

cNum(): m_data( 0 ){}

cNum( int data ): m_data( data ){}

cNum( const cNum & num ): m_data( num.m_data ){ printf( "Copying!\n" ); }

public:

cNum & operator++ (){ ++m_data; return( *this ); } // prefix

cNum & operator++ ( int ){ cNum * tmp = new cNum( *this ); ++m_data; return( *tmp ); } // postfix

cNum & operator= ( const cNum & num ){ m_data = num.m_data; return( *this ); }

public:

int GetData() const { return( m_data ); }

private:

int m_data;

};

int main()

{

cNum num( 25 ), eval;

printf( "Initial values:\n" );

printf( "num: %d, eval: %d\n\n", num.GetData(), eval.GetData() );

printf( "Calling prefix increment:\n" );

eval = ++num;

printf( "num: %d, eval: %d\n\n", num.GetData(), eval.GetData() );

printf( "Calling postfix increment:\n" );

eval = num++;

printf( "num: %d, eval: %d\n\n", num.GetData(), eval.GetData() );

printf( "Calling prefix increment (ignoring evaluation):\n" );

++num;

printf( "num: %d, eval: %d\n\n", num.GetData(), eval.GetData() );

printf( "Calling postfix increment (ignoring evaluation):\n" );

num++;

printf( "num: %d, eval: %d\n\n", num.GetData(), eval.GetData() );

return( 0 );

}

What are the advantages and disadvantages of polymorphism and inheritance?

Answer

the biggest advantage lies in creation of reusable code by programmers, you dont care about the specific objects used just like driving a car without knowing what plugs are in the engine. multiple forms of one object are called in the same way

Why use static data when you can use global data in the class in C plus plus?

Global data are used only as a last resort. It's highly recommended not use global data in your programs because sometimes it's really hard to avoid name clashing. And as result to track such problem down.

Write a function that counts the number of occurrences of a pair of letters in a string using c plus plus. For example the pair ab apears twice in abaacbaxabb?

//i don't think it would be a tough job to get this in c++

#include<stdio.h>

#include<string.h>

int number();

char str[20],pair[3];

main()

{

puts("enter the string");

scanf("%s",str);

puts("enter the pair of letters to be scanned");

scanf("%s",pair);

printf("%d is the no of occurences",number());

}

int number()

{

int nmbr=0,i;

char str1[3];;

for(i=0;str[i]!='\0';i++)

{

str1[0]=str[i];

str1[1]=str[i+1];str1[2]='\0';

if(strcmp(str1,pair)==0)

nmbr++;

}

return nmbr;

}

How is a bitwise copy made in c plus plus?

A bitwise copy is what you automatically get when you do not provide a copy constructor. The compiler simply provides code that copies the object without regard to the type of the members. This is dangerous if any of the members happen to be pointers, because then you have two pointers to the same object and, if you delete one, you wind up having the other pointing to an object that has been deleted.