Write the algorithm to find the largest number of three number?
To determine the largest of any group of numbers, we must first determine the largest of any two numbers. For that we use the following simple algorithm:
If number A is greater than number B, then return number A otherwise return number B.
In C++ we can encode this algorithm using the following template function:
T& max( T& a, T& b) { return( a>b?a:b ); }
Using this one basic function we can build more complex functions to return the largest of any quantity of numbers. For instance, to return the largest of any three numbers, we would use the following:
T& max( T& a, T& b, T& c ) { return( max( max( a, b ), c )); }
To return the largest of any four numbers, we would use the following:
T& max( T& a, T& b, T& c, T& d) { return( max( max( a, b, c ), d )); }
We could continue in this fashion, but there is a much simpler approach: place all the values in a vector and return the maximum value of the vector. The following example demonstrates this with a vector containing 10 random values:
#include
#include
#include
template
T& max(T& a, T& b ) { return( a>b?a:b ); }
template
T max( std::vector
{
std::vector
int iResult = *it;
while( ++it != v.end() )
iResult = max( iResult, *it );
return( iResult );
}
int main()
{
srand(( unsigned ) time( NULL ));
std::vector
printf( "Array: " );
for( std::vector
{
*it = rand() % 100 + 1;
printf( "%d ", *it );
}
printf( "\n");
printf( "Largest: %d\n", max(v) );
return( 0 );
}
How do you convert postfix expression to prefix expression using c plus plus?
Let Q be an arithmetic expression written in infix notation. Besides operands and operators, Q may also contain left and right parentheses. We assume that the operators in Q consist only of exponentiations (↑), multiplications (*), divisions (/), additions (+) and subtractions (-), and that they have the usual three levels of precedence as given above. We also assume that operators on the same level, including exponentiations, are performed from left to right unless otherwise indicated by parentheses. (This is not standard, since expressions may contain unary operators and some languages perform the exponentiations from right to left. However, these assumptions simplify our algorithm.)
The following algorithm transforms the infix expression Q into its equivalent postfix expression P. The algorithm uses a stack to temporarily hold operators and left parentheses. The postfix expression P will be constructed from left to right using the operands from Q and the operators, which are removed from STACK. We begin by pushing a left parenthesis onto STACK and adding a right parenthesis at the end of Q. The algorithm is completed when STACK is empty.
69
Algorithm: POLISH(Q, P)
Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression P.
1. Push "(" onto STACK, and add ")" to the end of Q.
2. Scan Q from left to right and repeat Steps 3 to 6 for each element of Q until the STACK is empty:
3. If an operand is encountered, add it to P.
4. If a left parenthesis is encountered, push it onto STACK.
5. If an operator ⊗ is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator (on
the top of STACK) which has the same precedence as or higher precedence than ⊗.
(b) Add ⊗ to STACK.
[End of If structure.]
6. If a right parenthesis is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator (on
the top of STACK) until a left parenthesis is encountered.
(b) Remove the left parenthesis. [Do not add the left parenthesis to P.]
[End of If structure.]
[End of Step 2 loop.]
7. Exit.
The terminology sometimes used for Step 5 is that ⊗ will "sink" to its own level. .
70
EXAMPLE
Consider the following arithmetic infix expression Q:
Q: A+(B*C- (D/E↑F)*G)*H
We simulate the previous algorithm to transform Q into its equivalent postfix expression P.
First we push "(" onto STACK, and then we add ")" to the end of Q to obtain:
A + ( B * C - ( D / E ↑ F ) * G ) * H )
(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13)(14) (15) (16)(17) (18)(19) (20)
The elements of Q have now been labeled from left to right for easy reference. Table below shows the status of STACK and of the string P as each element of Q is scanned. Observe that
(1) Each operand is simply added to P and does not change STACK.
(2) The subtraction operator (-) in row 7 sends * from STACK to P before it (-) is pushed onto STACK.
(3) The right parenthesis in row 14 sends j and then I from STACK to P, and then removes the left parenthesis from the top of STACK.
(4) The right parenthesis in row 20 sends * and then + from STACK to P, and then removes-the left parenthesis from the top of STACK.
After Step 20 is executed, the STACK is empty and
P: A B C * D E F ↑ / G * - H * +
71
which is the required postfix equivalent of Q.
How to convert 2D array to single dimensional array?
You don't need to physically convert the array, you simply need to point at the first element and read the elements sequentially. The following code shows how to achieve this, as well as how to physically convert a 2D array to a separate 1D array. As can be seen, there is no practical benefit to making the conversion.
Example
#include
int main()
{
const int rows = 2;
const int cols = 3;
const int size = rows * cols;
// Create a static 2D array, intialise and print the matrix
int arr2[rows][cols];
std::cout << "2D array:\n" << std::endl;
for( int r=0; r { for( int c=0; c { arr2[r][c]= (r+1) * (c+1); std::cout << arr2[r][c] << " "; } std::cout << std::endl; } std::cout << std::endl; // Efficient conversion to 1D array: // Point to the first element then print sequential values. int* ptr = (int*) arr2; std::cout << "1D array (using pointer):\n" << std::endl; for( int i=0; i std::cout << *ptr++ << " "; std::cout << "\n" << std::endl; // Inefficient conversion to 1D array: // Copy the 2D array to a separate 1D array int arr1[size]; ptr = (int*) arr2; for( int i=0; i arr1[i]=*ptr++; // Print the copy: std::cout << "1D array (using copy):\n" << std::endl; for( int i=0; i std::cout << arr1[i] << " "; std::cout << "\n" << std::endl; return( 0 ); } Output 2D array: 1 2 3 2 4 6 1D array (using pointer): 1 2 3 2 4 6 1D array (using copy): 1 2 3 2 4 6
Multithreaded program generates Fibonacci series using java-answer?
The formula for the Fibonacci series is
Fn = Fn-1 + Fn-2 for n ≥ 2 with F0 = 0 and F1 = 1.
In layman's terms, in the Fibonacci series each successive number is the sum of the previous two numbers, starting with 1. So we have 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc
To do this in Java or any computer program you will need to create a recursive program, one that picks up previous values. This is quite easy, even for a beginner, once one grasps the Fibonacci fundamentals. Here is an example in Java:
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
For n, enter the number of values required, otherwise the increasing values of the results will overflow the parameters of the data display!
This code can be adapted for any progamming language, e.g. pascal, basic etc. One can even use the principles to construct a spreadsheet that will show the Fibonacci series in successive rows in Excel, for example.
What is an object and how are they created in object oriented programming languages?
Objects are the examples of the idea which the class represents. Objects of a class are constructed using the "new" keyword. For example: class Person { String name; } class Earth { public static void main(String... args) { Person sunny = new Person(); // Creating Object sunny.name = "Sunny"; } } Here, we have a class Person, the object of this class (in this case a person having name Sunny) is created from another class Earth using the keyword "new".
Write a program using do while loop?
char YorN; //I named this after Yes or No
do
{
cout<< "Do you want to continue (Y/N)? "; //You have to answer this with a 'Y' or 'N' to continue
cin >> YorN;
}
while((YorN !='Y')&&(YorN !='N')&&(YorN !='y')&&(YorN !='n')); //This ends the program when the user has -
entered either of these characters: 'Y', 'y', 'N', 'n'.
//The while keeps activating until YorN equals 'Y', 'y', 'N', 'n'.
I hope this has helped you! :D
What are the basic input and output of c and c plus plus?
That is STANDARD input and STANDARD output.
By default, standard input is the keyboard, and standard output is the screen. Standard I/O is set by the operating system, though it may be redirected by script invocation or system commands within the C/C++ program itself. You could, for instance, set standard output to a printer or a file in lieu of a screen.
You should also Google Standard Error.
How do you write a function in Turbo C Plus Plus?
// declaration:
return_type function_name([argument_type_1[=value][, argument_type_2[=value][, ...]]]);
// definition (function signature must match declaration):
return_type function_name([argument_type_1 argument_name_1[, argument_type_2 argument_name_2[, ...]]])
{
// implementation
}
In the case of separate declaration/definition, the definition file must include the file that contains the declaration unless they are both in the same file. If the function is a template function, both the declaration and the definition must be visible to the compiler BEFORE it can be used (thus they must both be in the same file). For all other functions other than inline expanded functions, only the declaration need be visible.
Note that the definition is also a declaration, however default values must be omitted and all arguments must be named. The declaration arguments may also be named but they needn't match those in the definition (the definition names are the ones actually used).
Alternatively:
// combined declaration and definition:
return_type function_name([argument_type_1 argument_name_1[=value][, argument_type_2 argument_name_2[=value][, ...]]])
{
// implementation
}
Functions that are defined in the declaration are impicitly inline expanded. Functions that are defined separately must be prepended with the inline keyword in the definition, and the definition must be visible to the compiler BEFORE the function can be used.
Functions that do not return a value must return void. If any other return type is specified, the function must explicitly return that type via all return paths. The main function must return an int, however return(0) is implied if not specified in the final statement.
Object files are intermediate files generated when an application is constructed from source code. In a classic compile-assemble-link toolchain, the compiler translates (C language) source code into assembly language output. The assembler translates this intermediate assembly source into a binary form known as object code. Files containing object code often have a .o or .obj file name extension and are generally called object files. The linker takes the object files and combines them into the complete executable.
While many modern tools hide the individual steps, or even integrate compilation and assembly into one, most (all?) compilers generate object files.
Derived data is data that is copied or enhanced from operational data sources into an informational database. This is in the information catalog center.
What is an object in C plus plus?
In c++
object is an instance of a class.class is an abstract data type.abstract data type means humen defined data type which is created in order to full fill the requirements of the problem.once we create a class ,we can have as many objects (of that class )as we want.
Difference between member functions and static member functions?
c: A static function is visible only in the source file containing it. A static member is not defined. c++: A static function is visible only in the source file containing it. A static member variable is common to all instances of a class. A static member function is used to access static members.
Is there any other keyword like goto in c plus plus?
The goto statement is a control flow statement that causes the CPU to jump to another spot in the code. This spot is identified through use of a statement label. The following is an example of a goto statement and statement label:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cmath>
int main()
{
using namespace std;
tryAgain: // this is a statement label
cout << "Enter a non-negative number";
double dX;
cin >> dX;
if (dX < 0.0)
goto tryAgain; // this is the goto statement
cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;
}
What is function overriding in C plus plus?
Overloading means to provide more than one function with the same function name in the same namespace. Overloaded functions must differ in the number and/or type of arguments they accept. The number and type of arguments constitutes the function signature, which is used to differentiate them. That is, the number and type of arguments you pass determine which instance of the function is called. The return value is not part of the signature, thus overloads cannot differ by return type alone.
Overriding relates to virtual functions where derived classes can provide more specialised implementations of generic methods. When you call the generic base class method implicitly, the most-derived override is called automatically, thus ensuring polymorphic behaviour; objects behave according to their actual type, even when the actual type cannot be determined in advance and without the need for expensive runtime type information. While a base class may be designed to be aware of some of its derivatives, it cannot be made aware of all its derivatives since new derivatives could be created at any time, by anyone with access to the base class definition. Overriding virtual functions ensures that base classes do not need to know anything about any of their derivatives, thus reducing the need for unnecessary coupling.
What is the method of constructor overloading in c plus plus?
Constructor overloading, just like any function's overloading, is where more than one configuration of parameters exists for the function. Based on the number and type of the parameters, different versions of the function can be resolved by the linker.
This is typically used in the constructor as the default constructor (no parameters), the copy constructor (one reference parameter of the same type as the class), and the conversion constructor (any other combination of parameters).
What are the situations where overloading function can be an ambiguity?
We know that compiler will decide which function to be invoked among the overloaded functions. When the compiler could not choose a function between two or more overloaded functions, the situation is called as an ambiguity in function overloading.
When the program contains ambiguity, the compiler will not compile the program.
The main cause of ambiguity in the program
· Type conversion
· Functions with default arguments
· Functions with pass by reference
Type conversion
#include
using namespace std;
#include
void fun(int i)
{ cout << i;}
void fun(float f)
{ cout << f;}
int main()
{
fun(10);
fun(10.2);
return 0;
}
In this example type conversion creates ambiguity. fun(10) will refer the first function.
We think the value 10.2 is floating point value. So fun(10.2) will refer the second function. But fun(10.2) will refer which function? It could not refer any function. Because 10.2 will be treated as double data type by the compiler. (In c++ all the floating point values are converted by the compiler as double data type.) This is type conversion of float to double. So now compiler could not search the function fun with double data type.
So the compiler will give error message call of overloaded 'fun(double)' is ambiguous.
This example clearly rises the ambiguity in the program because of the type conversion.
Functions with default arguments
#include
using namespace std;
#include
void fun(int i)
{ cout << i;}
void fun(int i, int j=8)
{ cout << i << j;}
int main()
{
fun(10);
fun(10.2f);
return 0;
}
This program will give error message that overloaded 'fun(int)' is ambiguous. Because the fun(int i, int j =8) is a function with default arguments. It can be called in two ways. They are
(i) function with one argument.
fun(2) now the value of i is 2 and j is 8 (8 is the default value).
(ii) function with two arguments fun(5,6). So i is 5 and j is 6.
fun(int i) is a function with one argument. It should be invoked with one argument. So
when we call a function with 1 argument the compiler could not select among the two functions fun(int i) and fun(int i, int j=8).
This example clearly illustrates the ambiguity in the program because of function with default arguments.
Function with reference parameter
#include
using namespace std;
#include
void fun(int i)
{ cout << i;}
void fun(int &i)
{cout <
int main()
{
fun(10);
return 0;
}
This program will show the error message call of overloaded 'fun(int)' is ambiguous.
First fun(int) takes one integer argument and second function fun(int &) takes a reference parameter. In this case, compilers do not know which function is intended by the user when it is called. Because there is no syntactical difference in calling the function between the function with single argument and function with single reference parameter.
So compiler could not decide which function should be invoked when it is called. So this leads ambiguity in the program.
What is a class in c plus plus how does it compare with structure in c?
A struct in C is a POD (plain old data) type. A class in C++ can also be a POD for backward compatibility with C code, but more typically combines data with methods that operate upon the data, including constructors and initialisers.
Classes in C++ can be declared using either the struct or class keyword. By convention you will typically use struct to define POD data types and class to define more complex data types.
The only practical difference between a struct and a class is that classes use private access and inheritance by default while struct uses public access and inheritance by default. Thus the following two class definitions are functionally the same:
struct A {
A():m_data(0) {} // public access by default
private:
int m_data;
};
class B {
int m_data; // private access by default
public:
B():m_data(0) {}
};
What is a valid c plus plus identifier?
In C++ we provide names for the entities we create, the variables, functions and types in our programs. These names, or identifiers, are required to conform to some simple rules.
An identifier must start with a letter and is comprised of a sequence of letters and digits. Somewhat surprisingly, in this context the underscore _ is considered to be a letter (although there are conditions associated with its use). There's no restriction on the length of an identifier.
How many essential functions are required to write a c program and write those?
One.
int main (void) { return 0; }
How is Java different than any other OOP language lke C plus plus?
There are many differences between Java and other programs, as there are also similarities: - managed code: java does not produce native code, but some byte code that will make it runnable in something called "virtual machine". The best thing about that: compile on windows and deploy that application on UNIX. - full object oriented -- even more than C++ where global variables are possible. Here, in java, everything must take place in an object - works on many operating systems. - a lot of technologies grouped in J2EE, that covers many the aspects of enterprise programming - servlets, jsp, ejb, jdbc to access the database, etc. The list is huge, I don't want to get in too much detail about that.
I guess it features some of the most mature technologies on the market.
Answer to: which programming language is more robust C sharp or Java?While I generally prefer "C" as a more robust language, I also consider anything that is released by Microsoft to be unreliable and likely to fail. Java is the product of Sun Microsystems, and has a very good reputation. While I'm not a Java programmer, I have heard nothing but good reports about Java. Answer to: why is Java more secure than other languagesJava is considered more secure than other languages for several reasons:1)Java is a purely Platform independent means the application that will work in any kind of Operating System.But .Net is platform independt software.
2).Net support to develop application in different languages and to develop application Rapidly. This feature is not exist in Java
Answer to why is Java more popular than CA long time ago, many people believed Java was slower than C because Java had to run through a virtual machine. Today however, Time and speed aren't really affected by the programming language or the used technology as much as affected by memory cards capacity and processors speed (Clock rate). Hench programmers and developers started looking for the most powerful yet easy to 'learn and work with' programming language. And there came Java with the multi-platform support, Object oriented methodology and other great capabilities and features.On the other hand, General Purpose applications are still developed using C++ because it doesn't need any intermediate software to run.
and i think that java it's been improved everyday by the newest releases of the implementation of the virtual machine.
What is the virtual keyword used for in C plus plus?
Virtual functions (or virtual methods as they are also known), are methods declared in a class that are expected to be overridden by a derived class. That is, the method is a generic method that applies to the class in which it is declared (the base class), but that may require modification by a more-specialised class (the derived class). When you implicitly call the base class method, the overridden method is called instead, thus ensure the correct behaviour. The overridden can still call the base class method explicitly, as can any other code that has access to the base class method.
If you do not declare generic methods to be virtual, overriding those methods in the derived class may have unexpected side-effects, particularly if the method is overloaded in the base class. For instance, a derived class' override will effectively hide all the overloads of the base class.
Note that if you declare any virtual function, then you are essentially notifying the end-user that the class is intended to act as a generic class and may be derived from, if required. However, if the function is declared pure-virtual, you are notifying the end-user that the class is abstract and mustbe derived from (it is not optional).
Also, if there are any virtual methods then the destructor must be virtual as well, to ensure the derived object is destroyed before the base class is destroyed.
It is often good practice to declare all methods as virtual if there's at least one virtual method, however this only applies to methods that would require alternative handling by more-specialised classes. If the base class can provide a complete implementation that requires no further specialisation, it needn't be declared virtual.
Although there is a memory cost involved in declaring virtual methods, the bulk of that cost is paid with the first virtual function which establishes the virtual table (v-table). Thereafter, the cost is minimal. The v-table ensures the most-derived method is called, thus ensuring correct behaviour of derived classes, even when working with the generic base class.
How you can access data member inside the main program in c plus plus programming language?
Public, protected and private accessors only apply to code outside of the class. Instances of a class (objects) have complete and unrestricted access to all their own instance variables (data members). They also have unrestricted access to the instance members of all other instances of the same class whenever those instances are passed as arguments to a class member method. Static methods of the class have the same privilege, as do friends of the class.
So the question isn't why an object can access its own public members without using an operator or member function. Any code outside of the class has that exact same right, but if an object has unrestricted access to its protected and private members, why should its public members be treated any differently?
C is a programming language.
Compiler is used to convert our source code which is in high-level language or human understandable code into machine language. Compiled source code can be executed any where once if it is compiled .
Meaning c plus plus pointer to an array and pointer to a structure?
They both mean the same thing; an array is a type of data structure (a linear structure). A pointer variable is just a variable like any other, but one that is used to specifically store a memory address. That memory address may contain a primitive data type, an array or other data structure, an object or a function. The type of the pointer determines how the data being pointed at is to be treated. Pointers must always be initialised before they are accessed, and those that are not specifically pointing at any reference should always be zeroed or nullified with the NULL value. This ensures that any non-NULL pointer is pointing at something valid. Remember that pointer variables are no different to any other variable insofar as they occupy memory of their own, and can therefore point to other pointer variables.
Write a program to count the number of characters words and lines in given text c plus plus?
#include<iostream>
#include<fstream>
int main()
{
std::ifstream infile ("example.txt", std::ios::in);
unsigned chars(0);
unsigned words(0);
unsigned lines(0);
std::string delim("\t\n ");
char ch(0);
char last(0);
if (!infile.good())
{
std::cerr << "The filename is invalid." << std::endl;
return -1;
}
while (infile.get(ch))
{
switch (ch)
{
case ('\n'):
++lines;
case (' '):
case ('\t'):
// only count words if the last char was not a word delimiter
if (delim.find(last) == std::string::npos)
++words;
default:
++chars;
}
last = ch;
}
infile.close();
std::cout << "Number of chars:\t" << chars << std::endl;
std::cout << "Number of words:\t" << words << std::endl;
std::cout << "Number of lines:\t" << lines<< std::endl;
}