How do you implement Pascal's Triangle in C plus plus?
There are many ways to implement Pascal's Triangle in C++. One of the easiest ways is to use a vector of vectors, which is essentially a two-dimensional dynamic array. Although you could use a static 2D array, the matrix would need to be sparse because the first row has only one value, while the second has two values, and so on. Unused elements would need to store the value zero, but unused elements are wasteful. You could improve upon this by creating a 1D array of dynamic arrays, however C++ vectors are much easier to work with and achieve the same thing.
The following program asks the user to enter the top value of the triangle and the number of rows in the triangle. The range of acceptable values has been limited to ensure all printed triangles will fit comfortably within an 80-character console window.
The program employs a simple class definition to encapsulate the triangle and its methods. The default constructor builds the triangle using the top value and the number of rows supplied from the user-input, while the print function displays the triangle's values in a symmetric triangle formation.
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<sstream>
// Some typdefs to simplify coding.
typedef unsigned int uint;
typedef std::vector<uint> row;
// Simple class definition.
class pascal_triangle
{
public:
pascal_triangle(uint top=1, uint rows=10);
void print();
private:
const uint get_width();
std::vector<row> m_triangle;
};
// Default constructor:
pascal_triangle::pascal_triangle(uint top, uint rows)
{
for(uint i=0;i<rows;++i)
{
row r;
uint x=top;
for(uint k=0;k<=i;++k)
{
r.push_back(x);
x=x*(i-k)/(k+1);
}
m_triangle.push_back(r);
}
}
// Return the width required for the largest value.
const uint pascal_triangle::get_width()
{
// Reference the last row of the triangle.
row& r=m_triangle[m_triangle.size()-1];
// Determine the largest value in that row.
uint largest=0;
for(uint i=0;i<r.size();++i)
if(r[i]>largest)
largest=r[i];
// Determine required width plus one space.
uint width=1;
do
{
largest/=10;
++width;
} while( largest );
// Return an even width.
return(width+width%2);
}
// Print the given triangle:
void pascal_triangle::print()
{
// Call private method to determine width.
const uint width=get_width();
// Repeat for each row...
for(uint i=0;i<m_triangle.size();++i)
{
// Insert half-width padding spaces.
std::cout<<std::setw((m_triangle.size()-i)*(width/2))<<' ';
// Print the row values.
row& r=m_triangle[i];
for(uint j=0;j<r.size();++j)
std::cout<<std::setw(width)<<r[j];
std::cout<<std::endl;
}
std::cout<<std::endl;
}
// Print the given range:
void print_range(const uint min,const uint max)
{
std::cout<<'['<<min<<".."<<max<<']';
}
// Return a natural number in the given range from user input:
uint enter_natural(const std::string& prompt,const uint min,const uint max)
{
uint result=0;
while(!result)
{
std::cout<<'\n'<<prompt<<' ';
print_range(min,max);
std::cout<<": ";
std::string in;
std::getline(std::cin,in);
std::stringstream(in)>>result;
if(result<minresult>max )
{
std::cout<<"The valid range is ";
print_range(min,max);
std::cout<<"\nPlease try again.\n"<<std::endl;
result=0;
}
}
std::cout<<std::endl;
return(result);
}
int main()
{
std::cout<<"Pascal's Triangle\n"<<std::endl;
uint top=enter_natural("Enter top value",1,10);
uint rows=enter_natural("Enter number of rows",2,10);
pascal_triangle t(top,rows);
t.print();
return(0);
}
What is the salary of a java programmer and a c plus plus c programmer?
Java programmers earn an average of £52,500.
C++ programmers earn an average of £57,500.
See sources and related links, below, for more information.
Program to perform binary search operations using dynamic memory allocation?
#include<iostream>
#include<iomanip>
#include<vector>
#include<algorithm>
#include<random>
#include<time.h>
void initialise (std::vector<unsigned>& data)
{
// Pseudo-random number generator (range: 1 to 99).
std::default_random_engine generator;
generator.seed ((unsigned) time (NULL));
std::uniform_int_distribution<unsigned> distribution (1, 99);
data.clear();
unsigned max_elements(50);
while (max_elements--)
data.push_back (distribution (generator));
}
int linear_search(std::vector<unsigned>& data, unsigned value, unsigned& comparisons)
{
int index(-1);
for( comparisons=0; comparisons<data.size() && index<0; ++comparisons)
if (data[comparisons] -1)
{
std::cout << "not found. ";
}
else
{
std::cout << "found at index " << binary_index << ". ";
}
std::cout << "Comparisons: " << binary_comparisons << std::endl;
}
}
How do you use array in template for two different data types in c plus plus programming language?
You simply instantiate the array for each type. That's the beauty of template (or generic) programming.
vector<int> myIntArray;
vector<double> myDoubleArray;
vector<myClass> myClassArray;
myDoubleArray.push_back(3.5);
myDoubleArray.push_back(6.7);
myDoubleArray.push_back(3.14159);
The myDoubleArray (actually, it called a vector, which is the container type most closely like an array) now contains 3.5, 6.7, 3.14159, and you can easily use them naively, as in myDoubleArray[1] is equal to 6.7, etc.
Of course, the power of STL containers is that you can use various algorithms on them, and you can create iterators to more easily traverse them, but this is enough to answer the question.
If the array is static you can simply point at the first element. For dynamic arrays you can allocate a contiguous block to a single pointer which can then be subdivided using a one-dimensional array of pointer to pointers, each of which points to a one-dimensional array of pointers, each of which points to a separate object within the array. For extremely large arrays, however, it is better to split the elements into separate one-dimensional arrays, by creating a one-dimensional array of pointer to pointers first, then allocating each of those pointers to a separate one-dimensional array of pointers, each of which points to a separate one-dimensional array of objects. Either way, you must destroy all the individual arrays in the reverse order of creation.
How do you program pyramid of letters using dev c plus programming?
#include
int main()
{
static int ROWS = 6;
char ch;
printf("Please enter an UPPERCASE letter:");
scanf("%c",&ch);
for( int row = 0; row < ROWS; ++row )
{
// Print padding.
for( int column = 1; column < ROWS - row; ++column)
printf(" ");
// Print letters left of centre.
for( int letter = row; letter >= 1; --letter)
printf("%c", ch);
// Print centre letter.
printf("%c", ch);
// print letters right of centre.
for( int letter = row; letter >= 1; --letter)
printf("%c", ch);
printf("\n");
}
return( 0 );
}
How many bytes are read in pointers by pointers dereferencing?
When you dereference a pointer you "read" the number of bytes determined by the pointer's type. That is, a char pointer dereferences a single byte while an int pointer dereferences 4 bytes (assuming a 32-bit int) -- regardless of the type actually stored at that address. However, note that a pointer can only actually point at a single byte since it only has storage for a single memory address. How many additional bytes are dereferenced is entirely dependant on the type of the pointer.
To determine how many bytes are actually allocated to an address, use the sizeof operator, passing a dereferenced pointer (the pointer must point at the start of the allocation). If the pointer points at several elements of the same type (an array), then divide the total bytes by the size of the pointer's type to determine the number of elements in the array.
What are advantages of visual c plus plus?
Well, there are really no disadvantages. If you are just starting programming, I would recommend using Visual Basic 2008. It is extremely easy to learn, and endless possiblities as far as making your program goes. The download link is right here: http://www.microsoft.com/express/vb/Default.aspx#webInstall It is free. If you are getting the registry key, make sure to use Internet Explorer.
Need a c program for a plus b plus whole square?
#include<iostream>
int main() {
std::cout << "Enter value a: ";
double a;
std::cin >> a;
std::cout << "Enter value b: ";
double b;
std::cin >> b;
double sum {a+b};
std::cout << "a + b + (a + b) * (a + b) = " << sum + sum * sum << std::endl;
}
mesh's basic salary is input through the keyboard. his dearness allowance is 40% of basic salarying , and house rent allowance is 20% of basic salaried. write a program to calculate his gross salary
In c plus plus program using class to represent the static data structure?
#include<iostream>
#include<trace.h> // user-defined trace macro
using namespace std;
class X
{
public:
X (int data=0)
: m_data (new int (data))
{
TRACE ("creating X @ 0x%x\n", this);
}
~X ()
{
delete m_data;
TRACE ("destroying X @ 0x%x\n", this);
}
X& operator += (int data)
{
*m_data += data;
return *this;
}
private:
int* m_data;
};
static X x = 0;
void foo()
{
TRACE ("entering foo()\n");
static X x = 0;
x += 1;
TRACE ("exiting foo()\n");
}
int main()
{
TRACE ("entering main()\n");
foo();
TRACE ("exiting main()\n");
}
Output:
1: creating X @ 0x24f698
2: entering main()
3: entering foo()
4: creating X @ 0x24f69c
5: exiting foo()
6: exiting main()
7: destroying X @ 0x24f69c
8: destroying X @ 0x24f698
Explanation of output:
1: The static global variable x is instantiated and initialised with the value 0. Note that instantiation occurs before entering main, even though main is the entry point of the application. The compiler has simply inserted the required code at the entry point, immediately in front of the main function code. Note also that this has nothing to do with x being declared static: if you remove the static keyword x would still be instantiated before main was invoked. Therefore x is implicitly static because it was declared at file scope.
2: The main function is invoked.
3. The foo function is invoked from main.
4. The static function variable foo::x is instantiated and initialised with the value 0.
Note that although foo:x is declared static, it does not physically exist until the function is called for the first time. This is because foo::x is scoped to the function.
5. Exit from the foo function.
Note that although foo::x is no longer in scope it is not destroyed at this point. This is because it was declared static. The function also incremented foo::x so foo:x will still have the value 1 if we call foo again, and will increment its value to 2.
6. Exit from the main function.
Normally the program would exit at this point. However, because we have 2 statics still in memory, the compiler has inserted code in place of the main function's closing brace to destroy the static objects.
7. foo::x is destroyed.
8. Global x is destroyed.
At this point the program can exit.
Output a prompt.
Either:
Read from standard input (std::cin) to an integer.
Or:
Read a line from standard input (std::getline()) to a string.
Create a string stream (std::stringstream) to read the string.
Read from the string stream to an integer.
For each integer from 2 to half the entered integer:
If the entered integer is divisible by the current integer:
The number is not prime.
Exit the program.
The number is prime.
Exit the program.
Overload plus operator for string concatenation in coding?
#include
using std::cout;
using std::endl;
#include
using std::string;
int main()
{
string s1( "AA" );
string s2( " AAB" );
string s3;
//
cout << "\n\ns1 += s2 yields s1 = ";
s1 += s2; // test overloaded concatenation
cout << s1;
return 0;
}
How do you enumerate all the possible subsets of x y z in C plus plus?
Enumerating subsets requires that each element in the set be mapped to a bit value. Combining these bit values (with logical OR) gives you the subset. Each subset will then have a value in the range 0 to 7, giving 8 subsets in all: {}, {x}, {y}, {z}, {x, y}, {x, z}, {y, z}, {x, y, z}. However, you cannot simply count from 0 to 7 to enumerate these subsets because this is highly inefficient. In a set of 3 it's not a significant loss, but in a larger set the inefficiency is substantial. For instance, in a set of just 64 elements, you must count from 0 to 9,223,372,036,854,775,809 in order to enumerate the 64 subsets that have just one element. If that doesn't drive the point home, then nothing will.
In order to correctly enumerate subsets you must use the Banker's sequence. Each sequence varies depending upon how many elements are in the set, however the sequence allows you to quickly enumerate one set after another in a logical sequence. It also allows you to start from anywhere in the sequence and continue from that point on, thus making it possible to quickly enumerate all sets with a specific number of elements.
The following code is quite involved but includes several auxiliary functions that help speed up the main code at the bottom. Some examples are included to demonstrate different usages, including the enumeration of subsets of {x, y, z}, subsets of a set of 5 elements and subsets of a subset of a 9 element set. Note that the final example (all subsets of a 32 element set) is commented out because it will take a seriously long time to enumerate all the possible subsets. However, the code is flexible enough to allow you to narrow the search down to just those subsets with a specific number of elements.
Note that the two main functions to focus upon are the find_first_subset() and find_next_subset() functions. These two functions are the driving force behind the Banker's sequence.
#include
// Returns the count of set bits in the given subset.
// E.g., 01010010 returns 3.
unsigned int count_set_bits( register unsigned int subset )
{
// An alternative method is to logical AND the bitset with 0x1
// then right shift the bitset by 1 bit. That requires an average
// of 32 separate operations (worst case is 64). This method always
// uses 17, thus always returns in constant time. For unsigned
// short, eliminate the last shift. For char, eliminate the last
// two shifts.
subset -= (( subset >> 1 ) & 0x55555555 );
subset = ((( subset >> 2 ) & 0x33333333 ) + ( subset & 0x33333333 ));
subset = ((( subset >> 4 ) + subset ) & 0x0f0f0f0f );
subset += ( subset >> 8 );
subset += ( subset >> 16 );
return( subset & 0x0000003f );
}
// Returns all set bits from the given subset's MSB down.
// E.g., 00100010 returns 00111111.
// The inversion of the return value can be used to mask
// bits that are greater than the MSB in another subset.
unsigned int fill_down( register unsigned int subset )
{
subset |= ( subset >> 1 );
subset |= ( subset >> 2 );
subset |= ( subset >> 4 );
subset |= ( subset >> 8 );
subset |= ( subset >> 16 );
return( subset );
}
// Returns the least-significant set bit in the given subset.
// E.g., 00100110 returns 00000010.
unsigned int get_LSB( register unsigned int subset )
{
return( subset ^ ( subset & ( subset - 1 )));
}
// Returns the most-significant set bit in the given subset.
// E.g., 00100110 returns 00100000.
unsigned int get_MSB( register unsigned int subset )
{
subset = fill_down( subset );
return( subset & ~( subset >> 1 ));
}
// Returns the first subset of subset_count within the given set.
// The return value can be passed to get_next_subset().
unsigned int get_first_subset( const unsigned set, unsigned int subset_count )
{
// Initialise the subset.
unsigned int subset = 0;
// Check validity of parameters.
if( subset_count && subset_count <= count_set_bits( set ))
{
// Assign the least-significant bit of set to subset.
subset = get_LSB( set );
// Repeatedly eliminate the LSB from set and
// combine the next LSB to subset until we've
// filled the subset up to the required count.
while( --subset_count )
subset |= get_LSB( set & ~fill_down( subset ));
}
// The first subset is complete (or is 0).
return( subset );
}
// Returns the next subset of the given bitset that follows previous_subset.
// The return value can be passed back to this function to get the next subset.
unsigned int get_next_subset( const unsigned set, const unsigned previous_subset )
{
// Initialise the next subset.
unsigned int next_subset = 0;
// Check validity of parameters.
if( previous_subset )
{
// Locate the MSB from the previous_subset.
unsigned int bit = get_MSB( previous_subset );
// Eliminate the MSB from the next subset.
next_subset = previous_subset & ~bit;
// Locate the next available bit in the set, if any.
if( bit = get_LSB( set & ~fill_down( bit )))
// The next subset is complete.
next_subset |= bit;
// Make recursive call using the set without its MSB
// Note: the subset we pass has already already been reduced.
else if( next_subset = get_next_subset( set & ~get_MSB( set ), next_subset ))
// Locate the next available bit in the original set
// At least one bit is guaranteed to exist: the MSB
// we eliminated from the recursive call.
next_subset |= get_LSB( set & ~fill_down( next_subset ));
}
return( next_subset );
}
// Prints the subset (only prints the least-significant count of bits).
void print_subset( unsigned int subset, unsigned int bits )
{
const unsigned int max_bits = 32;
if( bits > max_bits )
return;
unsigned int i = 0;
// Skip any redundant bits...
for( ; i // Begin printing. for( ; i std::cout << (( subset & 0x80000000 ) ? "1" : "0" ); std::cout << std::endl; } // Enumerate all subsets of set (only the least-significant count of bits), void enumerate_subsets( unsigned int set, unsigned int bits ) { std::cout << "From the set of:" << std::endl; print_subset( set, bits ); for( unsigned int subset_count = 0; subset_count <= count_set_bits( set ); ++subset_count ) { std::cout << "Subsets of " << subset_count << ":" << std::endl; unsigned int subset = get_first_subset( set, subset_count ); do print_subset( subset, bits ); while( subset = get_next_subset( set, subset )); } } // Enumerate all subsets of the set {x, y, z} void enumerate_subsets_xyz( void ) { unsigned int set = 1 | 2 | 4; // {x=1, y=2, z=4} unsigned int bits = 3; std::cout << "From the set of:\n{xyz}" << std::endl; for( unsigned int subset_count = 0; subset_count <= count_set_bits( set ); ++subset_count ) { std::cout << "Subsets of " << subset_count << ":" << std::endl; unsigned int subset = get_first_subset( set, subset_count ); do{ std::cout << "{"; if( subset & 1 ) std::cout << "x"; if( subset & 2 ) std::cout << "y"; if( subset & 4 ) std::cout << "z"; std::cout << "}" << std::endl; }while( subset = get_next_subset( set, subset )); } } // Test functions. int main() { // Enumerate all subsets of the set {x, y, z} (3 bits) enumerate_subsets_xyz(); std::cout << std::endl; // Enumerate all subsets of the set 11111 (5 bits) enumerate_subsets( 0x1f, 5 ); std::cout << std::endl; // Enumerate subsets of the subset 101010101 (9 bits total but only 5 selected) enumerate_subsets( 0x155, 9 ); std::cout << std::endl; //// Just for the hell of it, let's enumerate all possible sets for all 32 bits. //enumerate_subsets( 0xffffffff, 32 ); //std::cout << std::endl; return( 0 ); }
What are the essential characteristics of an object in c plus plus?
The only really essential characteristic is that every object of a class must have at least one constructor (besides a copy or move constructor) and must have a destructor. However it is not necessary to declare either if the compiler-generated default semantic provides the exact behaviour we require. There are some additional compiler-generated characteristics that, while not essential to every class of object, we need to be aware of.
If we do not provide any user-defined constructor for a class, X, the compiler will generate the following:
A default constructor may include formal arguments other than void, provided all formal arguments are declared with default values.
There are two "rules" that determine which of the above will be generated by the compiler:
Note: The second rule is partially enforced (as of C++11). For backward compatibility, copy constructors and copy assignments are generated even if a destructor is defined. However, that generation is deprecated in the ISO standard and you should expect a modern compiler to warn against it.
There are 5 situations where an object is either copied or moved:
There are three ways to initialise a new object from an existing object:
In all three cases, x is the new object (the one being initialised) while y is an existing object of the same type or of a type that has T as a public base. The first form is known as universal initialisation as it can be used anywhere an initialisation is required. The second form can be used anywhere a universal initialisation can be used, but is predominantly used to differentiate between an initialiser-list constructor and an "ordinary" constructor. The third form can only be used as an in-class initialiser. The following shows all forms of initialisation (only one in each group can actually be used).
class X {
// in-class initialisations
int i {0}; // ok
int i (0); // ok
int i = 0; // ok
// constructor initialisation lists
X (int ii): i {ii} {} // ok
X (int ii): i (ii) {} // ok
X (int ii): i = ii {} // compiler error: cannot use = in a constructor initialisation list!
};
An "ordinary" constructor is any constructor that accepts one or more non-default arguments besides a copy or move constructor. Conversely, initialiser-list constructors are typically used to initialise containers with element values. The following demonstrates the difference:
std::vector
std::vector
For consistency, universal initialisation is the preferred form (it makes it clear that an initialisation is taking place) unless we explicitly need to differentiate, as shown in above example. The third form should generally be avoided as it looks more like an assignment when it's actually an initialisation, however old habits die hard so we often use it in trivial initialisations, particularly with built-in types:
int main () {
int x = 42; // int x {42} is the preferred method
// ...
}
The difference between copy and move operations is that when we copy we create two independent objects with the same value as the source object. Thus x=y assures us that x==y when the copy is complete. When we move, x takes "ownership" of y's original value while y is left in a moved-from state. The moved-from state is non-specific, but it must be valid because the assumption is that y will fall from scope and must be in a valid state to do so.
When passing objects to functions by value, the object's copy constructor is always considered first. If no copy constructor is defined, the move constructor is used instead. But if neither copy or move is defined, objects of that class cannot be passed by value, they can only be passed by reference.
Conversely, when returning an object from a function by value, the move constructor is always considered first. If there is no move constructor, the copy constructor is used instead. But if neither exists, objects of that class cannot be returned by value, they can only be returned by non-local reference.
If an object has a copy or move constructor, it should also have a corresponding copy or move assignment operator. Not all objects are intended to be copied or moved, however most will support either or both. The difference between copy (or move) construction and copy (or move) assignment is that the constructor instantiates a new object from an existing object's value while an assignment assigns an existing object's value to an already-existing object. Assignment introduces the possibility of self-assignment, where an object's value is assigned to the same object. Self-assignment is a rare case, but we often have to guard against it. Consider the following:
void f (T& x, T& y) {
x = y;
}
In the above example, there is a possibility (however rare) that x and y may refer to the same object. If we look at a naive implementation of the move assignment operator we can better understand the problem:
class T {
int* ptr;
public:
T& operator= (T&&); // move assignment
// ...
};
T& T::operator= (T&& other) {
delete this->ptr;
this->ptr=other.ptr;
other.ptr=nullptr;
}
Here, an object of type T "owns" the resource pointed to by this->ptr and the intention is to move ownership of other.ptr to this->ptr. In order to take ownership of a another resource, we must first release the existing one, so we delete this->ptr. But what if other and this are the same object? This means that the resource referred to by other->ptr is also deleted -- they are one and the same resource -- the very resource we wanted to take ownership of! So when we assign other.ptr to this->ptr, we're left referring to the same invalidated memory we originally referred to. And when we assign nullptr to other.ptr, this->ptr is also assigned the nullptr, thus this->ptr is not referring to anything. To avoid this problem, we must guard against self-assignment:
T& T::operator= (T&& other) {
if (this == &other) return; // sanity-check!
delete this->ptr;
this->ptr=other.ptr;
other.ptr=nullptr;
}
Self-assignment guards are commonly referred to as sanity-checks, because the code would be insane without it and we simply cannot reason code that is insane.
Not all classes require self-assignment sanity checks when copying or moving via assignment. If our code can be reasoned such that self-assignment has no "side-effects", then we do not need to guard against it. Indeed, it would be a design-error to provide a sanity-check in the absence of side-effects, because self-assignment is (or should be) a rare occurrence, and a sanity-check would incur an overhead in all but those rare cases. Thus we only require sanity checks when we have side-effects to guard against.
Constructors and destructors interact correctly within class hierarchies. Constructors build objects "from the bottom up":
Destructors "tear down" an object in the reverse order it was constructed:
When a class declares a virtual method, this tells us that the class is intended to be used as a base class and that objects of the class have polymorphic behaviour. That is, we can invoke that method, we may not know the runtime type of the whole object, we only know its base class, however the most-derived override of that method will be invoked automatically thus ensuring correct behaviour. Any class that has a virtual method must also have a virtual destructor, because if any of its bases are explicitly destroyed, the most-derived class destructor must be invoked first to ensure the object is destroyed "from the top down", even if we do not know the runtime type of that object.
What is the program for snake and ladder game in c plus plus?
#include<iostream>
#include<array>
#include<string>
#include<random>
#include<ctime>
using player_t = std::array<unsigned, 2>;
using pair_t = std::pair<unsigned, unsigned>;
using snake_t = std::array<pair_t, 10>;
using ladder_t = std::array<std::pair<unsigned, unsigned>, 9>;
const std::string player (const bool human)
{
return std::string {human ? "You" : "I"};
}
int main()
{
std::default_random_engine generator ((unsigned) time (0));
std::uniform_int_distribution<unsigned> distribution (1, 6);
player_t players = {0,0};
const snake_t snakes = {pair_t {98,78}, {95,75}, {93,73}, {87,24}, {64,60}, {62,19}, {56,53}, {49,11}, {47,26}, {16,6}};
const ladder_t ladders = {pair_t {1,38}, {4,14}, {9,31}, {21,42}, {28,84}, {36,44}, {51,67}, {71,91}, {80,100}};
std::cout << "Snakes and Ladders\n";
std::cout << "==================\n\n";
std::cout << "First to land exactly on square 100 wins.\n";
bool human = (distribution (generator) % 2)==0 ? true : false;
std::cout << player (human) << " will go first.\n\n";
for (;;human=!human)
{
std::cout << (human ? "Your" : "My") << " turn:\n";
unsigned dice = distribution (generator);
std::cout << '\t' << player (human) << " rolled a " << dice << ".\n";
unsigned& pos = players [human?0:1];
if (pos+dice>100)
{
std::cout << '\t' << player (human) << " cannot move";
goto next_player;
}
pos+=dice;
std::cout << '\t' << player (human) << " landed on square " << pos;
for (auto snake : snakes)
{
if (snake.first==pos)
{
pos = snake.second;
std::cout << " with a snake; return to square " << pos;
goto next_player;
}
}
for (auto ladder : ladders)
{
if (ladder.first==pos)
{
pos = ladder.second;
std::cout << " with a ladder; climb to square " << pos;
goto next_player;
}
}
next_player:
std::cout << ".\n\n";
if (pos==100)
{
std::cout << player (human) << " won!\n";
break;
}
}
}
How does one write an algorithm that rounds off a decimal point to the nearest integer?
double round (double x) return (int) x + 0.5;
Why the background colour of turbo c plus plus is blue?
I want my C++ program become interesting
How can I change the color of background and color of font even size of font.........
I will always use
system("cls")
to clear there screen.....
so I want do C++ DOS into something we call presentation like powerpoint
Haha........
Any tutorial?
That all
Thank you
Why importance discrete mathematics for computer science?
Discrete math is essential to college-level mathematics and beyond.
Discrete math-together with calculus and abstract algebra-is one of the core components of mathematics at the undergraduate level. Students who learn a significant quantity of discrete math before entering college will be at a significant advantage when taking undergraduate-level math courses.
Discrete math is the mathematics of computing.
The mathematics of modern computer science is built almost entirely on discrete math, in particular combinatorics and graph theory. This means that in order to learn the fundamental algorithms used by computer programmers, students will need a solid background in these subjects. Indeed, at most universities, a undergraduate-level course in discrete mathematics is a required part of pursuing a computer science degree.
Discrete math is very much "real world" mathematics.
Many students' complaints about traditional high school math-algebra, geometry, trigonometry, and the like-is "What is this good for?" The somewhat abstract nature of these subjects often turn off students. By contrast, discrete math, in particular counting and probability, allows students-even at the middle school level-to very quickly explore non-trivial "real world" problems that are challenging and interesting.
Discrete math shows up on most middle and high school math contests.
Prominent math competitions such as MATHCOUNTS (at the middle school level) and the American Mathematics Competitions (at the high school level) feature discrete math questions as a significant portion of their contests. On harder high school contests, such as the AIME, the quantity of discrete math is even larger. Students that do not have a discrete math background will be at a significant disadvantage in these contests. In fact, one prominent MATHCOUNTS coach tells us that he spends nearly 50% of his preparation time with his students covering counting and probability topics, because of their importance in MATHCOUNTS contests.
Discrete math teaches mathematical reasoning and proof techniques.
Algebra is often taught as a series of formulas and algorithms for students to memorize (for example, the quadratic formula, solving systems of linear equations by substitution, etc.), and geometry is often taught as a series of "definition-theorem-proof" exercises that are often done by rote (for example, the infamous "two-column proof"). While undoubtedly the subject matter being taught is important, the material (as least at the introductory level) does not lend itself to a great deal of creative mathematical thinking. By contrast, with discrete mathematics, students will be thinking flexibly and creatively right out of the box. There are relatively few formulas to memorize; rather, there are a number of fundamental concepts to be mastered and applied in many different ways.
Discrete math is fun.
Many students, especially bright and motivated students, find algebra, geometry, and even calculus dull and uninspiring. Rarely is this the case with most discrete math topics. When we ask students what the favorite topic is, most respond either "combinatorics" or "number theory." (When we ask them what their least favorite topic is, the overwhelming response is "geometry.") Simply put, most students find discrete math more fun than algebra or geometry.
We strongly recommend that, before students proceed beyond geometry, they invest some time learning elementary discrete math, in particular counting & probability and number theory. Students can start studying discrete math-for example, our books Introduction to Counting & Probability and Introduction to Number Theory-with very little algebra background.
How do you write a program to demonstrate boolean operators in C plus plus?
#include
#include
class A
{
public:
A(std::string desc,double price):m_desc(desc),m_price(price){}
A(const A& rhs):m_desc(rhs.m_desc),m_price(rhs.m_price){}
A& operator= (const A& rhs){ m_desc=rhs.m_desc; m_price=rhs.m_price; }
const bool operator== (const A& rhs) const { return(m_desc==rhs.m_desc && m_price==rhs.m_price);}
const bool operator!= (const A& rhs) const { return(m_desc!=rhs.m_desc && m_price!=rhs.m_price);}
static void compare(const A& a, const A& b);
friend std::ostream& operator<< (std::ostream& os, const A& rhs);
private:
double m_price;
std::string m_desc;
};
std::ostream& operator<< (std::ostream& os, const A& rhs)
{
os< return(os); } void A::compare(const A& a, const A& b) { if ( a==b ) std::cout< // else if ( a!=b ) std::cout< } int main() { A a("Knife", 1.89); A b("Fork", 1.99); A c("Fork", 2.99); A d(a);
What operators in C were modeled on similar operators in ALGOL 68?
The short answer is probably these C operators +=, -=, *=, /= * %= are from Algol68′s +:=, -:=, *:=, /:= & %:=.
c.f. usenet: Ada and C and Algol 68
BTW: The best quote about C's ancestry comes from Dennis Ritchie himself:
"The scheme of type composition adopted by C owes considerable debt to Algol 68, although it did not, perhaps, emerge in a form that Algol's adherents would approve of. The central notion I captured from Algol was a type structure based on atomic types (including structures), composed into arrays, pointers (references), and functions (procedures). Algol 68′s concept of unions and casts also had an influence that appeared later." Apr 1993 c.f. Dennis Ritchie (April 1993). "The Development of the C Language" (PDF)
Note that the /= and /:= are subtly different. Also C's %= is the same as Algol's %*:= operator.
Note also that the majority of C's operators came from Algol (+ - * / = ≠ etc ). However the "%" operator is notability different.
* Wikipedia: Monadic_operators
* Wikipedia: Dyadic_operators_with_associated_priorities
C has the "return" and "sizeof" operator, whereas Algol68 has syntax "EXIT" (or "□") and operator "UPB" (or "⌈") that achieve a similar function.
Algol 68 also has some related constants: "max int", "max real", "int width", "real width" etc to determine sizes of things. These are not the same a C's sizeof, but similar.
The most peculiar operators of C's are /\ & \/, these come from Algol's ∧ & ∨ operators. These "C originals" were replaced by the current && and operators. c.f. What _did_ the C operators /\ and \/ do?
Algol68 further allows operators to be define using non-ASCII characters:
×, ÷, ≤, ≥, ¬, ∨, ∧, , ↓, ↑, ⌊, ⌈, ⎩, ⎧ and ⊥;
And used the characters →, ○, □, ␣ and ¢ for other purposes. It is kind of like Algol68 was taking the liberty of using unicode some 20 years before Unicode characters were defined. {Earlier Algol60 used non-ASCII ⊂ and ≡}
* C's: int i = b ? a : b; /* pick maximum */
* A68′s: INT i := ( a > b | a | b );
c.f. Wikipedia: ?: - a ternary operator
The assignment ":=" looks like an operator, but in terms of "Algol68″ OPerators it isn't. I believe they are called "Units associated with names" c.f. Array, Procedure, Dereference and coercion operations
(Or - if you are a language lawyer c.f. Algol 68 r1 report.html#52)
Similarly: Left assign, right assign and compare ( :=, =:, =) are also not "Algol68" Operators.
Pointers are not operators per se. There are a few "identity relations" associated with pointers: e.g. :=:, :/=:, IS & ISNT
c.f. Assignation and identity relations etc.
(Or - if you are a language lawyer c.f. Algol 68 r1 report.html#5221)
Why is passing a uint64 t to a function that takes uint64 t as the only argument ambiguous?
It is not ambiguous. There is something wrong with the question. Please restate the question.
How do you write a program to print Fibonacci series of n numbers using recursion in cpp?
#include<iostream>
unsigned fib (unsigned term, unsigned a=0, unsigned b=1)
{
if (term<1)
return a;
return fib (--term, a+b, a);
}
int main()
{
std::cout << "Fibonacci (1000th term): " << fib (1000) << std::endl;
}