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

How do you calculate the total salary of an employee in c plus plus?

Not to be pedantic, but an employee's salary does not have to be calculated. It is a fixed rate, paid monthly but calculated annually. If you are contracted to work for £24,000 a year, then your monthly salary, before tax/insurance, will be £2000, regardless of how many hours you actually worked. At the end of each year you may be offered a bonus for exceeding your annual targets, but this is over and above your agreed salary.

Wages, on the other hand, are worked out by the number of hours worked, with increased rates for overtime and unsociable hours. In manufacturing environments, you may be paid an agreed "piece" rate for each item you produce. To work out the annual pay of waged employees you need to add their weekly or monthly pay over a 12 month period.

How you actually achieve that in C++ depends on how the data is collected. A database back-end will often be used to track the employee payroll, so you will generally need an SQL or similar query to collate the information for a specific employee by their payroll number (or NI number).

Write a program in c plus plus to accept the string and then take the starting and ending point from the user and display the sub string through function?

#include<iostream>

#include<sstream>

unsigned input_num (std::string prompt, unsigned min, unsigned max)

{

unsigned num = 0;

while (1)

{

std::cout << prompt << " (range " << min << " - " << max << "): ";

std::string input = "";

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

std::stringstream ss (input);

if (ss >> num)

{

if (num >= min && num <= max)

break;

else if (num<min)

std::cout << "Index must be greater than or equal to " << min << std::endl;

else

std::cout << "Index must be less than or equal to " << max << std::endl;

}

else

std::cout << "Invalid input." << std::endl;

}

return (num);

}

void print_substring (std::string input, unsigned left, unsigned right)

{

std::cout << input.substr (left, right - left + 1) << std::endl;

}

int main()

{

std::cout << "Input string:\t";

std::string input = "";

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

unsigned left = input_num ("Enter the start index of the substring", 0, input.size()-1);

unsigned right = input_num ("Enter the end index of the substring", left+1, input.size()-1);

print_substring (input, left, right);

}

How do you create triangle circle and rectangle classes derived from a base class shape with virtual area function in c plus plus?

#include<iostream>

struct shape

{

virtual double area () const = 0;

};

struct triangle : shape

{

triangle (double b, double h): base (b), height (h) {}

double base, height;

double area () const override { return base * height / 2; }

};

struct circle : shape

{

circle (double r): radius (r) {}

double radius;

double area () const override { return 4 * atan(1) * radius * radius; }

};

struct rectangle : shape

{

rectangle (double w, double h): width (w), height (h) {}

double width, height;

double area () const override { return width * height; }

};

int main()

{

triangle t (10, 5);

std::cout << "triangle with base " << t.base << " and height " << t.height << " has area " << t.area() << std::endl;

circle c (5);

std::cout << "circle with radius " << c.radius << " has area " << c.area() << std::endl;

rectangle r (10, 5);

std::cout << "rectangle with width " << r.width << " and height " << r.height << " has area " << r.area() << std::endl;

}

Why certain features of C plus plus may be version and machine dependent?

C and C++ allow access to low-level concepts such as pointers and manual memory allocation. It also runs on a wide variety of operating systems and architectures.

For example, an int on a 32-bit machine is usually 4 bytes, but on a 64 bit machine it may be 8 bytes.

Whether or not this matters depends on what tricks the programmer is playing. If a portion of the code relies on ints being 32 bits, and it's, say, 56 bits on your machine for some bizarre reason, that code may not work properly.

Is an array not suitable?

That depends on what you want to use it for. An array offers constant-time random access to any element in the array, but is restricted by the fact it must be re-allocated in order to cater for new elements or to remove redundancy. Linked lists overcome this limitation at the expense of random access, which is linear-time other than for the first and/or last nodes which remain constant-time.

What should a function include?

A function must include an interface and an implementation. In some programming languages the two may be declared separately, particularly if the language is declarative.

The interface typically consists of the function's return type followed by the function name and the type of its arguments, if any, usually enclosed in parenthesis (often round brackets). In untyped languages, the return type and the type of arguments may be optional, but the arguments must be formally named while the return value usually has the same name as the function. In typed languages the types must be specified but the names are optional unless the interface and implementation are combined.

