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 binary file and text file?

The difference is that text files may only contain printable character codes, either from the ASCII character set or the UNICODE character set. That is, letters, digits, punctuation, space, tab and other symbols, including line feed or carriage return/line feed pairs. Non-printable characters, such as the null character '\0' (or '\0\0' in UNICODE), are not permitted in plain-text files, however UNICODE files permit a 16-bit endian marker at the start of the file to denote the byte order of the wide characters that follow.

Text files can be displayed in any plain-text editor or word processor (as unformatted text). The entire text can also be extracted as a string (memory permitting), or as a stream of printable characters in a string buffer.

Binary files, on the other hand, cannot be interpreted as plain-text (although they may contain plain text elements). Binary files may contain any combination of bytes, and require special handling in order to be interpreted correctly. The exact meaning of the order of the bytes is entirely dependent upon the program that created the binary files in the first place.

Can int value be assigned to char variable?

Yes, but the results may not be what you expect, depending on the relative sizes of an int and a char (in bytes), whether they are signed or unsigned, and whether they use big-endian notation or not.

By way of an example, in C++ an int is typically 4 bytes long while a char is 1 byte long. Both are signed by default. If you were to loop an integer from 0x80000000 to 0x7fffffff (-2147483648 to +2147483647) using big-endian notation and assign the value to a signed char, then the char would repeatedly cycle through the values 0 to 127, then -128 to 0. This is because the char takes on the value of the least-significant byte of the integer in big-endien notation (the bytes are effectively reversed in memory). However, if you cycle the int from 0xffffff80 to 0x7f (-128 to +127), then you get the expected behaviour (the char cycles from -128 to +127). However, if the char were unsigned, then the first loop would repeatedly cycle from 0 to 255 while the second would cycle from 128 to 255, and then from 0 to 127.

Thus to get the expected behaviour, both the int and char must both be signed or both must be unsigned, and the range of values must be within the range of the smaller of the two types (which will typically be the char), and the system must either use big-endian notation (reverse notation) or must otherwise compensate for little-endian notation.

What are uses of do while?

A do-while loop is only useful when you want the loop to execute at least once. This is because the conditional expression is evaluated at the end of each iteration, rather than before each each iteration as it is in a for and a while loop.

Write a program to solve a quadratic equation using the quadratic formula in c plus plus?

#include<stdio.h> #include<conio.h>

void main()

{

float a,b,c,z,d,x,y;

clrscr();

printf("Enter the value of a,b,c");

scanf("%f %f %f",&a,&b,&c);

d=((b*b)-(4*a*c));

z=sqrt(d);

x=(-b+z)/(2*a);

y=(-b+z)/(2*a);

printf("The Quadratic equation is x=%f and y=%f",x,y);

getch();

}

This answer does not think about imaginary roots. I am a beginner in C programming. There might be flaws in my code. But, it does well.

the code is

#include<stdio.h>

#include<math.h>

main()

