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 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);

}

What is difference between call by value and pass by value?

When you pass by value, the function's parameter is assigned the value of the argument that was passed. When you pass by reference, the function's reference parameter is assigned the address of the argument. In other words, pass by value copies the value, pass by reference passes the variable itself.


Pass by reference is always the preferred method of passing arguments to functions when those arguments are complex objects. If the argument is a primitive data type then the cost in copying the value is minimal, but copying a complex object is expensive in terms of performance and memory consumption. If the function parameter is declare constant, you can be assured the object's immutable members will not be affected by the function. If it is non-constant and you do not wish your object to be altered, you can either copy the object and pass the copy, or pass the object by value if the function is overloaded to cater for this eventuality (good code will provide both options).



How many pointers can be used in a c program?

Answergenerally we use simple pointer, void pointer,null pointer, structure pointer. Answerzero or more (unlimited).

What is queue in c plus plus?

A queue is a FIFO data structure. The best way to implement this is to use two pointers, one to track the head and one to track the tail. During a push operation, the tail pointer will advance one spot as the data is entered into the list. During a pop operation, the head pointer will advance one spot as data is removed. When the two pointers are pointing to the same space, the queue is empty.

What is the default return type of a function?

The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value. By default, it will return zero.

To learn more about data science please visit- Learnbay.co

What is Constructor in C plus plus?

A constructor is a special class method that instantiates an object of the class.

All objects must have at least two constructors, one of which must be a copy constructor. Even if you do not explicitly declare a copy constructor, one is generated for you with public access by the compiler. The purpose of the copy constructor is to instantiate new objects from existing objects. Even if you never explicitly call the copy constructor, it is automatically called whenever you pass an object to a function by value, as the object must be copied.

If you do not declare any constructors, then both the copy constructor and the default constructor are generated for you. The default constructor is a constructor that accepts no parameters, or that is declared with all default parameters.

Although the compiler will generate default and copy constructors for you, it is always recommended that you declare your own constructors, thus ensuring your object members are always correctly initialised and valid. An uninitialised object is a potential time-bomb.

Constructors are not functions; they do not return any value, not even void. The assignment operator (which does return a value) is not a constructor; it is used to initialise an existing object from another existing object -- it does not instantiate a new object.

Constructors are called whenever you instantiate a reference to an object, or allocate memory to an object using the new operator, or copy a new object from an existing object.

All constructors have the same name as the class itself. Construction overloads can be differentiated by their signature (the number and type of parameters they accept). The copy constructor is signified by the fact its only parameter is a constant reference to an object of the same class.

class Object

{

public:

Object(); // Default constructor (no parameters)

Object(const Object& object); // Copy constructor

Object(int x); // Overloaded constructor

}

As well as constructors, it is recommended you also declare your own assignment operator and destructor. Even if the compiler-generated versions are adequate for your needs, it costs nothing but a little time to declare your own. But if your class allocates dynamic memory on the heap, you must include code in the constructors, destructor and assignment operator to ensure that memory is correctly initialised and released, and that self-references are correctly accounted for; the compiler-generated methods will not do it for you.

How do you write a program in linked list in ascending and descending order in sorted way using c plus plus?

#include <stdio.h>

#include <conio.h>

int main()

{

int a[10],i,j,temp=0;

printf("Enter all the 10 numbers");

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

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

for(i=0;i<10;i++) //This loop is for total array elements (n)

{

for(j=0;j<9;j++) //this loop is for total combinations (n-1)

{

if(a[j]>a[j+1]) //if the first number is bigger then swap the two numbers

{

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}

}

}

printf("The ordered array is");

for(j=0;j<10;j++) //Finally print the ordered array

printf("%d \t",a[j]);

getch();

return 0;

}

Write a program in c plus plus in which insertion and deletion in an array?

#include<stdio.h>

#include<conio.h>

void main()

{

int a[10],i,j,k,n;

printf("enter number of elements of array");

scanf("%d",n);

printf("Enter array elements");

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

{

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

}

printf("enter the element you want to delete");

scanf("%d",k);

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

{

if(a[j]==k)

{

a[j]=a[j+1];

n=n-1;

}

}

printf("The array after deletion of %d is:",k);

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

{

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

}

getch();

}

Why are pointers important in C plus plus?

Pointers are variables. They allow you to store memory addresses and to indirectly manipulate the contents of those memory addresses. Pointers can point to variables, constants and functions -- anything that resides in memory -- so long as the type of the pointer is covariant with the type being pointed at. Pointers that are no longer in use should be nullified by assigning the value NULL, thus preventing indirect access to memory that may no longer be in scope.

In C, a pointer is no different to a reference, hence we use the term 'dereference' when indirectly accessing the value of a pointer (the memory being pointed at). But in C++, a reference is not a variable of any kind, it is simply an alias that you can use in your source code to refer to an instance of an object, function, variable or constant. C++ references must be initialised at the point of instantiation, and are not unlike constant pointers. However, unlike references in C, references in C++ can never be NULL (a NULL reference will invalidate your program).

How you calculate rand in c plus plus?

Use the random number generator classes.

#include<random>

#include<ctime>

std::default_random_engine generator ((unsigned)time(0)); // seed the generator

std::uniform_int_distribution<int> distribution (0, 100); // set the closed range

int r = distribution (generator); // pick a random number from 0 to 100 (inclusive)

Any device can be used to seed the generator. Here, we've simply used the current time. If you don't seed the generator, it will generate the same sequence of random values every time the program is run.