In typed languages that support function overloading, the function name and the number and type of the arguments form the function's unambiguous signature. The signature also includes the constness of the function and its arguments where supported, but does not include the return type nor any argument default values that may be provided.

The function's implementation must duplicate the interface (if declared separately) but must also formally name the arguments. The function body is usually parenthesised (often in curly braces).

What does a C developer do?

A C developer designs and writes programs using the C programming language. A C++ developer does the same but uses the C++ programming language. A C/C++ developer uses both C and C++.

What is the base class for all swing components?

The JComponent class of the javax.swing package serves as the base class.

How do you make a program like 5142332415 using looping?

There is insufficient information in the question to answer it. Please rephrase the question.

Write a function that creates a vector of user-given size M using new operator?

template<typename T> std::vector<T>* create_new_vector (const size_t M)

{

std::vector<T>* p = nullptr;

try

{

if (p = new std::vector<T>)

{

p->resize (M);

p->shrink_to_fit ();

}

}

catch (std::exception& e)

{

throw e;

}

return p;

}

What is the relationship between an array and a pointer?

All variable names are an alias for the value stored at the memory address allocated to them. To get the memory address itself, you must use the address of operator (&). The value returned from this can then be stored in a pointer variable.

Arrays are different. The array name is an alias for the start address of the array, thus you do not need the address ofoperator to obtain the memory address (although you can if you want to). This means that when you pass an array name to a function, you pass the memory address of the array rather than passing the array itself (which would require the entire array to be copied, which is a highly inefficient way to pass an array). In essence, the array is passed by reference rather than by value.

Consider the following code. This shows how a primitive variable name differs from the name of an array of primitive variables. The final portion shows how a pointer can be used to achieve the same results you got by accessing the array elements directly from the array name itself. This is in fact how the compiler implements arrays, using pointers, but there's no need to do this in your code. Accessing array elements directly by their index is a programming convenience.

#include

using namespace std;

int main()

{

int i = 10;

cout << "&i = address of i:\t0x" << &i << endl;

cout << "i = value of i:\t" << i << endl;

cout << endl;

int Array[10] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

cout << "&Array = address of Array:\t0x" << &Array << endl; // same as next line.

cout << "Array = address of Array:\t0x" << Array << endl; // same as previous line.

cout << "*Array = value of Array[0]:\t" << *Array << endl; // returns value of first element.

cout << endl;

int offset=0;

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

{

cout << "&Array[" << offset << "] = address of element " << offset << ":\t0x" << &Array[offset] << endl;

cout << "Array[" << offset << "] = value of element " << offset << ":\t" << Array[offset] << endl;

}

cout << endl;

int * pointer = Array; // point to the array address.

cout << "&pointer = address of pointer:\t\t0x" << &pointer << "\t(never changes)" << endl;

cout << endl;

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

{

cout << "pointer = address stored in 0x" << &pointer << ":\t0x" << pointer << "\t(same as &Array[" << offset << "]" << endl;

cout << "*pointer = value stored in 0x" << pointer << ":\t" << *pointer << "\t\t(same as Array[" << offset << "]" << endl;

++pointer;

}

cout << endl;

return( 0 );

}

What is the difference between the direct and indirect base class?

Direct base classes are those that are specified in a derived class' inheritance declaration. Indirect base classes are those that are inherited via the direct base classes.

class A{};

class B : public A{};

class C : public B{};

With respect to C, B is direct while A is indirect. With respect to B, A is direct.

What are the different types of overloading allowed in c plus plus?

There are only two types: user-defined and compiler-generated. User-defined overloads are the ones you specifically write. Compiler-generated overloads are created by the compiler based upon a template function that you define. The only real difference is that with a template function you only need to write one version of the function, and the compiler will generate the actual overloads on an as-required basis. With user-defined overloads you must write each overload in full.

Template functions save a lot of time and maintenance, however they are only practical when the only difference between the overloads is the type of argument. That is, if the implementation is exactly the same regardless of type, then template functions are clearly a better option than writing out each overload by hand. Moreover, if you ever need to alter the implementation, there's only one function to modify.

What are identifiers in C?