{

float a, b, c;

float dis, sqdis, real, imag, root1, root2;

printf("This program calculates two roots of quadratic equation of the form ax2+bx+c=0.\n");

printf("\n");

printf(" please type the coefficients a, b and c\n");

printf("\n");

printf("a = ");

scanf("%f", &a);

printf("\n");

printf("b = ");

scanf("%f", &b);

printf("\n");

printf("c = ");

scanf("%f", &c);

printf("\n");

dis = (b*b-4*a*c);

if(dis < 0)

{

sqdis = sqrt(-dis);

real = -b/(2*a);

imag = sqdis/(2*a);

printf(" The roots of the quadratic equations are \n x1\t=\t %f + %f i\n x2\t=\t %f -

%f i\n", real, imag, real, imag);

}

else

{

sqdis = sqrt(dis);

root1 = -b/(2*a)+sqdis/(2*a);

root2 = -b/(2*a)-sqdis/(2*a);

printf("The two roots of the quadratic equations are %f and %f.\n", root1, root2);

}

system("pause");

}

What is the advantage and disadvantage of constructor in c plus plus?

Objects allow you to establish invariants and limit the type of operations that can be performed upon the internal representation of the object, exposing only as much as is needed to use the object -- no more and no less. This greatly reduces the chances of the programmer making an error, creating more robust code more easily and with fewer runtime checks and much greater efficiency.

What is dangling pointer reference?

Whenever memory that was in use, and was referred to by a pointer variable, is freed, and the pointer variable is not updated accordingly (setting it to NULL, for example), the pointer variable is considerred to be a dangling pointer reference.

What are the advantages of the recursion in c plus plus?

Any problem that can be solved by dividing the problem into smaller problems of the same type is a good candidate for recursion. However, there are actually very few applications that cannot be resolved more efficiently with an iterative loop. It therefore pays to know when recursion is unavoidable and when it is optional.

The main benefit to recursion is that each instance of the function maintains its own set of non-static local variables completely independently of all other instances. But if these variables are of no use to the function when a recursive call returns, then an iterative implementation would be more efficient. Function calls are expensive in terms of memory consumption and performance, so the fewer we make, the better.

A classic example of recursive application is the quicksort algorithm. In simple terms, quicksort is a function that accepts a subset of data. The data is usually stored in an array and the function accepts the left and right index of the subset to be sorted. Initially this will be lower and upper bounds of the entire array, but if the indices indicate a subset with fewer than 2 items, the function immediately exits. This effectively defines the return path from the recursions.

Assuming there are 2 or more items, the function selects one of the items (the pivot) and then sorts the array such that items less than the pivot are placed to its left, and items greater or equal to its right. This moves the pivot into its final position, but the items on either side may still be unsorted. Thus the function calls itself twice, once for each of these subsets, which gradually reduces the problem down into smaller and smaller subsets until a subset has fewer than 2 items, at which point the recursion unwinds to the previous instance.

Recursion is required because when the first recursive call returns, the subset to the left of the pivot is guaranteed to be sorted, but the subset to the right is not. This means we must maintain local variables in order to determine the lower and upper bounds of that subset.

Although quicksort is an elegant application of recursion, there is still room for improvement. Firstly, it is better to make a recursive call upon the smaller of the two subsets. The smaller the subset, the fewer recursions that will be incurred sorting it.

Secondly, since the second recursion is also the last statement in the function, there is no need to maintain the local variables when it returns. Thus the second recursion can be implemented as a tail call. This effectively means we modify the existing local variables to suit and then recall the same instance (with a goto). This reduces the depth of recursion by one function call per recursion which will quickly add up to a significant boost in efficiency.

In a header file whether functions are declared or defined?

Ideally, functions should only be declared in a header and defined in a translation unit (source file) that includes the header. However, trivial functions are often defined in a header as they are usually good candidates for inline expansion, but you must remember to declare the function inline. Often it is better to forward declare inline functions so that maintainers are not distracted by the implementation details which can be placed towards the end of the header, out of the way. However, a definition is also a declaration, so forward declaring an inline function is not a requirement unless there is a cyclic dependency issue where a forward declaration is necessary to break the cycle.

In c plus plus Write a program that takes a decimal number input from the user and displays its binary number?

The following code will convert any number in any base to any other base, from binary to hexadecimal, and everything inbetween.

#include<iostream>

#include<string>

#include<sstream>

typedef unsigned long long ull;

typedef unsigned long ul;

const std::string symbols="0123456789abcdef";

std::string inputvalue(ul base)

{

using namespace std;

string value;

while(1)

{

cout<<"Enter a positive value : ";

string s;

getline(cin,s);

if(s.size())

{

for(string::iterator i=s.begin();i!=s.end();++i)

if(*i>='A' && *i<='Z')

*i+=32;

string actual = symbols.substr(0,base);

if(s.find_first_not_of(actual)!=string::npos)

{

cout<<"The value you entered is invalid for the base.\n"

<<"Please enter another value.\n"<<endl;

continue;

}

value=s;

break;

}

}

return(value);

}

ul inputbase(std::string prompt)

{

using namespace std;

ul result=0, min=2, max=16;

while(1)

{

cout<<prompt.c_str()<<" ["<<min<<".."<<max<<"] : ";

string s;

getline(cin,s);

if(s.size())

result=stoul(s,0,10);

if(result<min result>max)

cout<<"The base must be in the range "

<<min<<".."<<max<<"\n"

<<"Please enter another base.\n"<<endl;

else

break;

}

return(result);

}

ull base2dec(std::string value,ul base)

{

ull col=1, num=0;

for(std::string::reverse_iterator i=value.rbegin(); i!=value.rend(); ++i)

{

num+=symbols.find(*i,0)*col;

col*=base;

}

return(num);

}

std::string dec2base(ull dec,ul base)

{

using namespace std;

int len=1;

ull tmp=dec;

while(tmp/=base)

++len;

string value("0",len);

while(dec)

{

value[--len]=symbols[dec%base];

dec/=base;

}

return(value);

}

int main()

{

using namespace std;

ul base=inputbase("Enter the base of the value");

string value=inputvalue(base);

ul newbase=inputbase("Enter the base to convert to");

value=dec2base(base2dec(value,base),newbase);

cout<<"New value:\t"<<value.c_str()<<endl;

return(0);

}

What is looping in c plus plus?

A loop in computer languages is a set of statements that execute repeatedly, based on some criteria.

In C and C++, the three looping statements are while, do, and for...

while (test-expression) statement;
/* statement executes zero or more times, until test-expression is false, test first */

do statement while (test-expression);
/* statement executes one or more times, until test-expression is false, test last */

for (init-expression, test-expression, loop-expression) statement;
/* init-expression executed once, at beginning */
/* statement executes zero or more times, until test-expression is false, test first */
/* loop-expression evaluated at end of each iteration */

Often, statement, is a set of statements, such as...

while (test-expression) {
... statements
}

What is compilation process in programming?

In general a compiler will go through a few steps:

# Lexical analysis - making sure all the symbols in the source code are legal, and turning them into "tokens" for the next step.

# Syntactic analysis - analyze the tokens, ensuring they follow the rules of the language grammar and parsing them into some form of syntax tree. # Code generation - uses the syntax tree to create some form of intermediate language; oftentimes into assembly instructions, or a unique assembly-like language. # Code optimization - may or may not perform optimization on the intermediate language before translating it into executable code. Of course the true process of compilation is almost always much more complex than this, and may involve many more steps.

How do you swap two strings in c plus plus?

The most efficient way to swap strings is to point at them, and swap the pointers. Swapping the actual strings is problematic if the strings are of unequal length but impossible when they are also statically allocated. Dynamic strings can always be physically swapped, however it's highly inefficient. If it really must be done, then use a built-in method such as string::swap(). Otherwise just use string pointers and swap the pointers, never the strings themselves.

The following example shows how both techniques can be used on statically allocated strings. Example output is show below.

#include <iostream>

using namespace std;

void SwapPointers(char ** pp1, char ** pp2 )

{

cout<<"\nSwapping pointers:"<<endl;

char * t = *pp1;

*pp1 = *pp2;

*pp2 = t;

}

void SwapStatics(char * String1, char * String2, size_t len)

{

cout<<"\nSwapping static strings:"<<endl;

while(len--) String1[len]^=String2[len]^=String1[len]^=String2[len];

}

int main()

{

char s1[] = "one ";

char s2[] = "two ";

char s3[] = "three ";

// Note that the output statements before and after

// swapping are exactly the same, proving the strings

// have really swapped.

cout<<"Original strings:"<<endl;

cout<<s1<<s2<<s3<<endl;

SwapStatics(s1,s2,sizeof(s1));

cout<<s1<<s2<<s3<<endl;

cout<<endl;

// We cannot swap s3 with either s1 or s2, because

// s1 and s2 don't have the space to accomodate s3.

// However, we can use pointers instead:

char * p1 = s1;

char * p2 = s2;

char * p3 = s3;

// Again, note that the output statements are the

// same before and after swapping, proving the

// pointers have swapped.

cout<<"Original pointers:"<<endl;

cout<<p1<<p2<<p3<<endl;

SwapPointers(&p1,&p3);

cout<<p1<<p2<<p3<<endl;

cout<<endl;

// Just to prove the strings didn't swap...

cout<<"The strings have not swapped:"<<endl;

cout<<s1<<s2<<s3<<endl;

cout<<endl;

return(0);

}

Output:

Original strings:

one two three

Swapping static strings:

two one three

Original pointers:

two one three

Swapping pointers:

three one two

The strings have not swapped:

two one three

What is the code for merge sort in c plus plus?

#include <stdio.h>

void merge_sort(int [], int, int);

void merge_array(int [], int, int, int);

main()

{

int a[50], n, i;

printf("\nEnter size of an array: ");

scanf("%d", &n);

printf("\nEnter elements of an array:\n");

for(i=0; i<n; i++)

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

merge_sort(a, 0, n-1);

printf("\n\nAfter sorting:\n");

for(i=0; i<n; i++)

printf("\n%d", a[i]);

getch();

}

void merge_sort(int a[], int beg, int end)

{

int mid;

if (beg < end)

{

mid = (beg+end)/2;

merge_sort(a, beg, mid);

merge_sort(a, mid+1, end);

merge_array(a, beg, mid, end);

}

}www.eazynotes.com Gursharan Singh Tatla Page No. 2

void merge_array(int a[], int beg, int mid, int end)

{

int i, left_end, num, temp, j, k, b[50];

for(i=beg; i<=end; i++)

b[i] = a[i];

i = beg;

j = mid+1;

k = beg;

while ((i<=mid) && (j<=end))

{

if (b[i] <= b[j])

{

a[k] = b[i];

i++; k++;

}

else

{

a[k] = b[j];

j++; k++;

}

}

if (i <= mid)

{

while (i <= mid)

{

a[k] = b[i];

i++; k++;

}

}

else

{

while (j <= end)

{

a[k] = b[j];

j++; k++;

}

}

}

What is the difference between dynamic link library and shared library?

Static libraries are compiled into the program itself, shared libraries are compiled separately and referenced by the program. This enables the program to be much smaller, but requires the shared libraries be available to run.

What is the token in c plus plus language?

A token in C++, and in many other computer languages as well, is the largest set of characters in the source code that meets the criteria of a single language element. Often, tokens are separated by white space, but if the context is clear, this is not required. The expression a=b+c, for instance, contains 5 tokens, a, =, b, +, and c. The expression a = b + c is identical in meaning. The "largest set" rule can be shown with the example a=b+++c. The tokens are a, =, b, ++, +, and c. This expression means to add b and c, store the result in a, and then increment b.

What is the purpose of 'this' operator in c?

Every instance of a class inherits a 'this' pointer. It always points to the instance itself. Outside of the object you must use the object's variable name to refer to the object, or instantiate a pointer to the object. But from within the object's member methods you must use the 'this' pointer which is instantiated automatically as soon as the object is constructed and falls from scope when the destructor returns. Only non-static member functions have access to the 'this' pointer.

There are several uses, however the most important is when checking for self-references, particularly in the assignment operator overload. That is, any member function that accepts a reference to the same class of object should always check for self-references before attempting to mutate the instance. This is particularly important when the class "owns" memory that is dynamically allocated to it.

It is also used to return a reference to the current instance from the assignment operator and from any other operator overload or function that must return a reference to the current instance (including the addition and subtraction operators). Both uses can be seen in the following stripped-down example:

class MyObject

{

public:

// Assignment operator overload.MyObject& operator= ( const MyObject & obj ){

// Self-reference check.

if( this != &obj ){// Assignment code goes here...

}

// Return a reference to this object.

return( *this );

}

};

