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

When operator function is declared as friend function?

Ideally, never. Friend functions should only be employed when a function (whether an operator overload or not) requires private access to a class, and it is not otherwise possible to provide a public interface without unduly undermining the class encapsulation. However, as programmer, it is your responsibility to ensure all friend functions adhere to the same class rules (which you yourself define) as do the members of your class, even though friends are not regarded as being members of the class. Ultimately, if you have no control over the friend function implementation, then you must not allow that function to be a friend of your class, as this will seriously undermine the encapsulation.

Difference between C and C plus plus languages?

C was the C++ predecessor. As it's name implies, alot of C remains in C++. Although not actually being more powerful than C, C++ allows the programmer to more easily manage and operate with Objects, using an OOP (Object Oriented Programming) concept.

C++ allows the programmer to create classes, which are somewhat similar to C structures. However, to a class can be assigned methods, functions associated to it, of various prototypes, which can access and operate within the class, somewhat like C functions often operate on a supplied handler pointer.

Although it is possible to implement anything which C++ could implement in C, C++ aids to standarize a way in which objects are created and managed, whereas the C programmer who implements the same system has alot of liberty on how to actually implement the internals, and style among programmers will vary alot on the design choices made.

In C, some will prefer the handler-type, where a main function initializes a handler, and that handler can be supplied to other functions of the library as an object to operate on/through. Others will even want to have that handler link all the related function pointers within it which then must be called using a convention closer to C++.

To finish this discussion, C++ applications are generally slower at runtime, and are much slower to compile than C programs. The low-level infrastructure for C++ binary execution is also larger. For these reasons C is always commonly used even if C++ has alot of popularity, and will probably continue to be used in projects where size and speed are primary concerns, and portable code still required (assembly would be unsuitable then).

What is null pointer assignment?

