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

What is operator precedence in c programming?

Operator precedence is often associated with order of evaluation, however order of evaluation and operator precedence are actually undefined in C. Expressions may be evaluated in any order while operator precedence is derived from the language grammar. The concept of operator precedence merely simplifies our understanding.

When we think of operator precedence we can imagine a table with 15 rows. When parsing an expression, any operator on a given row takes precedence over those on lower rows. If we also number the rows in ascending order then we can associate each row with a precedence level, such that level 1 has the highest precedence and lower rows have lower precedence.

In addition to precedence, each row also has an associativity. Rows 2, 13 and 14 have right-to-left associativity while all others have left-to-right. For instance, the assignment operator appears on row 14 thus the expression a=b=c is evaluated as if it were actually written a=(b=c) rather than (a=b)=c.

What is the use of header file in c?

A header file is used to define constants, variables, macro's and functions that may be common to several applications. When a system consists of multiple applications that all access the same data it becomes essential that each application uses identical definitions and it is safer for all of those applications to use the same methods to read that data. updating data should only be performed by a single function, from a single application, but reading data can be safely performed by using the common defintions found in header files. you use header files in the programming language C to declare struct's functions and other things that could be usefull for your program.. it makes thing's simpler and easy to use...

What is the importance of recursion in computer programming?

Recursion is important because many algorithms are naturally recursive, particularly those that involve a divide-and-conquer technique. That is, we divide a complex problem into smaller instances of the same problem. Each division divides and reduces the problem further until the divisions are small enough to be resolved. We then aggregate those individual solutions to solve the original problem.

As a simple example, factorials can be calculated such that f(n) = n * f(n-1) for all n>1 where f(1) and f(0) are both 1. We can implement this function recursively as follows:

unsigned f(unsigned n) {

return n<2 ? 1 : n * f(n-1);

}

While the function itself is naturally recursive, that doesn't mean we must use a recursive solution. In this case, an iterative solution would actually be more efficient:

unsigned f(unsigned n) {

unsigned a = 1;

while (1<n) a *= n--;

return a;

}

However, in languages that allow compile-time computation (such as C++), recursive functions can be advantageous:

constexpr unsigned f(unsigned n) {

return n<2 ? 1 : n * f(n-1);

}

With this function, a good compiler will convert f(6) to the literal constant 720, completely eliminating the runtime overhead of invoking the function recursively. However, for values that cannot be computed at compile time due to excessive recursions, the runtime function will still be invoked, such that f(10) might be replaced with the constant expression 10 * f(9).

Languages that support template metaprogramming can provide the means to completely eliminate the runtime overhead associated with recursion:

template <unsigned N>

constexpr unsigned f () {

return N*f<N-1>();

}

template<>

constexpr unsigned f<1>() {

return 1;

}

template<>

constexpr unsigned f<0>() {

return 1;

}

Note that the terminating conditions are handled through specialisation rather than through recursion. At compile time, f<1>() invokes the first specialisation while f<0>() invokes the second. For all values N>1, the general function is invoked recursively at compile time.

constexpr unsigned x = f<10>();

Compile-time computation will effectively replace the above expression with:

constexpr unsigned x = 3628800;

Note that no code is generated for these template functions so we cannot invoke them at runtime, they are used purely for compile-time computation.

In languages that do not support template metaprogramming or constexpr, we can still make use of recursion, particularly where an iterative approach is too complex to implement efficiently. Divide-and-conquer algorithms are a typical example.

The Quicksort algorithm is a relatively simple recursive algorithm that can be implemented as follows:

void qsort (int a[], int lo, int hi) {

if (hi<=lo) return;

unsigned pivot = partition (a, lo, hi);

qsort (a, lo, pivot-1);

qsort (a, pivot+1, hi);

}

The partition() function does most of the actual work. Given the lower and upper bounds of the array it will select a pivot value and position this value such that all values to the left of it are less than it and all those to the right are not less than it. Once the array is partitioned, the index of the pivot value is returned. This value is used to determine the upper bound of the left sub-array (pivot-1) and the lower bound of the right sub-array (pivot+1).

What are the 3 turbo c language components?

Borland Turbo C came with an editor, compiler, linker and debugger, all of which were tightly integrated into the Turbo C IDE (integrated development environment). The professional version also came with standalone versions of the Turbo Assembler and Turbo Debugger.

Note that Turbo C is 27 years old. As such it is redundant. All Borland development tools are now owned by Embarcadero. Turbo C is now classed as "antique".

What are the difference between array declaration in java and c plus plus?

There is no difference, other than that declarations in C++ can also initialise the variable in a single instruction.

C example:

int x; // declaration

x=5; // initialisation

C++ example:

int y=5; // declaration and initialisation combined.

Structure of If-Then statement?

if (condition) statement1

[else statement2]

example:

if (i==j);