The 'this' pointer can also be used to pass a pointer (this) or reference (*this) to external functions that accept such arguments.

It should also be noted that when referring to an instance member from within a non-static member function, the dereferenced 'this' pointer is implied, as in:

this->[member_name]

Although this usage is never required, there may be times when it can help make your code more readable, or less ambiguous, especially when a member function must handle one or more external instances of the same class.

What is visibility mode what are the different inheritance visibility modes support by c plus plus?

There is no such thing as visibility mode in C++. Visibility is a function of information hiding but that relates to the way in which implementation details can be obfuscated within binary executables and libraries where only the interface need be exposed in a plain-text header file. This has nothing whatsoever to do with object oriented programming since information hiding is also possible in C.

You probably meant access specifiers. There are three levels: private, protected and public. Private access limits access to the class and to friends of the class. Protected is the same as private but extends access to derivatives of the class. Public access imposes no limits.

In terms of inheritance, the specified access level determines the accessibility of the protected and public members of the base class (private members are never inherited and will always remain private to the base class). in essence, members with access greater than the specified inheritance are reduced to the specified access. Thus if you specify protected inheritance, all public members of the base class become protected members of the derivative, while private inheritance reduces all public and protected members to private access. You may also reduce access to specific base class members simply be redeclaring them with the appropriate access.

