What is static in c plus plus programming?
The keyword "static" in C has a slightly complicated meaning, depending on where it is used. It generally denotes static storage, meaning that it is allocated in the static data area of the program, and not on the stack or heap. Also, it generally limits the visibility of the name to a certain area of the code.
If used on a variable or function of global scope, then it generally means that the function or variable can only be used by other functions within the same file, as opposed to "extern" which means that the variable and function can be used from other files.
If used on a local variable within a function, it means that the variable maintains its value between function calls (since it is allocated statically and not on the stack).
//Quicksort the array
void quicksort(int* array, int left, int right)
{
if(left >= right)
return;
int index = partition(array, left, right);
quicksort(array, left, index - 1);
quicksort(array, index + 1, right);
}
//Partition the array into two halves and return the
//index about which the array is partitioned
int partition(int* array, int left, int right)
{
//Makes the leftmost element a good pivot,
//specifically the median of medians
findMedianOfMedians(array, left, right);
int pivotIndex = left, pivotValue = array[pivotIndex], index = left, i;
swap(array, pivotIndex, right);
for(i = left; i < right; i++)
{
if(array[i] < pivotValue)
{
swap(array, i, index);
index += 1;
}
}
swap(array, right, index);
return index;
}
//Computes the median of each group of 5 elements and stores
//it as the first element of the group. Recursively does this
//till there is only one group and hence only one Median
int findMedianOfMedians(int* array, int left, int right)
{
if(left == right)
return array[left];
int i, shift = 1;
while(shift <= (right - left))
{
for(i = left; i <= right; i+=shift*5)
{
int endIndex = (i + shift*5 - 1 < right) ? i + shift*5 - 1 : right;
int medianIndex = findMedianIndex(array, i, endIndex, shift);
swap(array, i, medianIndex);
}
shift *= 5;
}
return array[left];
}
//Find the index of the Median of the elements
//of array that occur at every "shift" positions.
int findMedianIndex(int* array, int left, int right, int shift)
{
int i, groups = (right - left)/shift + 1, k = left + groups/2*shift;
for(i = left; i <= k; i+= shift)
{
int minIndex = i, minValue = array[minIndex], j;
for(j = i; j <= right; j+=shift)
if(array[j] < minValue)
{
minIndex = j;
minValue = array[minIndex];
}
swap(array, i, minIndex);
}
return k;
}
//Swap integer values by array indexes
void swap(int * array, int a, int b)
{
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
What is the difference between object-oriented and procedural programming?
Procedural programming can sometimes be used as a synonym for imperative programming. To a programming paradigm based upon the concept of the procedure call. Procedures, also known as routines, subroutines, methods, or functions (not to be confused with mathematical functions, but similar to those used in functional programming) simply contain a series of computational steps to be carried out. Any given procedure might be called at any point during a program's execution, including by other procedures or itself. The important features of Procedural Programming. 1. Programs are organized in the form of subroutines and all data items are global. 2. Program controls are through jump(goto) and calls to subroutines 3. Subroutines are abstracted to avoid repetitions. 4. Suitable for medium sized software application 5. Difficult to maintain and enhance the program code. K E Narayana
When destructor can be virtual in c plus plus?
A class constructor initialises object member variables, ensuring the object is in a valid state from the point of instantiation. The destructor resets those same variables when the object falls from scope. Typically, the destructor is only required to release any memory allocated to any internal class pointers.
What is data type in c plus plus?
A data type simply means the type of data represented by a variable or constant, or the return type of a function. C++ is a strongly-typed language thus all variables and constants must have a data type associated with them. The data type may be a primitive data type such as int or char, which are used as the building blocks for more complex data types. Primitives, typedefs, enums and classes (which includes structs and unions), are used to provide the definitions for all the various data types that you can employ within a program. Variables and constants provide instances of those data types. Pointer variables must also have a data type associated with them to determine the type of data being referred to, even if it is void* which simply means it points to any data type, the actual data type being determined at runtime. However, in C++, void* is rarely required since polymorphism allows programmers to treat objects generically; there is rarely a need to know the actual runtime type of an object, since that information is provided automatically by the object's own virtual table. The programmer need only know the generic data type and call the appropriate virtual methods of that type in order to invoke the specific behaviour of the actual data type.
What is the for loop in c plus plus?
In C, also in C++, the for loop executes zero or more times, until the test expression is false...
for (init-expression; test-expression; loop-expression) statement;
/* init-expression executed once, at beginning */
/* statement executes zero or more times, until test-expression is false, test first */
/* loop-expression evaluated at end of each iteration */
The set of datatypes and the definition of each member is dependent on hardware, the language standard, and the language implementation. Not knowing which language the question relates to is particularly limiting.
In Java, a long consists of 8 bytes. This is also generally true for C and C++, depending upon the compiler used. See the related links for further details.
Why is C plus plus such a robust programming language?
Borland's implementation of C++ was never regarded as the Bible of Computer Programming (whatever that means). If it were we'd probably still be using it today, but it was rendered obsolete in 1997 when Borland C++ Builder superseded it.
What is difference between constant in c plus plus and final in java?
The final keyword can be used to modify a class, method, or variable.
When used on a variable, it means that variable cannot be changed once set.
When used on a method, it means that no subclasses may override that method.
How can you pass variable arguments to a function in c?
## posted BY Pulkit ok. so to declare variable argements in arguments use this: ret_type function_name( . . .); using these three dots will tell compiler to include variable aarguments. Note: this feature has been included in New version of C,, this is not available in old compiler. thankx guys n grls ## posted BY Pulkit ok. so to declare variable argements in arguments use this: ret_type function_name( . . .); using these three dots will tell compiler to include variable aarguments. Note: this feature has been included in New version of C,, this is not available in old compiler. thankx guys n grls
Write a program in c plus plus to compute the factorial of a given number?
#include
#include
void main()
{
int n;
long f,fact(int b);
clrscr();
printf("\n\n\t Enter a Number(B/W 0 to 31)::");
scanf("%d",&n);
if(n>=32)
{
printf("\n\t Enter a number between 0 to 31");
exit 0;
}
f=fact(n);
printf("\n\t The Factorial of %d is %ld",n,f);
getch();
}
long fact(int b)
{
int i;
long f=1;
for(i=1;i<=b;i++)
{
f=f*i;
}
return f;
}
How do you implement a stack using an array in c plus plus?
An array in C++ is fixed-size and is unsuitable for implementing stacks. You can use a C-style dynamic array, of course, but the C++ method is to use a vector. A vector encapsulates a C-style dynamic array along with its size and greatly simplifies the way you work with arrays.
Dynamic arrays are generally the best way to implement a stack, however be aware that when the array is full and you want to add a new element, you must reallocate the array which can occasionally cause the entire array to be moved to new memory. A vector, on the other hand, automatically reserves 1.6 times the consumed memory on each reallocation and thus minimises the need to reallocate.
Vectors provide a push_back() and pop_back() method, since these are the fastest methods of inserting and extracting elements from an array (inserting or extracting anywhere else would result in elements being shunted up and down the array, which is inefficient). These two methods alone are all you need to implement a stack. However, vectors also permit random access to any element within the array. To eliminate all unnecessary features, you must encapsulate the vector within an adaptor class (a thin-wrapper) that only exposes the functionality you actually need. A minimal implementation is presented here:
#include<vector>
template<typename T>
class stack
{
std::vector<T> m_data;
public:
stack() =default;
~stack() =default;
stack(const stack&) =default;
stack(stack&&) =default;
stack& operator= (const stack&) =default;
stack& operator= (stack&&) =default;
void push (const T& data) {m_data.push_back (data);}
void pop () {m_data.pop_back ();}
T& top () {return m_data.back();}
const T& top () const {return m_data.back();}
};
This is fairly similar to the way a std::stack is implemented in the STL, although it also provides specialisations for pointer types. For more information on the implementation, consult the <stack> header in the standard library.
What types of functions cannot be made virtual?
Static member functions, member function templates and constructors cannot be virtual.
Which program can you use to write C Plus Plus scripts?
You can use any text editor you want, say notepad in windows and vi in unix. You can also use MS Word, but you need to save in text format, i.e. with no formatting, because the compiler only understands the text, and not the formatting.
Often, however, the text editor is part of an integrated development environment, that makes it easier to highlight code and errors, organize classes and modules, and to debug visually. In the Windows environment, that might be Visual Studio, but it can be any supported product for your platform.
How do you write a C program to print the diagonal element of a NxN matrix?
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],r,c;
for(r=0;r<=3;r++)
{
for(c=0;c<3;c++)
{
printf("\n enter the value=");
scanf("%d%d",&a[r][c],&b[r][c]);
}
}
printf("\n first matrix=\n");
for(r=0;r<=3;r++)
{
for(c=0;c<3;c++)
{
printf("%d\t",a[r][c]);
}
printf("\n");
}
printf("\n scond matrix=\n");
for(r=0;r<=3;r++)
{
for(c=0;c<3;c++)
{printf("%d\t",b[r][c]);
}
printf("\n");
}
printf("\n sum of given matrix=\n");
for(r=0;r<=3;r++)
{
for(c=0;c<3;c++)
{
c[r][c]=a[r][c]+b[r][c];
printf("%d\t",c[r][c]);
}
printf("\n");
}
getch();
}
What do you mean by inheritance . give example from c plus plus?
Inheritance in C++ is where you derive a new object from an existing object. The derived object is simply a more specialised version of the original object. The existing object could be a generic car object from which we could derive a more specific type of car such as the Aston Martin DB9. Moreover, if we have a DB9 object then we could just as easily derive an even more specific DB9 such as the Aston Martin DBR9.
In other words, the DB9 inherits all the properties that we might associate with a car, such as a chassis, 4 road wheels, a steering wheel, an engine and gearbox, and a body. By the same token, the DBR9 inherits all the properties of a DB9 (and therefore all the properties of a car), retaining the chassis, engine block and cylinder heads from the DB9 whilst adding high performance components elsewhere.
This is, of course, an over-simplification. But when we model the real-world within a computer we never model the real-world in minute detail, we only model part of the real-world (and usually just a minuscule part of it), and only in as much detail as we need in order to solve a problem. For instance, if we wished to model traffic flow through a city, we don't necessarily need to know how many DB9s are passing through. That "a car" passed through is probably all we need to know. But that car could be derived from a more generic "road-vehicle" object, which would then allow us to model buses, trucks, motorbikes and push bikes.
When modelling the real-world it's important to identify early on which objects are real and which are purely conceptual. In our DB9 example, the car object is best described as being a purely-conceptual object -- an abstraction -- but in our traffic flow model that same car could be a real object. Or it could be conceptual if we wished to distinguish between petrol, diesel, electric and hybrid cars.
In C++ there are several inheritance models. Single inheritance is fairly straightforward and describes how one type of object is directly derived from another type of object. When discussing the type of an object we are referring explicitly to its class, and it is the class that defines the type of inheritance.
Multiple inheritance describes how one class is directly derived from two or more distinct classes. You might use this type of inheritance when describing a hybrid car, since it is derived from both a petrol and an electric car. Or an amphibious landing craft which is both a car and boat.
Multi-level inheritance occurs when a generic class is also a derived class. In our DB9 example, the DB9 is generic with respect to the DBR9, but also derived with respect to the car. Most of the time this is of little concern since the derived object is only really concerned with the generic class or classes from it was directly derived. However, occasionally it leads to an inheritance model that can sometimes be problematic if not handled correctly: virtual inheritance.
Virtual inheritance describes the way in which a derived object inherits from two or more generic objects, and those generic objects are themselves derived from a common generic object. Going back to our hybrid example, we can see how this works in the real-world. Our hybrid car obviously inherits from both a petrol and an electric car, but both of these could inherit from the generic car. The problem is that this means there are two instance of the generic car within our hybrid, but the hybrid is just one car. When we refer to the car class directly from our hybrid, there is ambiguity because there's no way to determine which instance of car we are actually referring to. Virtual inheritance gets around this ambiguity by allowing both petrol and electric cars to inherit from car virtually, rather than directly.
What this means is that our hybrid (and any derivative of hybrid) inherits directly from one instance of car, while our electric and petrol cars both share this one instance, virtually. An electric car, by itself, will still inherit directly from car, as will a petrol car, since they are both the most-derived classes in those specific models, but our hybrid or any derivative of hybrid renders the car a virtual class. With only one instance of car, all ambiguity is removed.
Now that we've discussed how inheritance works in principal, we can examine
the ways in which we can modify access to the generic class members with respect to the derived class. Inheritance may be done with private, protected or public access. When not explicitly stated, the default is private access for classes and public access for structs (exactly the same as would apply to the class member access specifiers). Regardless of the access specified via inheritance, derived classes always inherit all the public and protected members of their generic classes. All we're really doing is modifying their visibility with respect to the derived class. However, private members of the generic class are never inherited, and we can never elevate access, we can only keep it the same, or reduce it. Any member with greater access to the specified access will be reduced to the specified access. Thus if we specify public access, all generic members maintain their current access. If we specify protected access, all public members of the generic class become protected members of the derived class. And with private access, all public and protected members become private members of the derived class.
Normally we will alter the access via the inheritance declaration itself, which applies to the generic class as a whole. However, we can also modify the access to individual members, simply be redeclaring them with the new access type, thus giving us fine granular control over every public and protected member that is inherited.
The following code examples demonstrate some of the principals thus far described.
class A {};
class B : public A {}; // single inheritance
class C : public B {}; single-inheritance, multi-level
class D : virtual public C {}; virtual single inheritance, multi-level
class E : virtual public C {}; virtual single inheritance, multi-level
class F: public D, public E {}; virtual multi-inheritance, multi-level
All these examples are non-functional since the declarations have been left empty. However, they describe the bare essentials required of inheritance. All access to the generic classes is declared public, so there would be no changes to how the base class members are accessed with respect to the derived class.
Most classes that are intended to act as generic classes will include one or more virtual methods (virtual functions). This simply means that derivatives are expected to override those methods as required in order to provide a more specific implementation. If the generic implementation suffices, there is no need to override it. However, it's important to remember that if there is one or more virtual functions in the generic class, the generic class destructor must also be virtual.
When a generic class is intended to act as a conceptual class or an abstract data type, then it must have at least one pure-virtual method. What this means is that the derived class must override all pure-virtual methods otherwise it becomes an abstract class itself. Once a derivative implements an override, that override reverts to being a virtual method which can subsequently be inherited, even if the the derived class remains abstract. The generic abstract class may or may not provide implementations for its pure-virtual methods, but any that are provided cannot be inherited (only the signature is inherited), and can only be called explicitly via a derived class override. Note that abstract base classes cannot be instantiated by themselves -- remember they are conceptual objects, not actual objects. They can only be instantiated through inheritance and only by providing (or inheriting) a complete implementation of the abstract interface.
To understand abstraction, consider a shape object. There is no such thing as a shape, there are only types of shape. Thus a shape is the concept of an object, whereas a circle, square or triangle are the physical embodiment of shape objects, and therefore inherit all the properties of shape; everything that is common to all shapes such as vertices, colour, a bounding rectangle (which is itself a shape), and so on. To use another analogy, a mammal is a conceptual object whereas a Golden Labrador is a specific type of mammal. Depending on the amount of detail you require in your model, a dog could be considered an actual object if you weren't interested in specific types of dogs, or conceptual if you were. If you were only interested in mammals and reptiles, then animal objects would be considered conceptual. And so on.
Is call by reference and pass by reference same thing?
Strictly speaking there is no such term as call by value. Functions are called while parameters are passed. When someone uses the term call by value they really mean pass by value, so in that sense they are the same. However call by value is incorrect terminology.
Menu driven program for selection sort bubble sort and insertion sort in c?
#include<iostream>
#include<time.h>
#include<iomanip>
#include<string>
void swap(int& x, int& y)
{
x^=y^=x^=y;
}
void bubble_sort(int* A, int size)
{
while(size)
{
int n=0;
for(int i=1; i<size; ++i)
{
if(A[i-1]>A[i])
{
swap(A[i-1], A[i]);
n=i;
}
}
size=n;
}
}
void insertion_sort(int* A, int size)
{
for(int i=1; i<size; ++i)
{
int value=A[i];
int hole=i;
while( hole && value<A[hole-1] )
{
A[hole]=A[hole-1];
--hole;
}
A[hole]=value;
}
}
void selection_sort(int* A, int size)
{
for(int i=0; i<size-1; ++i)
{
int j=i;
for(int k=i+1; k<size; ++k)
if(A[k]<A[j])
j=k;
if( i!=j )
swap(A[i],A[j]);
}
}
void sort(int* A, int size, int sort_type)
{
switch(sort_type)
{
case(0): bubble_sort( A, size );
case(1): insertion_sort( A, size );
case(2): selection_sort( A, size );
}
}
int* copy_array(int* A, int size)
{
int* copy=new int[size];
memcpy(copy, A, size*sizeof(int));
return(copy);
}
void print_array(int* A, int size, char* prompt)
{
std::cout<<prompt<<"\t";
for(int i=0; i<size; ++i)
std::cout<<std::setw(2)<<A[i]<<" ";
std::cout<<std::endl;
}
int get_rand(int range_min=0, int range_max=RAND_MAX)
{
return((int) ((double)rand() / (RAND_MAX + 1) * ((range_max + 1) - range_min) + range_min));
}
int input_char(std::string prompt, std::string input)
{
char ch;
do
{
std::cout<<prompt<<": ";
std::cin>>ch;
}
while(input.find(ch)==std::string::npos);
return(input.find(ch)%(input.size()/2));
}
int main()
{
srand((unsigned) time(NULL));
int size = get_rand( 10, 80);
if( int* A = new int[size] )
{
for( int i=0; i<size; ++i )
A[i]=get_rand( 1, size );
int choice=input_char("Please select a sorting method:\n[B]ubble, [I]nsert, [S]election", "bisBIS");
std::cout<<"You chose ";
switch(choice)
{
case(0): std::cout<<"bubble"; break;
case(1): std::cout<<"insertion"; break;
case(2): std::cout<<"selection"; break;
}
std::cout<<" sort...\n"<<std::endl;
print_array( A, size, "Before sorting" );
sort(A, size, choice);
print_array( A, size, "After sorting" );
delete [] A;
}
return(0);
}
What is difference between iostream and iostreamh in c plus plus?
<iostream.h> is an old style of programming and does not allow using namespaces. If you use <iostream> you can use namespaces, and limit number of predefined function (not used) included with your program.
What are destructors in c plus plus?
A destructor in C++ is a method of a class that runs when the class is deleted. It performs cleanup of the members of the class that need cleanup, such as deallocation of subobjects referred to by pointers in the class, subobjects which were earlier allocated by a constructor or other method of the class.
What is linkage in c plus plus?
"An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage"
Types:- External, Internal and None linkage
Example:-
External Linkage= extern int a1;
Internal Linkage= static int a2;
None Linkage= int a3;
Assuming the image is an RGB image, sum the red, green and blue components of the pixels separately then divide each by the number of pixels. E.g., given two pixels RGB(a, b, c) and RGB(x, y, z) the mean is RGB ((a+x)/2, (b+y)/2, (c+z)/2).
Write a program in c plus plus to reverse the sentence?
The simplest solution is to use a template function that will reverse an array of any type. This is achieved by iteratively working from both ends of the array, swapping characters while the left index is less than the right. The following example demonstrates the function using both a character array and a std::string, but the function will also work with an array of any type.
#include<iostream>
#include<string>
template<class T>
void rev_array(T A[], size_t size )
{
size_t left=0, right=size-1;
while( left<right )
{
T tmp=A[left];
A[left]=A[right];
A[right]=tmp;
++left; --right;
}
}
int main()
{
char arr[] = "Hello world!";
std::cout<<arr<<std::endl;
rev_array(arr, strlen(arr));
std::cout<<arr<<std::endl;
std::cout<<std::endl;
std::string str = "The cat sat on the mat.";
std::cout<<str.c_str()<<std::endl;
rev_array(&str[0], str.size() );
std::cout<<str.c_str()<<std::endl;
std::cout<<std::endl;
return(0);
}
Example output:
Hello world!
!dlrow olleH
The cat sat on the mat.
.tam eht no tas tac ehT
Need of constructor in c plus plus?
There is no specific keyword for a constructor in C++. Simply define and declare a method of the class with the same name as the class and it will be a constructor.
A constructor with no arguments is the default constructor, a constructor with one argument of class type is the copy constructor, and a constructor with one argument of some other type is the conversion constructor. You can provide other overloaded constructors if you want.
Why there is a need for C plus plus and how does it overcome the drawbacks of the C language?
Absolutely! C++ and Java are by far the two most popular programming languages in use today. Java is the most popular due to its ease of use, particularly with cross-platform development, but it compiles to byte code rather than native machine code, thus it is nowhere near as efficient as C++ and is therefore unsuitable for time-critical applications. Even its predecessor, C, is still in use today due to the fact that procedural C can be mapped 1:1 with the underlying machine code making it easier to develop small-scale, cross-platform applications such as driver software. However, since C++ is backward-compatible with C, the ability to mix low-level machine code with intermediate object-oriented code is advantageous when developing more complex applications, including operating systems. Java is simply too high level for this.