else if (j==k) printf ("i!=j, j==k\n);

else printf ("i!=j, j!=k\n);

here statement1 is an empty-statement, statement2 is another if-statement

There are three forms of statements

IF-THEN

IF-THEN-ELSE

IF-THEN-ELSIF

Sequence of statements is executed only if the condition evaluates to TRUE

If condition evaluates to FALSE or NULL, it does nothing

In either case control passes to next statement after the IF-THEN structure

IF THEN

statements;

END IF;

Sequence of statements in the ELSE clause is executed only if the condition evaluates to FALSE or NULL

IF THEN

statements;

ELSE

statements;

END IF;

What is pointer to function in c?

Accessing data by their address. A good example is parameter argv of function main.

1. Easy access

2.To return more than one value from a function.

3. To pass as arguments to functions. For eg. consider the following structure

struct student

{

char name[10];

int rollno;

};

If you pass this structure object as argument to function then, 14 bytes(10+4) of memory will be passed to the function. Instead, if you pass the pointer to the structure as argument then only 4 bytes (or 8 bytes)of memory will be passed to the function.

Individual digits sum with flowchart and algorithm?

Well, it's very hard to write a flowchart in text, so I'll give you some pseudo code instead.

int number = the given number

int sum = 0

loop while number is not 0

sum = sum + (number mod 10)

number = number / 10

What translates a program written in Assembly language into machine code?

Well, let's say you have the following Assembler statement:

MOV AX, 0005

Each processor (depending on the processor architecture, being some of them: SPARC, Intel 80x86, Motorola...) translates each Assembler mnemonic and register into Machine Code according to an Opcode Table.

Think of an Opcode Table this way:

Instruction OpCode

-----------------------------------

MOV A1

ADD A2

SUB A3

MUL A4

DIV A5

...

AX B0

BX B1

CX B2

...

Each mnemonic/register has its corresponding hex code for the processor to understand the operation, so:

MOV AX, 0005

Could be translated as:

A1 B0 0005

Hopefully this gives you an idea of how a processor assembles code and generates machine code.

How can structures be declared and used in c program?

You declare a structure as follows:

struct name {

typename_1 member_name_1; typename_2 member_name_2;

// additional members...

};

C program for upper triangular matrix for a given matrix?

This sounds very much like a homework problem. If you work on it and get started, you found a great place to ask a specific question. However, this is not a place to have your homework done for you.

What is a loop type?

A Loop is a programming language construct that instructs the processor to repeat a sequence of operations a number of times until a specific condition is reached. There are different types of loops. They are: * for loop * while loop * do while loop

Which header file is used to develop a function that can accept variable number of arguments?

.If you want to accept variable no of arguments then you have to include which of the following header files

a) Vararg.h b) stdarg.h c) stdlib.h d) stdioh

What is perfect number in C language?

Perfect numbers have nothing to do with programming languages. Some of them are: 6, 28, 496, 8128, 33550336.

What is the worst case and average case complexity of bubblesort?

Best case: O(n)

Worst case: O(n2)

Let's assume we're sorting data in an array of length n. Let's also assume that we're sorting in ascending order (low-high).

The worst case is that you will have the smallest value in the last space in the array. This means that it will move exactly once each pass towards the first space in the array. It will take n-1 passes to do this, doing n comparisons on each pass: O(n2)

