answersLogoWhite

0

📱

C Programming

Questions related to the C Computer Programming Language. This ranges all the way from K&R to the most recent ANSI incarnations. C has become one of the most popular languages today, and has been used to write all sorts of things for nearly all of the modern operating systems and applications. It it a good compromise between speed, power, and complexity.

9,649 Questions

Difference between register variable and automatic variables?

Register variables are stored in register of microprocessor/micro-controller. The read/write access to register variable is the fastest because CPU never need any memory BUS operation to access these variable.

Auto variable are stored in stack thus access are much slower. Auto variable can be converted to register by using register keyword before it. It has platform specific limitation. Register variable will work only if free registers are available to hold the variable for a function scope. In case of Microprocessor or microcontrollers having very less number of general purpose registers will never take register variable even if we declare it as register.

An algorithm to Reversing the order of elements on stack S using 1 additional stacks?

// stack to contain content

Stack sourceStack = new Stack();

// ... fill sourceStack with content

// stack to contain reversed content

Stack targetStack = new Stack();

while (!sourceStack.empty())

{

targetStack.push(sourceStack.pop());

}

// targetStack contains the reversed content of sourceStack

What is An array of wavelengths?

It is a spectrum. I know this because i am currently in physical science class and we just discussed it. Unless my teacher and book are wrong, this is right.

Storage classes available in c language?

There are four types of storage class or variable in c.

1) auto storage class.

2) register storage class.

3) static storage class.

4) external storage class.

Write a java program that finds and displays all the prime numbers less than 1000?

CLS
FOR n = 2 TO 100
FOR k = 2 TO n / 2
flag = 0
r = n MOD k
IF r = 0 THEN
flag = 1
EXIT FOR
END IF
NEXT k
IF flag = 0 THEN PRINT n,
NEXT n
END

How do you Convert binary number 10000001 to decimal?

Every digit in a binary number corresponds to power of two. So 0001 0101 is equal to 0*2^7 + 0*2^6 + 0*2^5 + 1*2^4 + 0*2^3 + 1*2^2 + 0*2^1 + 1*2^0, which equals 0+0+0+16+0+4+0+1, which equals 21.

What type of data deals with descriptions?

Descriptions are best represented using a character array (string) data type.

What is the most appropriate datastructure to implement priority queue?

Arrays are the most efficient data structure. Memory is allocated to the entire array as a single operation and the total memory consumed is equal to the product of the element size and the number of elements (all elements being of equal size, in bytes). This means that any element in the array can be accessed using simple pointer arithmetic from the start of the array, with the first element at offset 0. All high level languages hide the pointer arithmetic behind an array suffix operator, such that element [5] will be found 5 * sizeof (element) bytes from the start address of the array (the address where element [0] resides). Multi-dimensional arrays are implemented as an array of arrays, such that a two-dimensional array is a one-dimensional array where every element is itself a one-dimensional array. These can be thought of as being a table of rows and columns where the first dimension access a one-dimensional row array, and the second dimension accesses the column within that row. A three-dimensional array can then be thought of as being an array of tables or a cuboid (a stack of tables). A four-dimensional array can therefore be thought of as being an array of cuboids, a table of tables, or a cuboid of arrays. By imagining arrays in this manner it becomes much simpler to imagine arrays with more than 3 dimensions.

By contrast, a list or a tree structure is less efficient because every element requires at least one additional field to maintain the link from that element to another element, thus defining the structure. You also need to maintain an additional field to refer to the first element in the structure. If you have a structure that can dramatically vary in size, lists may be more efficient because there is no need to reallocate the entire structure; you simply allocate and deallocate memory for individual elements and update the links between elements to maintain the structure. However, you lose constant-time random access because you have to traverse the links in the structure to locate an individual element and the additional level of indirection means it will be slower than an array. However, reallocating an array often means copying the array to new memory. One way to minimise reallocations is to reserve more memory than you actually need, thus allowing you to add new elements more quickly at the cost of some memory. You only need to reallocate when you run out of reserve. You can also minimise the cost of reallocation by storing pointers rather than objects in your array. This adds an extra level of indirection, but speeds up the reallocation process by only copying pointers rather than objects being pointed.

How do you write a C program to find the GCD and LCM of two numbers using a switch statement?

The following function will return the GCD or LCM of two arguments (x and y) depending on the value of the fct argument (GCD or LCM).

enum FUNC {GCD, LCM};

int gcd_or_lcm(FUNC fct, int x, int y) {

int result = 0;

switch (fct) {

case (GCD): result = gcd (x, y); break;

case (LCM): result = lcm (x, y); break;

}

return result;

}