If you know what BNF is:

Identifier -> Start Cont

Start -> letter | underline

Cont -> empty | (letter | underline | digit) Cont

CAN Overloaded functions can return default values?

I'm not sure I understand you as it wouldn't make sense for a function to return a default value.

Do you actually mean can a function return an argument that has a default value? If so, then yes. Any argument passed to a function, whether defaulted or not, can be returned by the same function. If the argument is passed by value then you must return it by value. If passed by reference (which cannot be defaulted) then you can either return by reference or by value. However, if you pass by non-constant reference then you can just use the reference as an output argument, and use the actual return value for some other purpose, such as reporting any error condition(s) created by the function.

Overloaded functions are no different to ordinary functions, the only criteria is that each overload has an unique signature. The return value does not form any part of the signature, thus signatures cannot differ by return type alone.

Write a program that asks the user to enter 2 numbers obtains the two numbers from the user and print the sum products difference and quotient of the two numbers?

#include <iostream>

using namespace std;

int main()

{

int i1, i2, i3;

char o;

cout << "Enter two integers sparated by an operator: ";

cin >> i1 >> o >> i2;

if ( o '/' && i2 != 0 )

{

i3 = i1 / i2;

cout << i1 << " / " << i2 << " = " << i3 << endl;

}

else

cout << "Input Error!" << endl;

return 0;

}

Can you write a program in c plus plus for finding practical numbers?

#include<iostream>

#include<vector>

#include<sstream>

#include<cassert>

using set_type = std::vector<size_t>;

using set_const_iterator = set_type::const_iterator;

using subset_type = std::vector<set_type::const_iterator>;

using subset_const_iterator = subset_type::const_iterator;

using subset_reverse_iterator = subset_type::reverse_iterator;

// Returns the first subset of the given set with the given count.

subset_type first_subset (const set_type& set, size_t count)

{

assert (0U < count);

assert (count <= set.size());

subset_type subset;

for (set_const_iterator it=set.begin(); count--; ++it)

subset.push_back (it);

return subset;

}

// Returns the next subset after the given subset of the given set with the given count.

subset_type next_subset (set_type& set, size_t count, subset_type subset)

{

assert (subset.size() == count);

if (count)

{

subset_reverse_iterator sub_it = subset.rbegin();

set_const_iterator set_it = *sub_it;

subset.pop_back();

if (++set_it != set.end())

subset.push_back (set_it);

else if (1U != count)

{

const size_t value = set.back();

set.pop_back();

subset = next_subset(set, --count, subset);

set.push_back (value);

if (subset.size() == count++)

{

sub_it = subset.rbegin();

set_it = *sub_it;

if (++set_it != set.end())

subset.push_back (set_it);

}

}

}

return subset;

}

// Returns all the divisors of the given number.

set_type get_divisors (const size_t num)

{

set_type divs;

size_t factor = 0;

while (factor++<=num/2)

{

if (num%factor==0)

divs.push_back (factor);

}

return divs;

}

// Returns the sum of the given subset.

size_t sum (const subset_type& subset)

{

size_t sum = 0;

for (subset_const_iterator it=subset.begin(); it!=subset.end(); sum += **it, ++it);

return sum;

}

// Returns true if the sum of any combination of distinct divisors totals the given number

bool has_compound (const size_t num, set_type divisors)

{

bool found = false;

for (size_t count=1; !found && count<=divisors.size(); ++count)

for (subset_type subset = first_subset (divisors, count); !found && subset.size(); subset = next_subset (divisors, count, subset))

found = sum (subset) == num;

return found;

}

// Returns true if the given number is a practical number.

bool is_practical (const size_t num)

{

if (!num) return false;

if (num<3) return true;

if (num%2) return false;

set_type divs = get_divisors (num);

for (size_t val=1; val<num; ++val)

if (!has_compound (val, divs))

return false;

return true;

}

int main()