What are the function of c plus plus language?

C++ is merely a tool, it has no specific role in mathematics other than to compute complex mathematical algorithms much faster and more accurately than any human could. But that is more specifically the role of the computer itself: C++ merely makes it possible to program the necessary machine code than would otherwise be possible with low-level assembly, using abstract objects that emulate real-world object behaviours.

What are the advantages of operator overloading in C plus plus?

You pass parameters by value when you do not want the original value to change. Passing by value creates a temporary copy of the value, only the copy is affected, but it can add some overhead to the function call, especially if the value is a complex structure or object. If you want any changes reflected in the original value, you must pass by reference instead.

However, if the parameter is a constant reference, the object's immutable members are not altered. So when the option exists to pass by value or by constant reference, choose constant reference every time. Pass by non-constant reference only when you expect any changes to be reflected in the original value, otherwise pass by value.

What is data storage in c plus plus?

A storage class is not a class as such, it is a modifier. C++ provides several built-in storage classes: auto, register, static, extern and mutable.

The auto storage class is implied for all function local variables and it can only be used in functions. Since it is implied it is rarely used. However, with C++11, the auto keyword has an alternative use, allowing unambiguous types to be deduced without the need to explicitly declare their type. This greatly simplifies code where the type is of little importance to the reader, and is particularly useful when iterating through an STL container as it greatly simplifies and shortens the declaration of the for statement that controls the loop.