Multiple indirection in c language?

C uses pointers for indirection. So, using a pointer to a pointer would be multiple indirection. For example, the following code uses multiple indirection:

int i = 42;

int *pi = &i;

int **ppi = π

**ppi++;

printf("i is now %d\n", i);

What is the default return type in C and C plus plus?

No. There is no default return type for functions, it must be explicitly specified in both the function declaration and in the definition. To specify no return value, return void. To return a variant type, return void* (pointer to void). Otherwise return the exact type.

What is the C program to check whether a given character is vowel or not using if else?

#include<stdio.h> main() { char key; clrscr(); printf("Enter the key"); scanf("\n %c",& key); if (key>='A' key<='Z' )&&(key>='a' key<='z') { printf("%c is an character \n",key); } else { printf("%c is not character",key); } getch(); }

Why is c referred to as middle level language?

C is called a middle level language since it is a higher language than something like assembler, which communicates to the computer through operations that directly manipulate data and uses machine code.

High level languages, are very close to human readable/speakable languages, such as English and French ( and many more), and are therefore more human-oriented.

Unfortunately, the C programming language is neither a low-level language, such as assembler, or a high level language such as English, but somewhere in between. Thus a middle-level language
By mistake. It is a high-level language.

Reverse of a number using do while?

int RevNum( int num )

{

const int base = 10;

int result = 0;

int remain = 0;

do

{

remain = num % base;

result *= base;

result += remain;

} while( num /= base);

return( result );

}

What are the advantages of arrays?

Advantages:

1. You can use one name for similar objects and save then with the same name but different indexes.

2. Arrays are very useful when you are working with sequances of the same kind of data (similar to the first point but has a different meaning).

3. Arrays use reference type and so.

Disadvantages:

1. Sometimes it's not easy to operate with many index arrays.

2. C environment doesn't have checking machism for array sizes.

3. An array uses reference mechanism to work with memory which can cause unstable behaviour of operating system (unless special methods were created to prevent it) and often even "blus screen" and so on. store the many characters or vales in a single variable.

What is c plus plus data type?

The C++ string classes are derived from the std::basic_string<T> template class, where T is a character type. The standard provides the two most common string types, std::string (std::basic_string<char>) and std::wstring (std::basic_string<wchar_t>). The former is used for ASCII strings (which includes UTF-8 strings) while the latter is used for wide-character strings, particularly UNICODE strings.

All standard library strings are represented by an array of some character type (such as char or wchar_t) however, unlike an ordinary array, the individual character elements cannot be re-ordered other by overwriting each character. If you simply need an array of characters that can be re-ordered then use a std::vector<char> or std::vector<wchar_t> rather than a string.

The standard library strings include a rich set of methods, operations and algorithms that are commonly used with strings, such as std::string::find() to locate a character within a string, std::string::substr() to extract a substring from a string, and operator+= to concatenate one string onto another. Most implementations include the short string optimisation so that short strings (up to around 14 characters or so) may be stored in local memory rather than on the heap. Many strings tend to be short so this can provide enormous performance benefits with little cost in terms of memory.

What is the use of recursion function?

Read the part in your programming manual/text book about recursion.

The short answer while easy does not tell you anything about the power or dangers of recursion. It is the power and dangers of recursion that is important because once understood you can use recursion to good effect without running out of stack space.

What is the need of object oriented programming?

Structured programming is task-centric, object oriented programming is data-centric.Task-centric vs. Data-centricStructured programming is based around data structures and subroutines. The subroutines are where stuff actually "happens", and the data structures are simply containers for the information needed by those subroutines.

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 Algorithm
void linedda(int xa,int ya,int xb,int yb) {

int dx=xb-xa,dy=yb-ya,steps,k;
float xincrement,yincrement,x=xa,y=ya;

if(abs(dx)>abs(dy)) steps=abs(dx);
else steps=abs(dy);

xincrement=dx/(float)steps;
yincrement=dy/(float)steps;

putpixel(round(x),round(y),2)

for(k=0;kx+=xincrement;
y+=yincrement;
putpixel(round(x),round(y),2);
}
}
More Informationhttp://knol.google.com/k/thiyagaraaj-m/dda-line-algorithm/1lfp8o9xxpx13/78#
http://i.thiyagaraaj.com/articles/articles/dda-line-algorithm

What is a statement?

I 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.

What Does an array represent?

it is a random splitting of atoms made of protons and neutrons and electrons if they split the universe willexplode.