How do you make a speed calculator in c plus plus?
To calculate speed you need to know the distance travelled and the time taken to travel that distance such that Speed = Distance / Time. The result of this calculation gives the average speed without taking into account any periods of acceleration or deceleration. We can implement this using just one function:
long double speed (const long double distance, const long double duration) {
return distance / time; }
Note that we use the term "duration" rather than "time" purely to aid readability; "time" implies a specific moment in time rather than a duration.
We use a long double to cater for the widest possible range of values. However, if we want to ensure the most efficient calculation over a wide variety of numeric types, we would use a function template instead:
template<typename T>
T speed (const T& distance, const T& duration) {
return distance / duration;
}
The distance and duration variables will typically be taken from input:
int main () {
double distance, duration;
std::cout << "Enter the distance and duration: "
std::cin >> distance >> duration;
std::cout << "Speed = " << speed (distance, duration) << '\n';
}
Note that the actual units of measurement are not important to the function because speed is denoted by the given distance per given time unit. That is, if we travel 100 meters in 10 seconds, then the speed is 10 meters per second, whereas if we travel 100 miles in 10 minutes, then we are travelling at 10 miles per minute. Thus when distance is 100 and duration is 10, the speed is 10. It is up to the caller to convert these units to something more meaningful:
int main () { double distance, duration; std::cout << "Enter the distance in kilometers: ";
std::cin >> distance;
std::cout << "Enter the duration in hours: ";
std::cin >> duration;
std::cout << "Speed = " << speed (distance, duration) << " kilometers per hour\n";
}
Note that the examples do not perform any error-checking upon the input. In production code when entering numbers from input you will typically input strings instead. You will then test the strings are valid before typecasting the strings to a numeric format such as double.
How to print the marks of 10 students in c plus plus?
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<random>
#include<time.h>
struct student_t
{
unsigned m_student_id;
std::string m_student_name;
student_t(const unsigned student_id, const std::string& student_name): m_student_id(student_id), m_student_name(student_name) {}
};
struct students_t : std::vector<student_t>
{
students_t() : std::vector<student_t> ()
{
push_back( student_t( 1, "Albert Black"));
push_back( student_t( 2, "Charlie Dawson"));
push_back( student_t( 3, "Eric Farrel"));
push_back( student_t( 4, "Gary Houston"));
push_back( student_t( 5, "Iain Jackson"));
push_back( student_t( 6, "Kevin Lawson"));
push_back( student_t( 7, "Michael Nicholson"));
push_back( student_t( 8, "Oscar Peterson"));
push_back( student_t( 9, "Robert Stevenson"));
push_back( student_t( 10, "Tony Urquart"));
}
};
struct subject_t
{
unsigned m_subject_id;
std::string m_subject_name;
subject_t(const unsigned subject_id, const std::string& subject_name): m_subject_id(subject_id), m_subject_name(subject_name) {}
};
struct subjects_t : std::vector<subject_t>
{
subjects_t() : std::vector<subject_t> ()
{
push_back( subject_t( 1, "English"));
push_back( subject_t( 2, "Mathematics"));
push_back( subject_t( 3, "Physics"));
push_back( subject_t( 4, "Biology"));
push_back( subject_t( 5, "Chemistry"));
push_back( subject_t( 6, "History"));
push_back( subject_t( 7, "Geography"));
}
unsigned max_length()
{
// Returns length of longest name.
unsigned max=0;
for (std::vector<subject_t>::const_iterator isubject=begin(); isubject!=end(); ++isubject)
{
const subject_t& subject = *isubject;
if (max < subject.m_subject_name.size())
max = subject.m_subject_name.size();
}
return max;
}
};
struct mark_t
{
student_t& m_student;
subject_t& m_subject;
unsigned m_mark;
mark_t(student_t& student, subject_t& subject, const unsigned mark): m_student(student), m_subject(subject), m_mark(mark) {}
mark_t& operator= (const mark_t& rvalue)
{
this->m_student = rvalue.m_student;
this->m_subject = rvalue.m_subject;
this->m_mark = rvalue.m_mark;
return *this;
}
};
struct marks_t : std::vector<mark_t>
{
students_t& m_students;
subjects_t& m_subjects;
marks_t (students_t& students, subjects_t& subjects) : std::vector<mark_t>(), m_students(students), m_subjects(subjects)
{
// pseudo-random number generator
std::default_random_engine generator;
generator.seed ((unsigned) time (NULL));
std::uniform_int_distribution<unsigned> distribution (0, 100);
for (std::vector<student_t>::const_iterator istudent=students.begin(); istudent!=students.end(); ++istudent)
{
student_t& student = const_cast<student_t&> (*istudent);
for (std::vector<subject_t>::const_iterator isubject=subjects.begin(); isubject!=subjects.end(); ++isubject)
{
subject_t& subject = const_cast<subject_t&> (*isubject);
push_back( mark_t(student, subject, distribution(generator)));
}
}
}
std::ostream& print (std::ostream& os)
{
unsigned last_student_id = 0;
for (std::vector<mark_t>::const_iterator imark=begin(); imark!=end(); ++imark)
{
const student_t& student = imark->m_student;
if (last_student_id != student.m_student_id)
{
if (last_student_id)
os << '\n';
last_student_id = student.m_student_id;
os << '#' << student.m_student_id << '\t' << student.m_student_name << ":\n" << std::endl;
}
const subject_t& subject = imark->m_subject;
os << '\t' << std::setw (m_subjects.max_length()) << subject.m_subject_name << '\t' << std::setw(3) << imark->m_mark << std::endl;
}
os << std::endl;
return os;
}
};
int main()
{
students_t students;
subjects_t subjects;
marks_t marks (students, subjects);
marks.print (std::cout);
}
What is contiguous memory in c plus plus?
Contiguous memory refers to a single block of consecutive memory addresses. All data types larger than a char require contiguous memory addresses.
For any given data type T, sizeof (T) tells us how many bytes of contiguous memory will be allocated to an object of that type:
std::cout << "sizeof (char) == " << sizeof (char) << std::endl;
std::cout << "sizeof (int) == " << sizeof (int) << std::endl;
std::cout << "sizeof (double) == " << sizeof (double) << std::endl;
struct X {/* ... */};
std::cout << "sizeof (X) == " << sizeof (X) << std::endl;
When we speak of contiguous memory, we don't usually refer to the number of bytes allocated to a given type; it can be taken as read that those bytes will be allocated contiguously such that the low-order byte refers to the whole object, regardless of its length.
Typically we use the term contiguous memory when referring to an array of objects. All objects in an array (the array elements) are exactly the same length (in bytes) and because they are allocated contiguously it is trivial to calculate the offset address of any one element relative to any other element in the same array. This is precisely how the array suffix operator works using only a zero-based index; the operator is nothing more than a convenient method of implementing pointer arithmetic. The upshot is that all arrays permit constant-time random access to any element in the array.
Arrays are dense data structures. That is, there is no additional memory required to maintain the structure. The only information we need to keep track of is the start address and the number of elements.
However, the downside of contiguous memory allocations is that whenever we wish to increase the amount of memory allocated we often have to move the entire allocation to new memory. The larger the allocation the more costly this becomes. Moreover, inserting new data means we must move elements to make room. This is why variable-length arrays typically reserve additional memory for moderate expansion while new elements are always pushed onto the end of the array rather than inserted in the middle.
Linked-lists are non-contiguous data structures which make use of additional memory to maintain links between the elements. As such, the elements need not move once allocated. If we want to change the element sequence or insert a new element into the sequence we simply update the affected links; the elements themselves remain wherever they were originally allocated.
Some data structures make use of both contiguous and non-contiguous allocations. A deque (a double-ended queue, pronounced deck) is a typical example because it is usually implemented as a linked-list of separate arrays. Each array is contiguous but the list of arrays is not necessarily contiguous.
How is a bitwise copy made in c plus plus?
A bitwise copy is what you automatically get when you do not provide a copy constructor. The compiler simply provides code that copies the object without regard to the type of the members. This is dangerous if any of the members happen to be pointers, because then you have two pointers to the same object and, if you delete one, you wind up having the other pointing to an object that has been deleted.
What happens to your car if you switch from regular to plus?
If your car runs well on regular fuel then you will see no change with plus fuel except it will cost you more. If you have problems with pre-ignition or "pinging" the plus fuel with it's higher octane rating will reduce or eliminate the pinging.
What is a program that calculates the sum of any 5 digit integer number entered by user?
#include<iostream>
unsigned sum_of_digits(unsigned num)
{
unsigned sum = 0;
do
{
sum += num%10;
} while (num/=10);
return sum;
}
int main()
{
unsigned number = 12345;
unsigned sum = sum_of_digits (number);
std::cout << "Sum of digits in " << number << " is " << sum << std::endl;
}
Manupulating strings and arrays together in c plus plus?
A string is an array; an array of character data types (char or wchar_t). Therefore anything you can do with an array you can also do with a string.
C does not have a built-in type for either an array or a string, but C++ does. In C, the programmer was entirely responsible for managing the memory allocated to an array. Built-in functions allowed us to determine the length of a null-terminated string, append strings, or alter the amount of memory allocated to an array, but the functions and the arrays were entirely separate. With C++, std::vector and std::string objects allow us to manipulate dynamic arrays and variable length strings, respectively, without having to worry about the underlying memory allocations. Since all the required methods are encapsulated within the objects themselves, they are much easier to work with.
For instance, in C, if we wanted to determine the length of a string we might call the strlen function:
char* str = "Hello world!";
unsigned size = strlen (str);
Arrays are a bit more difficult in that we must maintain a separate variable to keep track of an array's length:
unsigned size = 10;
int* arr = malloc(size);
size = 11;
arr = realloc(arr, size);
In C++, strings and arrays know their own length, so we don't need to call external functions or maintain separate variables:
std::string str = "Hello world!";
std::cout << '"' << str << '"' << " has " << str.size() << " characters\n";
std::vector<int> vect(10,0);
std::cout << "vect has " << vect.size() << " elements\n";
A vector of strings allows us to manipulate strings and vectors together. A vector of strings is essentially a two-dimensional dynamic array where each row is a string, and every string can have different lengths. The following therefore creates a vector with 10 empty strings:
std::vector< std::string > vstrings (10, "");
We can then manipulate each of the individual strings in the array:
vstrings[0] = "Hello world!";
vstrings[1] = "Another string.";
vstrings[2] = "The third string.";
...
vstrings[9] = "The string to end all strings.";
Each of these strings is a different length. With a traditional two-dimensional array each row would be the same length. In this case we'd need at least a 10 x 31 array (including null-terminators), which wastes memory when any string is less than 30 characters long. The only way to resolve this is to use a one-dimensional array of pointers to strings instead. Vectors of strings do the same thing, but they are much easier to work with since all memory management is handled by the objects themselves.
#include<iostream>
int main()
{
int matrix[3][3];
for (size_t row=0; row<3; ++row)
{
for (size_t col=0; col<3; ++col)
{
std::cout << "Enter a value for element [" << row << "][" << col << "]: ";
std::cin >> matrix[row][col];
}
}
std::cout << std::endl;
for (size_t row=0; row<3; ++row)
{
for (size_t col=0; col<3; ++col)
{
std::cout << matrix[row][col] << '\t';
}
std::cout << std::endl;
}
std::cout << std::endl;
}
server side networking application ServerSocket class is used, in this class method named as serversocket_object.accept() is used by server to listen to clients at specific port addresses, for local computer it is either "localhost" or "127.0.0.1" and might be u'r subnet address in case of some LAN.
How to write a c plus plus program to multiply matrices using function template?
#include<iostream>
#include<algorithm>
#include<cassert>
unsigned multiply_recursive (unsigned a, unsigned b)
{
if (!a !b) return 0; // Note: not(a) or not (b)
if (a==1) return b;
if (b==1) return a;
return a + multiply_recursive (a, --b);
}
unsigned multiply_iterative (unsigned a, unsigned b)
{
int product = 0;
int x = std::min (a, b);
int y = std::max (b, a);
while (x--)
product += y;
return product;
}
int main()
{
unsigned x, y;
// Test all combinations with 0.
x = multiply_recursive (0, 0);
assert (x==0);
x = multiply_iterative (0, 0);
assert (x==0);
x = multiply_recursive (0, 1);
assert (x==0);
x = multiply_iterative (0, 1);
assert (x==0);
x = multiply_recursive (1, 0);
assert (x==0);
x = multiply_iterative (1, 0);
assert (x==0);
// Test non-zero values with 1.
x = multiply_recursive (1, 42); // inefficient: lowest value must be on right (fewer recursions).
y = multiply_iterative (1, 42);
assert (x==42 && y==42);
x = multiply_recursive (42, 1);
y = multiply_iterative (42, 1);
assert (x==42 && y==42);
// Test other non-zero values are commutative.
x = multiply_recursive (24, 42); // inefficient: lowest value must be on right (fewer recursions).
y = multiply_iterative (24, 42);
assert (x==1008 && y==1008);
x = multiply_recursive (42, 24);
y = multiply_iterative (42, 24);
assert (x==1008 && y==1008);
}
C plus plus programs - to replace every space in a string with a hyphen?
char *string = "this is a test";
char *p;
for (p=string; *p!='\0'; p++) if (*p==' ') *p='-';
What does generic programming in c plus plus means?
Generic programming means that the code is generic enough that it compile on any C++ implementation. That is, it has no platform-specific code.
Why the name C plus plus was standardized?
C++ was originally called "C with Classes" as that effectively described the language at the time. Even the compiler simply produced a C source which could be compiled using any C compiler. However after template metaprogramming was introduced along with a dedicated compiler and other refinements to the language, it was no longer just C with Classes, it was the successor to C which, in the C language itself, would be written C++ (shorthand for C=C+1, although purists would argue it should really have been named ++C since C++ evaluates to C, not C+1).
The name C++ was never standardised, however the language was standardised in 1998 and the name simply became part of the recognised standard, the ISO C++ Standard. The standard has been revised several times since then and we refer to them using informal names such as C++98 and C++11. The current standard is informally known as C++14, officially identified as ISO/IEC 14882:2014, released in 2014. The next revision of the standard is informally known as C++17. There is no official designation at this time as the specification is currently under development, but it is expected to be "feature-complete" in 2017.
In C plus plus what is the meaning of cant?
It has no meaning in C++. The name "cant" is undefined and there is no "std::cant" name defined by the C++ standard library. It's most-likely a user-defined name, but without seeing the definition or context in which it used it's impossible to say what its meaning is. In all likelihood it's a constant Boolean value, where can is true and cant is false (or vice versa depending on the logic of its usage).
How do you split a string in delimit c plus plus?
#include<iostream>
#include<vector>
#include<string>
std::vector<std::string> parse (const std::string& s, const char delim)
{
std::vector<std::string> result {};
auto start = 0U;
auto end = s.find (delim);
while (end != s.npos)
{
result.push_back (s.substr(start, end - start));
start = ++end;
end = s.find (delim, start);
}
result.push_back (s.substr (start, s.npos - start));
return result;
}
std::vector<std::string> parse (const std::string& s, const std::string& delim)
{
std::vector<std::string> result {};
auto start = 0U;
auto end = s.find (delim);
while (end != s.npos)
{
result.push_back (s.substr(start, end - start));
start = end + delim.length();
end = s.find (delim, start);
}
result.push_back (s.substr (start, s.npos - start));
return result;
}
int main()
{
std::string str1 = "This is a string that will be parsed by a single-space delimiter.";
std::string str2 = "This==is==a==string==that==will==be==parsed==by==equal==operator.";
std::string str3 = "This string has no delimiter.";
std::cout << str1 << std::endl;
std::vector<std::string> v1 = parse (str1, ' ');
for (auto i : v1 )
std::cout << i << std::endl;
std::cout << std::endl;
std::cout << str2 << std::endl;
std::vector<std::string> v2 = parse (str2, "==");
for (auto i : v2 )
std::cout << i << std::endl;
std::cout << std::endl;
std::cout << str3 << std::endl;
std::vector<std::string> v3 = parse (str3, '\\');
for (auto i : v3 )
std::cout << i << std::endl;
std::cout << std::endl;
}
What is the definition of Punctuators and Operators in C plus plus?
The following are the C++ punctuators:
!
%
^
&
*
()
-
+
=
{}
|
~
[]
\
;
'
:
"
<
>
?
,
.
/
#
Some punctuators are also operators. The exact meaning of a punctuator is dependant upon the context. For instance, the open/close brace {} is used as a punctuator to delimit a class declaration, a function definition or a compound statement. But as an operator, it used to delimit an initialisation list.
The # punctuator only has meaning to the preprocessor, used to introduce a preprocessing directive.
Some punctuators can also be combined to produce other operators, such as:
::
.*
->
->*
&&
++
--
==
!=
<=
>=
+=
-=
*=
/=
%=
^=
|=
&=
<<
<<=
>>
>>=
?:
...
In addition, C++ also has the following punctuators as operators:
new
delete
and
and_eq
bitand
bitor
comp
not
not_eq
or
or_eq
xor
xor_eq
How do you draw a flow chart to find the average of three numbers?
Sum = Sum + first number
Sum = Sum + second number
Sum = Sum + third number
Average = 1/3 x Sum
Best bet is to do your research on the internet. As of this writing, I'm not aware of any that have Guide Plus as part of their programming. Strange though it may sound, I have it on my computer as it was supplied by the video card manufacturer. Update: The "LiteOn LVW-5045 DVR" uses Guide Plus. Here is a list of the products that use the Guide Plus service: http://www.europe.guideplus.com/En/our_service/models.html Note: There are DVRs and DVD-Rs in this list in addition to VCRs.
Write a c or c plus plus program to print first 50 odd numbers using do while loop?
unsigned count = 0;unsigned num=1;
do {
std::cout << num << std::endl;
num +=2;
} while (++count<50);
What is c plus plus program use to convert algorithm in to c plus plus program?
You can't convert an algorithm into code. That is the job of the programmer, not the language. Algorithm's are expressed in plain-English and typically use pseudocode to broadly demonstrate the implementation of the algorithm. However, it is the programmer's job to convert these algorithms into working code. Pseudocode isn't a programming language as such, but it uses structures and statements that are familiar to any programmer and can be easily translated into any language. However, pseudocode is not a standard so there are many different ways to present pseudocode to the programmer. Moreover, pseudocode is generalised and is far too generic to be converted directly into any one language, never mind C++, which can take advantage of the underlying hardware to produce more efficient algorithms than would otherwise be implied by the pseudocode alone. Hence the need for plain-English algorithms in conjunction with the pseudocode. Programmer's can process all this information far more easily than any computer can. Even if you could program a converter for one algorithm, there's no guarantee it would work for any other algorithm. The time spent programming an algorithm converter would be far better spent simply translating the algorithm yourself.
What is the brief history of visual c plus plus?
The complete history of Visual C++ can be found in the "Visual C++" article in Wikipedia.
Yes but then you would have to write two programs. One for your menu console and another for your order form console. The order form can be spawned from your menu. Am not sure why you you would want to develop this "restaurant" in a console instead of a fully-fledged Windows application, but each to his own...
What is referencing program c plus plus?
// Referencing
// Demonstrates using references
#include
<iostream>
using
namespace std;
int
main()
{
int myScore = 1000;
int& mikesScore = myScore; //create a reference
cout <<
"myScore is: " << myScore << "\n";
cout <<
"mikesScore is: " << mikesScore << "\n\n";
cout <<
"Adding 500 to myScore\n";
myScore += 500;
cout <<
"myScore is: " << myScore << "\n";
cout <<
"mikesScore is: " << mikesScore << "\n\n";
cout <<
"Adding 500 to mikesScore\n";
mikesScore += 500;
cout <<
"myScore is: " << myScore << "\n";
cout <<
"mikesScore is: " << mikesScore << "\n\n";
return 0;
}
How do you check a file is a binary or a text file through c programme?
There is no standard method of differentiating between the two because all files are binary files. Even text files must be binary encoded since that's the only encoding the computer can actually use. However, there are a few methods you can use to try and determine the encoding.
Text files only differ insofar as they only contain text (plain text) so one way we can differentiate is by examining the individual character values because there are certain characters we simply would not expect to find in a plain text file. All the ASCII control codes can be found in the range 0x00 through 0x1F (0 to 31 decimal) and the majority of these should not be present. The exceptions are 0x09 (horizontal tab), 0x0A (new line) and 0x0D (carriage return), all of which can reasonably be expected to be present in a text file.
However, plain text files may use other encodings besides ASCII. These alternative encodings typically use multi-byte encoding where a single character is composed from one or more bytes rather than just a single byte as with ASCII. These encodings are collectively known as UNICODE, however there are many variants, such as UTF-8, UTF-16, UTF-32 and so on. A UNICODE text file should (but doesn't always) include a byte order mark (BOM) at the start of the file. This is primarily used to determine if the multi-byte encoding is big-endian or little-endian but is also used to determine the specific encoding itself. So if the first few characters form a recognised BOM it is reasonable to assume (with a high degree of confidence) that the remainder of the file is multi-byte encoded text and the BOM itself will tell us precisely how to interpret it correctly.
The most common BOMs in use today are:
0xEFBBBF : UTF-8
0xFEFF : UTF-16BE (big-endien)
0xFFFE : UTF-16LE (little-endien)
0x0000FEFF : UTF-32BE
0xFFFE0000 : UTF-32LE
0xF7644C : UTF-1
0xDD736673 : UTF-EBCDIC
0x0EFEFF : SCSU
0xFBEE28 : BOCU
0x84319533 : GB-18030
UTF-7 has several BOMs, each of which begins 0x2B2F76:
0x2B2F7638
0x2B2F7639
0x2B2F762B
0x2B2F762F
0x2B2F76382D
When looking for a BOM, always look for the largest BOM first.
If there is no BOM present and the file does not appear to be ASCII plain text, there may be an HTML-style header at the start of the file that provides us the actual encoding. For instance, the following header tells us that this file uses UTF-8 encoding:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
UTF-16 and UTF-32 encodings that do not include a BOM or a plain-text header can often be deduced by examining all the null bytes (0x00) bytes in each group of two or four bytes. If the majority appear on either the odd or even bytes, then the encoding is probably UTF-16LE or UTF-16BE. Similarly with UTF-32 if the majority of odd or even pairs of bytes are 0x0000 (check for these before checking for UTF-16).
If none of these methods can determine the encoding, the best thing to do is alert the user that it is not possible to deduce the encoding, and perhaps allowing them to choose the correct encoding for themselves.
Note also that when presenting plain text, it is important that you also use the appropriate character set in combination with the correct decoding method. Even with the correct decoding method, the text may still appear garbled if the wrong characters are being represented.