The register storage class can be used for any variable that will fit in a CPU register. Since register variables do not exist in RAM, they have no address. Declaring a register variable is not a guarantee that the variable will be stored in a register, only that it might be. Simple variables such as counters are good candidates for register variables, however your compiler should be able to automatically determine when to use a register rather than RAM for a variable.

The static storage class ensures that a variable remains in memory at all times. This does not mean the variable is accessible at all times, however, since visibility is ultimately determined by the variable's scope. However, when you modify a static variable that is in scope, it will maintain that value even when it falls from scope (static variables are never destroyed). All static variables must be initialised with a value and each time the program is run, they will default to the initial value.

Class member functions as well as variables can be declared static. Static members of a class are local to the class, rather than to an instance of the class. They are generally used to provide internal class functionality or information that is common to all instances of the class (much like global functions and variables, but scoped to the class). Public static members are also accessible outside of the class, even when no instances of the class exist.

Extern provides external linkage to a global variable that is defined in another file. This is typically used when two or more source files share the same global variable. One file defines the global while all others declare it external.

The mutable storage class is only used in classes, and allows the member to override the constness of the class. That is, when calling constant member functions, the class' mutable members can be modified while the immutable (normal) members remain constant. Mutable members are typically used internally be the class, such that the external "state" of the class can remain constant.

How do you create an array in visual basic?

If you are referring to the searching and sorting of strings, there are 2 main methods that Visual Basic uses most. If you want to search for a phrase in a string, you would probably use the InStr method, which would give you an integer which would indicate the place where the phrase was found. It might look something like this:

Dim InputString as String

Dim StringToFind as String = "Whatever text you want to find"

Dim PositionInteger as Integer

PositionInteger = InStr(InputString, StringToFind)

If you wanted to sort the string, you could do it with the substring method using the split point you found with the previous code. To do that, you would make a variable that would contain the latter half of your string, and use the subtring method to extract it from the whold string. To do that, you must type "Substring" and in parenthasis, give it a starting position, and an ending position. If you want all the characters from the phrase to the end of the sting, you do not need to put in an end point. The starting point for this example will be the position of the start of the search phrase, plus thirty (since you want to start after the end of the phrase, which is thirty characters long). Your code might look like this:

Dim NewString as String

NewString = Substring(PositionInteger + 30)

This would make the variable "NewString" contain all the characters following the search phrase.

C plus plus which software is necessary?

There is no necessary software other than a C++ implementation suitable for your hardware. Typically you will write C++ programs in an IDE that provides all the tools necessary for your chosen platform. To write generic code you simply avoid platform-specific code and use the generic language as stipulated by the current C++ standard.

How make a calculator in c?

#include

int main(){

int a, b, choice;

printf("This program implements a calculator\n");

do{

printf("Enter your choice:\n1-Addition\n2-Subtraction\n3-Multiplication\n4-Division\n5-Modulus\n6-Quit\t:");

scanf("%d", &choice);

switch(choice){

case 1: printf("Enter two numbers :");

scanf("%d%d", &a, &b);

printf("Sum = %d\n", a+b);

break;

case 2: printf("Enter two numbers :");

scanf("%d%d", &a, &b);

printf("Subtraction = %d\n", a-b);

break;

case 3: printf("Enter two numbers :");

scanf("%d%d", &a, &b);

printf("Product = %d\n", a*b);

break;

case 4: printf("Enter two numbers :");

scanf("%d%d", &a, &b);

printf("Quotient = %d\n", a/b);

break;

case 5: printf("Enter two numbers :");

scanf("%d%d", &a, &b);

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

break;

case 6: break;

default: printf("Invalid choice\n");

}

}while(choice != 6);

return 0;

}

Write a Fibonacci function then takes an input from the user in main program and pass to function which prints Fibonacci series up to this number using function in c plus plus language?

We use long int or long instead of int as for larger terms the number is also larger.

Code is as follows:

#include

#include

long fib(long n);

void main()

{

long res,n;

int i;

printf("Enter the number of terms of the Fibonacci Series:\t");

scanf("%d",&n);

for(i=0;i

{

res=fib(i);

printf("\n %d",res);

}

_getch();

}

long fib(long n)

{

long res;

if(n==0n==1)

return (n);

else

res=fib(n-1)+fib(n-2);

return(res);

}