What is the need of object oriented programming?
Object oriented programming, on the other hand, shifts your primary focus to the data itself. Instead of asking "what do I want to do and what will I need to know to do it", you ask "what kind of things do I want to have and what can those things do for me". Instead of designing your functions first and then coming up with data structures to support them, you design types first and then come up with the operations needed to work with them.
Three OOP PrinciplesPerhaps the most important feature of OOP is polymorphism, the ability to identify certain aspects that several data types have in common, and write code that works equally well with all of them by ignoring the differences in situations where they don't matter.For example, consider a simple drawing program where you have a set of shapes (circles, rectangles, etc.) that share certain things in common (they all have a location, size, and color) but are different in other ways (how they look or whether they can be rotated). In a structured program, you'd write a function to draw a shape, containing logic like "if the shape is a circle, do ABC; if it's a rectangle, do XYZ" and so on.
But in an OO program, you'd simply tell the shape to draw itself, and the shape would know, based on its own type, what to do: you write a specialized drawing function when you define each shape, and when you send a "draw" message to any shape, it automatically calls the one for the correct shape type. Polymorphism eliminates the need for you to check what kind of shape it is: you just have to know that shapes can draw themselves, and let the shape worry about how it actually happens.
Another important OO principle is encapsulation, the ability to bundle code and data together in one place and hide that data from the outside world, forcing anyone who wants to access it to go through the associated code. For example, all shapes have a location and a size, but the best representation might be different. A circle only needs three numbers (center X, center Y, and radius) but a rectangle needs four (top, bottom, left, right). Structured programming encourages code everywhere to deal directly with the innards of data structures, so most likely you'd need to use the same representation for all shapes in order to avoid checking the type every time you wanted to measure a shape, even though that representation is wasteful for circles.
Object oriented programming addresses that problem two ways: first, encapsulation says that the internal representation of a shape is off-limits to anyone else, so if you want to know how big a shape is, you have to call its getSize() method instead of reading its size directly out of memory. Second, polymorphism allows different shapes to implement their getSize() methods differently, allowing circles to use a more efficient version while presenting the same interface to the outside world.
Finally, there's inheritance, which makes it easy to extend existing structures to produce new structures with slightly different behavior. For example, a filled circle is mostly the same as a regular circle, but it draws itself differently and also has a fill color. In a structured program, you'd probably handle filled circles by adding a fill color to all shapes and a flag that indicates whether the shape is filled or not, and the fill color would simply go unused (wasting memory) in unfilled shapes. In an object-oriented program, you can make FilledCircle a subclass of Circle, inheriting all the existing circle behavior, and then replace the draw() method and add a place to store the fill color. Then if you changed something about Circle later, the change would automatically propagate to FilledCircle, while changes you made to FilledCircle would not affect any other shapes.
Design vs. LanguageWhether your code is object oriented or merely structured depends partly on your choice of language, but also on your design. For example, the C language doesn't offer any features for object oriented programming, but with enough discipline you can still write object-oriented code in C, such as the GTK windowing library. On the other hand, you can write a Java program that completely fails to take advantage of Java's OOP features, by putting all your code in a single class and using classes with public members just as you'd use structs in C. One organizes code by comprehensiveness while the other organizes code by the data affected.Structured programming consists of breaking big problems into smaller problems, then further breaking those into still smaller problems, and so on, until a level of such simplicity is reached that the implementation is obvious to the programmer expected to do the coding. Object-oriented programming consists of grouping code with the data on which it operates so that this "object" can function independently of the rest of the software system. Structured programming and object-oriented programming are not mutually exclusive. You can structure the code in an object, and you can use objects to implement the modules of code in a structured program. Procedural (Structure) vs. OO programming require different approachesSimilarities: Both require a rudimentary understanding of programming concepts and basic control flow. Loops, conditional statements, and variables are concepts that are important whether you are using a procedural language or an object oriented language.Differences: Typically object oriented is viewed as more difficult. This is because an entirely different problem solving approach must be taking. In addition, there are a variety of object-oriented-only concepts such as classes and inheritance. For simple programs, procedural is often preferred. The more complicated the project, the easier it is to leverage the strengths of object oriented design.
Other notes: Not all languages fall strictly into procedural or object oriented baskets. In actuality, it is more of a spectrum. Languages like Basic and C are pretty much entirely procedural. Languages like C++ and Pascal can be written in either procedural or object oriented styles. Languages like Java and Python adhere much more strictly to object oriented design (although some programmers argue these aren't TRUE object oriented languages).
Advantages of DDA line drawing algorithm?
DDA Line Drawing Algorithm
Step 1:[Determine The Dx & Dy]
Dx=Xb-Xa
Dy=Yb-Ya
Step 2:[Determine Slope is Gentle or Sharp]
If |Dx|>|Dy| then
Gentle Slope
M=Dy/Dx
Set The Starting Point
If Dx>0 Then
C=CELING(Xb)
D=Yb+M*(C-Xb)
F=FLOOR(Xa)
R=FLOOR(D+0.5)
H=R-D+M
IF M>0 Then
Positive Gentle Slope
M1=M-1
Now Step Through The Columns
WHILE C<=F
C Programming Coding For DDA AlgorithmI don't really know that is a good question to ask a teacher or someone.
Explain with an example Insertion Sort?
A sorting technique that sequences a list by continuously dividing the list into two parts and moving the lower items to one side and the higher items to the other. It starts by picking one item in the entire list to serve as a pivot point. The pivot could be the first item or a randomly chosen one. All items that compare lower than the pivot are moved to the left of the pivot; all equal or higher items are moved to the right. It then picks a pivot for the left side and moves those items to left and right of the pivot and continues the pivot picking and dividing until there is only one item left in the group. It then proceeds to the right side and performs the same operation again
Write a program to genarate Fibonacci series upto sum numbers?
void main()
{
int n,old=0,curr=1,new=0;
clrscr();
printf("enter the total number of terms up to which you want to print the Fibonacci series");
scanf("%d",&n);
printf("%d",old);
printf("\n%d",curr);
for(i=1;i<=n;i++)
{
new=old+curr;
old=curr;
curr=new;
printf("\n%d",new);
}
getch();
}
Why and when do you use the define directive?
The #define preprocessor directive is severely overused in my opinion.
Often, you will see programmers write something like this:
# define MAX(a, b) (((a) > (b))? (a) : (b))
However doing so is rather dangerous, because the preprocessor replaces things textually.
This means that if you pass in a call to a function, it may happen twice, for example:
MAX(++i, j) will be expanded to
(((++i) > (j))? (++i) : (j))
which is bad.
A much safer (and more common) example is that people will use #define to create a constant variable:
#define MYCONST 10
This too can cause problems if another file depends on the constant and certain other conditions are met.
A safer alternative is to declare a const variable.
The one advantage of using #define for literal constants is that the number will not be stored in memory attached to an object like a const variable will.
Is C programming procedural or object oriented?
C is a weakly typed procedural programming language. For object oriented programming languages near C, you can look at ooc ( http://ooc-lang.org/ ), C++, D, and Java.
it is a random splitting of atoms made of protons and neutrons and electrons if they split the universe willexplode.
There can be no person who is singlehandedly responsible for the founding of alerbra. This is because algebra is a classification of a certain type of math. Therefor there is a vast amount of people who contributed to the upbringing of algebra.
Which data type can store any data?
In C macros are a piece of code that is replaced by its value whenever it called from.
Syntax for defining a macro is :
# define Macro_Name Value
As:
# include<stdio.h>
# define three 3
int main(){
printf("%d", three);
return 0;
}
output: 3.
In above example three is a macro and its value is 3.
The place for defining macros are same as including a header file in a program.
What is Size of int variable in c?
The size of an int variable in c is a function of the compiler implementation. It is usually a word in the underlying computer architecture. Original Microsoft C/C++ compilers for the 16 bit platform defined an int as 2 bytes. Current compilers for the 32 bit platform define an int as 4 bytes. The current ANSI C standard provides that an int is at least 4 bytes, but it could be higher, say 8 bytes on a 64 bit platform.
A preprocessor is a program that proccesses a file before it's passed down to the compiler and the linker. It permits to define some variables so that a programmer can change the program just by changing one line of code. It permits to include header files to.
How you create a table in C programming language?
Well, I don't know what do you mean by table, but here you are:
int main (void)
{
puts ("A3 B3 C3");
puts ("A2 B2 C2");
puts ("A1 B1 C1");
return 0;
}
What is an uninitialized pointer?
It means "nothing", there is no data provided at all; just an empty value.
Contrary to the previous edit it does not mean "zero", "none" or "blank"; as zero is a number and none and blank can be regarded as data.
The simple answer is that the program has undefined behaviour and is therefore an invalid program. There's no easy way to know what will happen because you have (knowingly or otherwise) violated a fundamental language rule; the unconditional access of memory outwith the range of the array. That memory may or may not belong to your program, but there is no way to tell for sure, thus the behaviour is undefined. Perhaps nothing bad will happen at all, or the program will simply crash. But with undefined behaviour, absolutely anything can happen and there's simply no way of knowing in advance. When a user's hard-disk files are deleted by your program, you will quickly learn the peril of allowing undefined behaviour!
Example:
int x[10] = {0, 1, 2, 4, 5, 6, 7, 8, 9];
int* p = x;
p += 10; // one-past-the-end of the array
*p = 42; // undefined behaviour!
Referring to the one-past-the-end of an array is perfectly valid. Indeed, many algorithms that operate upon arrays using a half-closed range of iterators specifically rely upon this validity to determine when the algorithm has reached the end of the sequence and should stop processing. However, we must never dereference this address even if the address is actually part of the array. Consider the following algorithm:
void scale (int* b, int* e, int scalar) {
while (b != e) {(*b) *= scalar; ++b; }
}
This algorithm operates upon any sequence of elements denoted by the half-closed range [b:e), where e refers to the element one-past-the-end of the sequence we wish to scale.
Given our earlier definition of array x, we can scale any sequential portion of the array:
scale (x, x+5, 2); // Scale the first 5 elements (x[0] through x[4]), doubling the values. scale (x+5, x+10, 3); // Scale the last 5 elements (x[5] through x[9]), tripling the values.
scale (x, x+10, 4); // Scale the entire array (x[0] through x[9]), quadrupling the values.
Note that the begin iterator, b, must initially refer to an element within the bounds of x (that is, x[0] through x[9]), but e may refer to any element in the range x[0] through x[10]. Although x[10] is outwith the bounds of x, we never actually access this element, we simply refer to it to check that b is still in range before dereferencing the element and scaling its value.
Undefined behaviour is created when we invoke this algorithm with invalid iterators:
scale (x, x+11); // Undefined behaviour! Range includes x[10] which is outwith the bounds of x. scale (x-1, x+10); // Undefined behaviour! Range includes x[-1] which is outwith the bounds of x. scale (x+9, x-1); // Undefined behaviour! Algorithm does expect reversed sequences.
Note that the algorithm is designed for efficiency and therefore does not check the given range for validity. Although inherently unsafe, efficiency often places the onus of responsibility upon the caller, never the algorithm.
Next Answer
Exceeding the range of elements in an array (or a string) is a common newbie programming error, and is considered improper or "illegal" programming practice in C or any other programming languages and the outcome of doing so is considered "undefined". That means the results cannot be predicted. Compilers attempt to catch such errors and often have options to enable/disable checking for invalid array references during program execution.
So what happens when a range is exceeded? What does undefined get you? Their are several possibilities.
The following code demonstrates function overloading to calculate volumes of cubes, cylinders and rectangular boxes (cuboids).
#include
#include
using namespace std; // required for console input/output.
// User-input control function (avoids garbage input).
unsigned int GetNum( char * prompt )
{
int iResult = 0;
cout << prompt << ": ";
while( !( cin >> iResult ) iResult < 0 )
{
cin.clear();
cin.ignore( BUFSIZ, '\n' ); // If BUFSIZ not defined, use literal constant 512 instead.
cout << "Please enter numeric characters only." << endl << endl;
cout << prompt;
}
return( iResult );
}
// Forward declarations of overloaded functions.
void volume(unsigned int);
void volume(unsigned int,unsigned int);
void volume(unsigned int,unsigned int,unsigned int);
void volume(unsigned int s)
{
unsigned int cube = s*s*s;
cout << "Volume of cube is " << cube << endl << endl;
}
void volume( unsigned int r, unsigned int h)
{
// For the greatest accuracy across all platforms,
// PI is defined as 4 * arctan(1).
float cylinder = (4*atan((float)1)) * r*r*h;
cout<<"Volume of cylinder is " << cylinder << endl << endl;
}
void volume(unsigned int l, unsigned int b, unsigned int h)
{
unsigned int cuboid= l*b*h;
cout << "Volume of cuboid is " << cuboid << endl << endl;
}
int main()
{
unsigned int s;
s = GetNum( "Enter side of cube" );
volume( s );
unsigned int r, h;
r = GetNum( "Enter radius of cylinder" );
h = GetNum( "Enter height of cylinder" );
volume( r, h );
unsigned int l, b;
l = GetNum( "Enter length of cuboid" );
b = GetNum( "Enter breadth of cuboid" );
h = GetNum( "Enter height of cuboid" );
volume( l, b, h );
return 0;
}
OUTPUT:
Enter side of cube: 4
Volume of cube is 64
Enter radius of cylinder: 2
Enter height of cylinder: 3
Volume of cylinder is 37.6991
Enter length of cuboid: 9
Enter breadth of cuboid: 8
Enter height of cuboid: 6
Volume of cuboid is 432
Press any key to continue . . .
[EDIT] Reasons for changes to original answer:
The actual arguments (we call them parameters) to a function are the original copies in the caller's address space. The function prolog code provided by the compiler provides for making copies of all of the parameters. These copies are called the formal parameters. In C and C++, the default calling convention is call by value, which means that the called function only has access to the formal copy. Optionally, you can call by reference, passing instead the address of the actual parameter. Using dereference notation, the called function then has access to the actual parameter, and the formal parameter is simply its address.
One of the things that sometimes confuses people is the name of the parameter. You might, for instance, call something alpha in you main function. It is called alpha, and alpha means the memory location of alpha. In the function, however, you can call the parameter something else, perhaps beta. Within the context of the called function, beta contains the value of or the address of alpha, but it is not alpha, it is beta. To make matters worse, you can have another alpha within a block, or within the function, and that is certainly not related at all to the original alpha.
Recommendation: Always call an object by consistent names. This way, you won't get into scoping rules trouble.
How you pass array elements to a function?
Passing array elements to a function is achieved by passing the individual elements by reference or by value, just as you would any other variable. However, passing the entire array requires that you pass a pointer-to-pointer to the array along with the dimension(s) of the array.
Importance of virtual functions?
Private virtual functions are useful when you expect a particular method to be overridden, but do not wish the override to be called from outside of the base class. That is, the base class implementation and its overrides remain private to the base class.
Private virtual methods are particularly useful in implementing template method patterns, where certain algorithmic steps need to be deferred to subclasses, but where those steps need not be exposed to those subclasses. In many cases the private virtual methods will be declared pure-virtual, thus rendering the base class an abstract base class.
Write a program to exchange the value of two variables?
#include<stdio.h>
void main()
{
int a,b,t;
printf("enter the values of two varaible");
scanf("%d%d",&a,&b);
t=a;
a=b;
b=t;
printf("the exchanged values are",b,a);
}
What are the applications for circular linked lists?
A singly-linked circular list is useful for implementing queue data structures with minimum overhead. Normally we implement a queue with two pointers: one to the tail for insertions and one to the head for extractions. With a circular list we only need to maintain a single pointer to the tail because the tail always points "forwards" to the head (instead of null as it normally would), thus achieving constant-time access to both the head and tail via a single pointer.
Circular linked lists are generally useful wherever "wraparound" is necessary. That is, from any given node in the list, we can traverse forwards with the guarantee that we will eventually arrive back at that same node. With doubly-linked circular lists we have the advantage of traversing in either direction (bi-directional traversal).
What is a traversing process in data structure?
like searching in data structure, move on nodes and check them
What is the difference between enumeration and set of preprocessor define in c?
An enumeration is a group of named integral constants. An enumeration is also a type thus it provides type safety. When passing a constant to a function, an enumeration eliminate values that are not part of the group, thus allowing the compiler to catch errors that would otherwise slip through.
A set or pre-processor definitions (or macro definitions) do not provide any type safety and are never actually seen by compiler (they are processed before the compiler sees the resultant code). Macros are nothing more than a text-replacement system that effectively allow programmers to create a language within the programming language and thus create code that would be difficult if not impossible to produce using the language alone. However, when the language provides a simpler, type-safe mechanism, it is always better to utilise it and thus enlist the help of the compiler to eliminate errors. Macros do have their uses, particularly when debugging, but they must be used only when it is appropriate to do so. Enumerations are preferred over a set of macro definitions every time.
Some languages also permit enumeration classes, which gives stronger guarantees than a "plain" enumeration, not least eliminating the implicit promotion between enumerated types and integral types.