This error message means that somewhere in your program you have used a pointer-varible containing NULL-value. (Within an actual OS it with stop the program immediately, but in MS-DOS it doesn't.)

What is diff between method and class?

method is a process

property is about it.

please check the answer from others also. because its only my guess.

SORRY

THANK YOU

What are escape sequences in c language?

Escape sequences are combination of characters which when used together form one single unit with a special meaning.Eg:

when a blackslash('\') and 'n' are written together like '\n', this represents a newline character.


For more escape sequences visit the related link.


What is meant by the data type of a variable in c plus plus?

The built-in (fundamental) data types are int, char, bool, float, double and pointer. All other integral types are either modified types or aliases (typedefs). User-defined types (including those provided by the standard library) are not considered part of the language.

What is meant by a function returning a value in c?

Consider this example:

#include

int add(int x, int y)

{ int n=x+y;

return n; }

int main()

{ Using namespace std;

cin >> x;

cin >> y;

cout << add(x,y);

return 0; }

What happens is the main() function asks the user for 2 integers then sends them to add() in the cout statement. Add() adds the two integers and returns the sum to the function that called it (main()) so technically 'add(x,y)' in the cout statement is replaced with add()'s return value. So if the user said x=1 and y=2, the program would print 3. NOTE:

For example, return 0 in main(). Anything else is an error code that is RETURNED TO THE OS or SHELL.

In the of Unix/Linux, we can see the returned value of main using

echo $?

In the case of Windows, we can see the returned value of main using

echo %ERROR_LEVEL%

while we are in DOS or Command prompt

Write program to implement stack with POP and PUSH operations?

SOURCE CODE:

#include

#include

void push(int st[],int data,int &top);

void disp(int st[],int &top);

int pop(int st[],int &top);

int flg=0;

int top=-1,tos=-1;

int st[50];

void push(int st[],int data,int &top)

{

if(top==50-1)

flg=0;

else

{

flg=1;

top++;

st[top]=data;

}

}

int pop(int st[],int &top)

{

int pe;

if(top==-1)

{

pe=0;

flg=0;

}

else

{

flg=1;

pe=st[top];

top--;

}

return(pe);

}

void disp(int st[],int &top)

{

int i;

if(top==-1)

{

printf("\nStack is Empty");

}

else

{

for(i=top;i>=0;i--)

printf("\t%d",st[i]);

}

}

void main()

{

int dt,opt;

int q=0;

clrscr();

printf("This Program Is Used to Perform PUSH & POP operations On Stack");

printf("\n\n\tMain Menu.........");

printf("\n\n1.Push");

printf("\n\n2.Pop");

printf("\n\n3.Exit");

do

{

printf("\n\n\tEnter Your Choice 1-3:");

scanf("%d",&opt);

switch(opt)

{

case 1:

printf("\nEnter the Element to be Push:");

scanf("%d",&dt);

push(st,dt,tos);

if(flg==1)

{

printf("\nAfter Inserting the Element, Stack is:\n\n");

disp(st,tos);

if(tos==50-1)

printf("\nStack is Now Full");

}

else

printf("\nStack Overflow Insertion Not Possible");

break;

case 2:

dt=pop(st,tos);

if(flg==1)

{

printf("\n\tData Deleted From the Stack is:%d\n",dt);

printf("\n\tAfter Deleting the Element from the stack is:\n\n");

disp(st,tos);

}

else

printf("\nStack Empty,Deletio Not Possible:");

break;

case 3:

q=1;

break;

default:printf("\nWrong Choice Enter 1-3 Only");

}

}while(q!=1);

}

OUTPUT

Main Menu.........

1.push

2.pop

3.exit

Enter your choice 1-3:1

Enter the element to be push:4

After inserting the elements,stack is:

4

Enter your choice 1-3:1

Enter the element to be push:7

After inserting the elements,stack is:

7 4

Enter your choice 1-3:1

Enter the element to be push:4

Program for row wise sort for a square matrix in C?

#include<stdio.h>

#include<conio.h>

void main()

{

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

printf("enter the order");

scanf("%d",&m,&n);

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

{

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

{

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

}

}

for(k=0;k<m;k++)

{

for(i=0;i<=m-1;i++)

{

for(j=0;j<n-i-1;j++)

{

if(a[k][j]>a[k][j+1])

temp=a[k][j];

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

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

}

}

}

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

{

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

{

printf("sorted matrix=%d",a[i][j]);

}

}

getch();

}

Source code for prim's algorithm in C plus plus programming?

#include<stdio.h>

#include<conio.h>

int a,b,u,v,n,i,j,ne=1;

int visited[10]={0},min,mincost=0,cost[10][10];

void main()

{

clrscr();

printf("\n Enter the number of nodes:");

scanf("%d",&n);

printf("\n Enter the adjacency matrix:\n");

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

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

{

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

if(cost[i][j]==0)

cost[i][j]=999;

}

visited[1]=1;

printf("\n");

while(ne<n)

{

for(i=1,min=999;i<=n;i++)

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

if(cost[i][j]<min)

if(visited[i]!=0)

{

min=cost[i][j];

a=u=i;

b=v=j;

}

if(visited[u]==0 visited[v]==0)

{

printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);

mincost+=min;

visited[b]=1;

}

cost[a][b]=cost[b][a]=999;

}

printf("\n Minimun cost=%d",mincost);

getch();

}

Why you use C when C plus plus is there?

C is a much simpler language than C++, with fewer keywords. The resultant machine code maps very closely to the source code, thus C is more low level than C++, but is sufficiently abstract that even assembler language programmers can develop highly efficient code much more easily than they can with assembler alone. C++ evolved from C, but has a far greater degree of abstraction and its object-oriented programming support is ideally suited to solving highly complex problems with more complex data structures more easily but every bit as efficiently as with C. However, since C is much older, there is still a wealth of useful and highly efficient C code that can still be used by C++ programmers to this day, thus it is still worthwhile learning C even if you already know C++, as the transition to C is much easier than the transition from C to C++, unless you are familiar with object-oriented principals.

What are the manipulator in c plus plus?

What is a manipulator?

C++ manipulators are functions or operators that are used specifically with input and output streams in order to manipulate those streams or to insert or extract special characters. Many manipulators apply to both input and output streams but some are specific to one or the other.

The following list briefly describes all the manipulators available in C++, including those only available in C++11. Most manipulators can be found in the header, while the parameterised manipulators (those that accept arguments) will be found in the header.

Output stream manipulators

std::flush - synchronises the output buffer with the controlled output sequence

std::endl - inserts a newline character (\n) and flushes the output stream

std::ends - inserts a null character (\0) without flushing the output stream

Input stream manipulators

std::ws - extracts and discards whitespace characters from the input stream

Numerical base format manipulators ("basefield" flags)

std::dec - inserts/extracts integral numeric data with decimal notation

std::hex - inserts/extracts integral numeric data with hexadecimal notation

std::oct - inserts/extracts integral numeric data with octal notation

Floating-point format manipulators ("floatfield" flags)

std::fixed - inserts/extracts floating point values with fixed notation

std::scientific - inserts/extracts floating point values with scientific notation

std::hexfloat - inserts/extracts floating point values with hecadecimal notation (C++11 only)

std::defaultfloat - default behaviour (C++11 only)

Adjustment manipulators ("adjustfield" flags)

std::internal - output is padded to the field width by inserting fill characters at a specified internal point

std::left - output is padded to the filed width by appending fill characters

std::right - output is padded to the field width by prepending fill characters

Flags (on)

std::boolalpha - generates text values "true" and "false" for boolean values

std::showbase - generates the base for basefield values

std::showpoint - generates a decimal point for "floatfield" values

std::showpos - generates positive sign to positive values

std::skipws - ignores whitespace characters

std::unitbuf - flushes the buffer after every insertion

std::uppercase - generates upper-case letters for generated letters

Flags (off)

std::noboolalpha - does not generate text values for boolean values

std::noshowbase - does not generate the base for basefield values

std::noshowpoint - does not generate decimal point for "floatfield" values unless the decimal portion is non-zero

std::noshowpos - does not generate positive sign for positive values

std::noskipws - does not ignore whitespace characters

std::nounitbuf - does not flush the buffer afer every insertion

std::nouppercase - does not generate upper-case letters for generated letters

Parameterised manipulators

std::setiosflags - set format flags

std::resetiosflags - reset format flags

std::setbase - set basefield flag

std::setfill - set fill character

std::setprecision - set floatfield precision

std::setw - set field width

Many of these manipulators work together. For instance, the std::internal, std::left and std::rightmanipulators all work in conjunction with the std::setwand std::setfill manipulators.

All manipulators are implemented as operators which can be chained together using the insertion (<<) or extraction (>>) operators as appropriate to the stream. Excluding the parameterised manipulators, most manipulators are also implemented as functions (passing the streram as an argument). Others, including all parameterised manipulators, are implemented as members of the stream. Some, such as std::flush, are implemented all three ways; as an operator, a function and a member function.

Some examples of manipulator usage:

// set field width to 8 characters for console output

std::cout << std::setw (8); // operator

std::cout.width (8); // member method

// set precision to 16 places for floatfields

std::cout << std::setprecision (16); // operator

std::cout.precision (16); // member method

// insert newline and flush stream

std::cout << std::endl; // operator

std::endl (std::cout); // function

// flush stream

std::cout << std::flush; // operator

std::flush (std::cout); // function

std::cout.flush (); // member method

// generate hexadecimal values with base prefix

std::cout << std::showbase << std::hex; // operator

std::showbase (std::cout); // function

std::hex (std::cout); // function

More information on manipulators can be found in the sources and related links section, below.

Inventor of C?

A Bell Labs researcher named Dennis Ritchie (who was one of the driving forces behind Unix) created the C programming language.

What are c plus plus statements?

Statements are how we tell the compiler what we want our program to do. In other words, they are the instructions written in C++ code. A statement may be a simple instruction to invoke a function call, such as:

foo();

Or to perform an operation, such as adding two integers:

x+=y;

Note that all statements end with a semi-colon.

We can also group individual statements together to form a compound statement. For instance, when we use an if statement to evaluate a condition, we might want more than one statement to execute if the condition were true. We use curly braces to create a compound statement:

if (x==42)

{

for(int i=0; i<100; ++i)

std::cout<<i<<std::endl;

foo();

}

In the above example, if x were 42, then we'd print the number 0 to 99 and then call foo(). If x were not 42, then we'd skip over the entire compound statement and execute the next statement instead.

Compound statements may also be nested. In the above example, for instance, the for loop might contain a compound statement:

if (x==42)

{

for(int i=0; i<100; ++i)

{

std::cout<<i<<std::endl;

foo(i);

}

}

In this case, we print the value 0 and then call foo(0) on the first iteration of the loop, then print 1 and call foo(1), and so on. But since the for loop constitutes the entire compound of the if statement, we can eliminate the outer set of braces completely:

if (x==42)

for(int i=0; i<100; ++i)

{

std::cout<<i<<std::endl;

foo(i);

}

We can also create compound statements using commas to separate the individual statements. For instance, when we delete a pointer we will typically nullify the pointer straight away. Like so:

if (p)

delete (p), p=NULL;

The above is simply a shorthand for the following compound statement:

if(p)

{

delete(p);

p=NULL;

}

Program to count number of leaf node in binary tree in c plus plus?

Add the following recursive method to your binary tree's node class:

size_t Node::count_leaves()

{

if (!left && !right) return 1; // this node is a leaf

size_t count = 0;

if (left) count += left-count_leaves(); // count leaves on left

if (right) count += right-leaves(); // count leaves on right;

return count; // return total leaves.

}

To count the leaves of the entire tree, call the method on the root node of the tree. To count the leaves of a subtree, call the method on the root node of the subtree.

What is the purpose of getch()?

getch() is a way to get a user-inputted character. It can be used to hold program execution, but the "holding" is simply a side-effect of its primary purpose, which is to wait until the user enters a character. getch() and getchar() are used to read a character from screen.

What is called pointers-c plus plus?

Yes, C++ has pointers, which are references to memory locations. which are variables that store memory addresses, or NULL (zero). If the pointer is non-NULL, the pointer is said to dereference the object (or variable) residing at the stored memory address, which permits indirect access to that object so long as the object remains in scope.

Characteristics of constructor?

Contains an access modifier followed by the name of the class and some parameters. More specifically:

public class MyClass {

//Constructor

public MyClass() {

}

}

Can you use the same function name for a member functoin of a class and an outside function in the same program file?

Yes you can use the same function name for a member function and an external function. They are primarily distinguished by the number and type of arguments they accept (the function signature). If they match exactly, then the scope resolution operator (::) is used to differentiate them by namespace. The class namespace is the class name itself. The external function uses global scope unless scoped to another namespace. When the scope is not explicitly stated, then the scope is implied by the call site.

Note that whenever there is any ambiguity about which function is implied, the compiler will emit an error indicating where the ambiguity lies, and the program will ultimately fail to compile.

What key word is use as identifire in c programming?

A keyword identifier is one whose meaning has already been declared to the C compiler and we can't use it as variable,because if we want to do so we are trying to establish a new meaning to the keywords which is not permitted.

Who is the founder of C programming language?

C was developed by Dennis Ritchie at AT &T's Bell Laboratories of USA in 1972.

Is c is the subset of c?

No, C is its own language. However, C++ is another language that is based on C, but isn't really a "superset" of it. C++ introduces object-oriented-programming, which facilitates development much more easily than the original C. In fact, there are a whole class of languages based on C, including C# and C++. Note: The (ancient) predecessor of C was B.

Palindrome in c plus plus?

There are several ways to determine if a string is a palindrome or not. Typically, you must first ignore all spacing, capitalisation and punctutation within the string, which can be done by copying the string, character by character, ignoring all non-alphanumeric characters. You then point to the first and last characters in the modified string and, so long as both characters under the pointers are the same, work the pointers towards the middle of the string until the pointers either meet in the middle or they pass each other. That is, if the string has an odd count of characters, the pointers will meet at the middle character, otherwise they will pass each other. At that point you can say with certainty the string is a palindrome. If the characters under the pointers differ at any time, then the string is not a palindrome. This is fairly straightforward to program.

A more interesting problem is when you have to locate the longest palindrome within a string which is not itself a palindrome. For instance, the string "Madam, I'm Adam is a palindrome" is not a palindrome, but it does contain one: "Madam I'm Adam". In this case we cannot point to the first and last characters and work towards the middle. Instead, we have to test every possible substring of the string. We do this by starting at the first character and treat it as if it were actually the middle character of a palindrome, and then move our pointers to the left and right of this character while the characters match. When they no longer match, or one of the pointers has reached either end of the string, we store the longest palindrome found up to that point and then move onto the next character and treat it as the middle character. If we continue in this manner, treating every character as if it were the middle character of a palindrome, we will eventually locate the longest palindrome.

The problem with this approach is when the longest palindrome has an even number of characters instead of an odd number. To get around this we simply place a single space between each character, and treat each of those as being the middle character as well. When a palindrome is found, we simply remove the spaces. In this way we can use exactly the same algorithm to cater for both odd and even character palindromes.

The only remaining problem is when we wish to print the palindrome itself. Since this will be a substring of the original string, we cannot use the modified string we used to locate the palindrome. One way to get around that is to store the original positions of each letter in an array of indices, and use that array to determine where the substring lies with in the original string.

The following program demonstrates this technique in full. The key function is the ispalindrome() function, which accepts a lower-case copy of the string (including the original spacing an punctuation), and a vector that contains the indices of each letter within the string (ignoring puctuation and spacing), separated by -1 values (representing the implied spaces between each letter). The pos value tells the function which index of the vector is to be treated as the middle character of the potential palindrome, while x and y are output parameters that determine the start and end of the palindrome within the vector. The function returns true if a palindrome was found, and the x and y values can be used to extract the palindrome from the original string, using the indices stored in the vector. Note that when the search for a palindrome fails, we step back the x and y indices by one, and if the vector index is -1, then we step back another index. We then test the x and y values to see if they indicate a palindrome was found or not.

The strip() function is another key function. This generates the vector from the lower case copy of the original string. Although we could eliminate the -1 values at the start and end of the vector, it's simpler to just leave them in.

You will note that the program can cater for strings that are themselves palindromes, as well as strings that contain palindromes.

#include<iostream>

#include<string>

#include<vector>

using namespace std;

string input_string(string prompt)

{

cout<<prompt<<":\t";

string input;

getline(cin, input, '\n');

return(input);

}

void convert_tolower(string& s)

{

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

*i=tolower(*i);

}

vector<int> strip(const string& s)

{

vector<int> v;

v.push_back(-1);

for(int i=0; i<s.size(); ++i)

{

if((s[i]>='a' && s[i]<='z') (s[i]>='0' && s[i]<='9'))

{

v.push_back(i);

v.push_back(-1);

}

}

return(v);

}

bool ispalindrome(const string s, const vector<int> v, int pos, int& x, int& y)

{

for(x=pos,y=pos; x>=0 && y<v.size(); --x, ++y)

if( v[x]!=-1 && ( s[v[x]]!=s[v[y]] ))

break;

++x, --y;

if( v[x]==-1 )

++x, --y;

return(x>=0 && x<y && y-x>1);

}

int main()

{

string input;

while(1)

{

input=input_string("Enter a string");

if(input.size()==0)

break;

string copy(input);

convert_tolower(copy);

vector<int> v=strip(copy);

string pal;

int pos=0;

for(int i=0; i<v.size(); ++i)

{

int start=0, end=0;

if( ispalindrome( copy, v, i, start, end))

{

string tmp( input.substr(v[start],v[end]-v[start]+1));

if( tmp.size() > pal.size() )

{

pal = tmp;

pos = v[start];

}

}

}

if( pal.size() )

{

cout<<"Palindrome:\t";

for(int i=0; i<pos; ++i)

cout<<" ";

cout<<pal<<"\n"<<endl;

}

else

cout<<"The string contains no palindromes!\n"<<endl;

}

return(0);

}

Example output:

Enter a string: Madam, I'm Adam

Palindrome: Madam, I'm Adam

Enter a string: Madam, I'm Adam is a palindrome

Palindrome: Madam, I'm Adam

Enter a string: In girum imus nocte et consumimur igni

Palindrome: In girum imus nocte et consumimur igni

Enter a string: 0123456765432

Palindrome: 23456765432

Enter a string:

Press any key to continue . . .

How do you swap 2 variables without using third variable?

void main() { int a,b; clrscr(); printf("\n\n\t\tenter any two nos..."); scanf("%d%d",&a,&b); a=a+b; b=a-b; a=a-b; printf("\n\n\t\tvalue of a=",a); printf("\n\n\t\tvalue of b=",b); getch(); }