The best case is that the data comes to us already sorted. Assuming that you have a smart implementation (which you should, because it's easy) which stops itself once a pass makes no changes, then we only need to do n comparisons over a single pass: O(n)

What is an array to show 4X4?

An array of 4 times 8 is a 2D array with 4 Rows and 8 Columns.

// Declaration of a 2D array [ROWS] [COLUMNS]

int [][] arr = new int[4][8];

// What a 2D Array looks like populated with numbers

//

// _____________________

// Row 0 | 1 0 0 0 0 0 0 7

// Row 1 | 0 0 0 0 0 0 0 0

// Row 2 | 0 0 0 0 0 0 4 0

// Row 3 | 0 0 0 0 0 0 0 0

The example array above has the number 1 place in the first row of the first column.

In the first row of the eight column the number 7 is placed.

In the third row of the seventh column the number 4 is placed.

// Accessing these values

int one = arr[0][0];

int seven = arr[0][7];

int four = arr[2][6];

Types of header file?

stdio.h math.h conio.h cstring.h OR string.h - i can't remember ... ctype.h some more i can't remember answer by riya: ALLOC.H ASSERT.H BCD.H BIOS.H COMPLEX.H CONIO.H CTYPE.H DIR.H DIRENT.H DOS.H ERRNO.H FCNTL.H FLOAT.H FSTREAM.H GENERIC.H GRAPHICS.H IO.H IOMANIP.H IOSTREAM.H LIMITS.H LOCALE.H MALLOC.H MATH.H MEM.H PROCESS.H SETJMP.H SHARE.H SIGNAL.H STDARG.H STDDEF.H STDIO.H STDIOSTR.H STDLIB.H STREAM.H STRING.H STRSTREA.H SYS\STAT.H SYS\TIMEB.H SYS\TYPES.H TIME.H VALUES.H

How t print a table in tabular form in two dimensional array in c plus plus?

#include<iostream>

#include<iomanip>

#include<vector>

#include<random>

#include<ctime>

using data_t = std::vector<std::vector<int>>;

size_t get_width (int num)

{

size_t width=1;

while (num/=10)

++width;

return width;

}

std::vector<size_t> get_column_widths (const data_t& data)

{

std::vector<size_t> width;

for (auto row : data)

{

if (width.size() < row.size())

width.resize (row.size());

for (size_t i=0; i<row.size(); ++i)

{

size_t w = get_width (row[i]);

if (width[i]<w)

width[i]=w;

}

}

return width;

}

void print_table (const data_t& data)

{

using std::cout;

using std::endl;

using std::right;

using std::setw;

std::vector<size_t> width = get_column_widths (data);

cout << right;

for (auto row : data)

{

for (size_t i=0; i<row.size(); ++i)

{

cout << setw(width[i]) << row[i] << ' ';

}

cout << endl;

}

}

int main()

{

// Random number generator (range: [1:1000])

std::default_random_engine generator ((unsigned) time (0));

std::uniform_int_distribution<unsigned> distribution (1, 10000);

// Create a 10x5 matrix:

data_t data;

for (size_t row=0; row<10; ++row)

{

data.push_back (std::vector<int>{});

for (size_t col=0; col<5; ++col)

data[row].push_back (distribution (generator));

}

print_table (data);

}

How carefully does the compiler pay attention to indentation?

The compiler does not pay any attention whatsoever to indentation in C and C++.

Calculate no of palindromes in given string palindrome?

A string of length n always has at least n palindromes given that any string of length 1 is a palindrome. Thus we initialise the count to n and test all substrings of length 2 or more:

int count_palindromes (char* str) {

if (!str) return 0;

int n = strlen (str);

char* sub = malloc (n+1); // allocate memory for substring (+1 to include null-terminator)

memset (sub, 0, n+1); // zero the memory int count = n;

for (int len=2; len<=n; ++len) { // length of string (2 to n)

for (int i=0; i<=n-len; ++i) { // index of start character

memcpy (sub, str+i, len); // copy len characters from str+i

if (is_palindrome (sub)) ++count; // test the substring

}

free (sub);

sub = NULL;

return count;

}

Usage:

assert (count_palindromes ("racecar") == 10);

assert (count_palindromes ("abcde") == 5);

Note that counting palindromes in this manner is not generally useful. For every palindrome of length n>2 there has to be at least n+n/2 palindromes within it, and we can easily compute this figure without testing every substring. E.g., the palindrome "racecar" includes the palindromes "racecar", "aceca", "cec", "r", "a", "c", "e", "c", "a" and "r", but the only one we're actually interested in is "racecar" itself.

To achieve this we simply examine those substrings with either 2 or 3 characters. That is, when we find "cec" in the middle of "racecar", there's no need to test for "aceca" or "racecar" because "cec" is common to all three.

int count_palindromes (char* str) {

if (!str) return 0;

int n = strlen (str);

if (n<2) return 0;

char sub[4];

memset (&sub, 0, 4);

int count = n;

for (int len=2; len<=3; ++len) {

for (int i=0; i<n-len; ++i) {

memcpy (sub, str+i, len);

if (is_palindrome (sub)) ++count;

} return count;

}

Usage:

assert (count_palindromes ("racecar") == 1); // "cec"

assert (count_palindromes ("abbabcded") == 3); // "bb", "bab" and "ded"

The is_palindrome() function has the following implementation:

bool is_palindrome (char* str) { int x, y;

if (!str) return false;

int n = strlen (str);

if (n<2) return true; // empty strings and single character strings are always palindromes

x = 0; // point to first character

y = n-1; // point to last character

// work towards middle of string while characters are equal

while (x<y && str[x]==str[y]) ++x, --y;

return x>=y; // if the pointers met or passed one another, the string is a palindrome

}

What is the difference between gets and puts?

Direction:

gets: from standard input to memory

puts: from memory to standard input

note: 'gets' is unsafe, use 'fgets' instead

What does a count-controlled loop mean in programming?

A condition-controlled loop is one that has an indefinite number of iterations; its opposite is the count-controlled loop. Condition-controlled loops execute until some event occurs, which is usually user-initiated. For example, modern programs run an condition-controlled loop similar to the following:

while(GetMessage(message,hwnd,0,0)) { ... }

This loop continues to execute until there are no messages left (the WM_QUIT message is returned, which has a value of zero).

It is impossible to identify before execution the number of times such a loop will run, except during controlled tests, although you can easily identify what conditions will cause it to terminate.

What happens when a program is compiled?

when you compile your program , it is sequentially checking your coding and check whether there is an error. thats the simple thing happening. if there is no error, then it will create an executable file for your coding which is run when you ask to run the program after compiling. if your coding have an error, then you have to correct those errors. REMEMBER that it is compulsory to compile the program after you correct the errors. otherwise, it will not make an executable file with your corrections.