{

std::cout << "Practical numbers in the range 1 to 240\n\n";

std::stringstream ss;

for (size_t num=1; num<=240; ++num)

{

if (is_practical(num))

{

if (ss.str().size())

ss << ", ";

ss << num;

std::cout << num << std::endl;

}

}

// Assert that the numbers match those in sequence A005153

// of the Online Encyclopedia of Integer Sequences (OEIS).

std::string verify = "1, 2, 4, 6, 8, 12, 16, 18, 20, 24, "

"28, 30, 32, 36, 40, 42, 48, 54, 56, 60, 64, 66, 72, 78, "

"80, 84, 88, 90, 96, 100, 104, 108, 112, 120, 126, 128, "

"132, 140, 144, 150, 156, 160, 162, 168, 176, 180, 192, "

"196, 198, 200, 204, 208, 210, 216, 220, 224, 228, 234, 240";

std::cout << verify << std::endl;

std::cout << ss.str() << std::endl;

assert (ss.str() == verify);

}

How do you print hello world 100 times in c plus plus using while statment?

C++ Hello World Example:// this is a single line comment /* this is a multi-line comment */ #include // header file needed to print using namespace std; // instead of having to write std::cout // the main function is where the program begins execution int main() { // print Hello world. and a new line cout

How can we write a program which orders the elements of a board given there language of programming c plus plus?

In C++ you can use the standard library sort algorithm to sort any data sequence provided the elements support the appropriate comparison operator (std::less<T> for any given type T is used by default).

For example:

std::vector<int> v {5, 9, 7, 1, 3};

std::sort (v.begin(), v.end()); // v = {1, 3, 5, 7, 9}

std::sort (v.begin(), v.end(), std::greater<int>); // v = {9, 7, 5, 3, 1}

What do you mean by public private protected and friendly?

An Access Modifier is a key word in java that determines what level of access or visibility a particular java variable/method or class has. There are 4 basic access modifiers in java. They are:

1. Public

2. Protected

3. Default and

4. Private

Java does not have a friendly access modifier.

Public Members:

If a variable or method is declared public, it means that it can be accessed by anyone or any other class (irrespective of which package they are in).

Private Members:

Members marked private can't be accessed by code in any class other than the class in which the private member was declared

Protected and Default Members:

The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package

Find vowel from given string in C plus plus language?

std::string test ("The cat sat on the mat");

std::string vowels ("aeiouAEIOU");

size_t pos = test.find_first_of (vowels);

if (pos != test.npos)

std::cout << "Vowel found at position " << pos << std::endl;

What are the advantages and disadvantages of the linked implementation of a queue relative to the contiguous implementation?

Contiguous implementation (e.g., using an array), has a major disadvantage in that you have to allocate enough space in the array to hold all the elements in the queue. When there is insufficient space, you have to re-allocate, which may occasionally require the entire array be copied to new memory. In addition, with each extraction, you are left with unused memory at the start of the array. Thus before any re-allocation, you must first check if there are unused elements and then shunt all elements forward, thus creating space at the end of the array.

If we ignore the shunting and re-allocations necessary with an array, insertions and extractions will occur in constant time for both contiguous and linked implementations. However, once you take shunting and re-allocation into account, we find that contiguous implementations occasionally falter during an insertion.

Contiguous implementations also require more memory than linked implementations. Although a linked node is larger than an array element by one pointer (32 bits on a 32-bit system), contiguous implementations must allocate far more memory than is actually required in order to minimise the number of re-allocations. Thus an array must always have unused elements. Moreover, when all elements are extracted from the queue, the current allocation remains in memory. With linked implementations, the only memory allocated is the memory actually in use at any given moment, with the minimum memory requirement being just one pointer, to the tail node.

An optimal queue implementation will use a circular linked list, where only the tail node need be maintained by the list object. The tail's next node always points to the head node, so there is no need to maintain this separately.

The only real disadvantage of a linked implementation is the need to allocate and deallocate memory for each insertion and extraction respectively. However, this is a constant time operation. With contiguous implementation, only extraction is guaranteed to be a constant time operation. Most of the time, insertions will be constant time, but will occasionally take variable time due to the need to shunt or re-allocate.

How can i find last node of a cicular list whose size i don't know and the last node points to any other node except first node of the link list through c plus plus language of data structure?

How can i find last node of a cicular list whose size i don't know and the last node points to any other node except first node of the link list through c plus plus language of data stucture?