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

Two stacks in one array?

/*implementing two stacks in 1 array*/ #include #include #include int size,top1=-1,top2,a[100]; void push(); void pop(); void peep(); void main() { int i,ch; char c='y'; clrscr(); printf("\Enter size:"); scanf("%d",&size); top2=size; while(c=='y') { clrscr(); printf("\n ###### MENU #####\n"); printf("\n1: push"); printf("\n2: pop"); printf("\n3: peep"); printf("\n4: exit") ; printf("\n Enter choice:"); fflush(stdin); scanf("%d",&ch); switch(ch) { case 1:push(); break; case 2:pop(); break; case 3:peep(); break; case 4:exit(0); default:printf("\n wrong choice"); } printf("\n Another operation(y/n):"); fflush(stdin); scanf("%c",&c); } exit(0); getch(); } void push() { int item,ch; if(top1+1==top2) { printf("stack is full "); printf("\n cant push "); } else { printf("\nEnter item to be inserted:"); scanf("%d",&item); printf("\n enter choice(1 for stack1 else stack2):"); scanf("%d",&ch); if(ch==1) { top1++; a[top1]=item; } else { top2--; a[top2]=item; } } } void pop() { int ch; printf("\n Enter from which stack u want to pop(1 for stack1/else stack2):"); scanf("%d",&ch); if(ch==1) { if(top1==-1) printf("\n cant delete from stack 1 its empty"); else printf("\n item deleted is:%d" ,a[top1--]); } else { if(top2==size) printf("\n cant delete from s2its empty"); else printf("\n item deleted is: %d" ,a[top2++]); } } void peep() { int i; printf("\n stck 1:" ); for(i=0;i=top2;i--) printf(" %d",a[i]); }

Program to find the second largest number in a given set of numbers using arrays without sorting?

Improved Solution to this problem would be able to find any first, second, third.. largest number...

here it is, in Java:

class Sam {

public static void main(String args[]) {

int[] nums = new int[] { 445, 43, 1045, 110, 209, 109, 33, 24, 1566 };

int cnt = 0;

int size = nums.length;

int temp;

int largest = 0;

int secondLargest = 0;

int thirdLargest = 0;

int fourthLargest = 0;

int fifthLargest = 0;

//the logic rests here

while (cnt < size) {

temp = nums[cnt];

if (temp > largest) {

secondLargest = largest;

largest = temp;

} else if (temp > secondLargest) {

thirdLargest = secondLargest;

secondLargest = temp;

} else if (temp > thirdLargest) {

fourthLargest = thirdLargest;

thirdLargest = temp;

} else if (temp > fourthLargest) {

fifthLargest = fourthLargest;

fourthLargest = temp;

} else if (temp > fifthLargest) {

fifthLargest = temp;

}

cnt++;

}

System.out.println("largest:" + largest);

System.out.println("secondLargest:" + secondLargest);

System.out.println("thirdLargest:" + thirdLargest);

System.out.println("fourthLargest:" + fourthLargest);

System.out.println("fifthLargest:" + fifthLargest);

}

}

// Regards,

// SwapniM

// mail me at: swap.masane@gmail.com

#include

using std::cin;

using std::cout;

using std::endl;

double maxFirst(const double data[], intindex);

double maxSecond(const double data[], intindex, double maxNumber1);

double sum(double max1, double max2);

int main()

{

double myArray[] = {

1.0,

4.6,

32.1,

9.7,

41.2,

41.3,

343,

23,

566.02,

345.8,

675.5,

654.4

};

int arraySize = (sizeof myArray)/(sizeof myArray[0]);

cout << "Your array is: ";

for (int k = 0; k < arraySize; k++)

{

cout << endl << myArray[k];

}

double max1 = maxFirst(myArray, arraySize);

double max2 = maxSecond(myArray, arraySize, max1);

cout << endl << "First biggest number is: " << max1;

cout << endl << "Second biggest number is: " << max2;

system("PAUSE");

return 0;

}

double maxFirst(const double data[], intindex)

{

double maxNumber1 = data[0];

for (int i = 0; i < index; i++)

{

if (maxNumber1 < data[i])

{

maxNumber1 = data[i];

}

}

return maxNumber1;

}

double maxSecond(const double data[], intindex, double maxNumber1)

{

double maxNumber2 = data[1];

for (int j = 0; j < index; j++)

{

if (data[j] == maxNumber1)

{

continue;

}

else if (maxNumber2 < data[j])

{

maxNumber2 = data[j];

}

}

return maxNumber2;

}

What are object files in c?

Object files are intermediate files generated when an application is constructed from source code. In a classic compile-assemble-link toolchain, the compiler translates (C language) source code into assembly language output. The assembler translates this intermediate assembly source into a binary form known as object code. Files containing object code often have a .o or .obj file name extension and are generally called object files. The linker takes the object files and combines them into the complete executable.

While many modern tools hide the individual steps, or even integrate compilation and assembly into one, most (all?) compilers generate object files.

Why are Cobol and Fortran are case sensitive?

The languages are not case sensitive in most implementations. However, Fortran versions from F77 forward allow the use of lower-case letters in statements; the compiler simply translates them all to upper-case before processing.

Case sensitivity is a contentious item among programmers. Typing in mixed, INsensitive case is a lot more readable, but programming with case sensitivity can be a recipe for disaster. For example, it's a lot easier to read a name called SetOutputStage than SETOUTPUTSTAGE or setoutputstage. But if the compiler is case sensitive, all it takes is one fumblefingered letter to create 2 variables - e.g. SetOutputStage and SetOutputstage, which are virtually indistinguishable to the eye!

What is the purpose of a getchar function?

The getchar() function gets a single character from stdin.

Here is a very basic example:

#include <stdio.h>

int main() {

char ch;

do {

ch = getchar();

putchar(ch);

} while (ch != ';');

return 0;

}

It reads from data you input and prints it again of the screen after you press key. It works until it reaches ";" symbol.

The getchar() function is equivalent to getc(stdin).

What is derived data?

Derived data is data that is copied or enhanced from operational data sources into an informational database. This is in the information catalog center.

C with the line over it mean with?

A lower case c with a horizontal line above it means "with". This character might be seen as instructions for medication "should be taken "with" food"

What is type compatibility in c?

Compatible data types are data types that are intrinsically the same. For instance,

typedef int myint;

myint x = 0x7fffffff;

int y = x; // x and y are the same type, so assignment is permitted.

int * p = &x; // compatible, p points to x.

*p = y; // compatible, but y is a value, not a memory address.

short z = x; // compatible, but z will be truncated to -1.

z is -1 because x appears in memory in reverse order: 0xffffff7f. Since z is only two bytes in length it is equal to 0xffff after assignment, which equates to -1.

Write a C program to find GCD of 2 numbers using non-recursion?

One way to find the GCD (Greatest Common Divisor) of two numbers is Euclid's method. The following program demostrates this, without using recursion. The third number printed is the GCD of the first two. The highlighted lines are the core of the algorithm.

#include

int GcdByEuclid (int a, int b) {

if (a < 0 b < 0) return -1;

while (a > 0 && b > 0) if (a > b) a -= b; else b -= a;

if (a == 0) return b; else return a;

}

int main (int argc, char *argv[]) {

int a, b;

if (argc < 3) {

fprintf (stderr, "Usage: gcd a b\n");

return 1;

}

a = atoi(argv[1]);

b = atoi(argv[2]);

printf ("%d %d %d", a, b, GcdByEuclid (a, b));

return 0;

}

When is a doubly linked list appropriate?

Whenever you need constant time access to both the head and tail of the list and require bi-directional traversal of the list from any given node (not necessarily the head or tail).

With a singly linked list, the only way to perform a reverse traversal is through a recursive call. For instance, the following C function will print singly linked nodes in reverse order (the caller simply passes the head node to the function):

void print_reverse(node* current)

{

if( current )

{

print_reverse( current->next);

current->print(); }

}

While this works, for long lists there's a risk you might run out of stack space. This is because the head node (in the initial call) cannot print itself until the recursive call to the next node has returned, which it can't do until its recursive call returns, and so on until the recursion reaches the tail node. Only then will the recursions begin to unwind and the nodes can actually print themselves. Even if stack space isn't an issue, it's inefficient because you are effectively traversing the list twice; forwards to get to the tail and then backwards to do the actual printing.

With a doubly-linked list you simply traverse the list from the tail node to the head node in order to print them in reverse order:

void print_reverse(list& List)

{

node* current = List.tail;

while( 0 != current )

{

current->print();

current = current->prev; }

}

While not quite as concise as a recursive call, it is a good deal more efficient.

The other advantage is that should you have a reference to any node (whether the head, the tail or anything in between), you have the option to traverse forwards or backwards as you see fit. With a singly linked list you can only go forwards from a given node unless you used recursion to get to that node in the first place.

C program pointers to pointers examples?

Pointer to Pointer is a double pointer, denoted by (**). Pointer stores the address of the variable and pointer to pointer stores the address of a pointer variable and syntax can be given as int **ptr2ptr;

What is Dazzling Pointer in c plus plus?

The pointer that points to a block of memory that does not exist is called a dazzling pointer or wild pointer

Difference between member functions and static member functions?

c: A static function is visible only in the source file containing it. A static member is not defined. c++: A static function is visible only in the source file containing it. A static member variable is common to all instances of a class. A static member function is used to access static members.

Write an assembly language program to convert lowercase to uppercase?

inc bx ; next char.

loop upper_case

; int 21h / ah=09h - output of a string at ds:dx.

; string must be terminated by '$' sign.

lea dx, string+2

mov ah, 09h

int 21h

jmp start ; loop

; wait for any key press....

mov ah, 0

int 16h

null:

ret

Is printf keyword?

== == What is printf in c or prototype of printf with example

(q) What is prototype of printf function ? Explain each term.

Ans: Prototype of printf function is :

int printf( const char *format ,…)

Explanation of each term :

Parameter of printf function is :

(three continuous dots) : It is called ellipsis. It indicates the variable number of

arguments.

Example of ellipsis:

#include

void ellipsis(int a,...);

void main()

{

int a=5,b=10;

clrscr();

ellipsis(a,b);

getch();

}

void ellipsis(int a,...)

{

printf("%d ",a);

}

Output:5

So printf function can have any number of variables as an argument.

Write a program to delete an array element in c?

Enter how many elements you want to enter: 4

Enter the array elements:

10

20

30

40

Enter the location, where you want to delete: 3

Deleted value : 30

The new element list: 10 20 40

What Library and linking of turbo c?

Technically speaking, you can create a useful, functional C program that consists solely of statements involving only the C keywords. However, this is quite rare because C does not provide keywords that perform such things as input/output (I/O) operations, high-level mathematical computations, or character handling.

for more details visit:

http://free4ebook.com/The%20Library%20and%20Linking.html

C program to calculate First and Follow?

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char t[5],nt[10],p[5][5],first[5][5],temp;

int i,j,not,nont,k=0,f=0;

clrscr();

printf("\nEnter the no. of Non-terminals in the grammer:");

scanf("%d",&nont);

printf("\nEnter the Non-terminals in the grammer:\n");

for(i=0;i<nont;i++)

{

scanf("\n%c",&nt[i]);

}

printf("\nEnter the no. of Terminals in the grammer: ( Enter e for absiline ) ");

scanf("%d",&not);

printf("\nEnter the Terminals in the grammer:\n");

for(i=0;i<nott[i]=='$';i++)

{

scanf("\n%c",&t[i]);

}

for(i=0;i<nont;i++)

{

p[i][0]=nt[i];

first[i][0]=nt[i];

}

printf("\nEnter the productions :\n");

for(i=0;i<nont;i++)

{

scanf("%c",&temp);

printf("\nEnter the production for %c ( End the production with '$' sign )

:",p[i][0]);

for(j=0;p[i][j]!='$';)

{

j+=1;

scanf("%c",&p[i][j]);

}

}

for(i=0;i<nont;i++)

{

printf("\nThe production for %c -> ",p[i][0]);

for(j=1;p[i][j]!='$';j++)

{

printf("%c",p[i][j]);

}

}

for(i=0;i<nont;i++)

{

f=0;

for(j=1;p[i][j]!='$';j++)

{

for(k=0;k<not;k++)

{

if(f==1)

break;

if(p[i][j]==t[k])

{

first[i][j]=t[k];

first[i][j+1]='$';

f=1;

break;

}

else if(p[i][j]==nt[k])

{

first[i][j]=first[k][j];

if(first[i][j]=='e')

continue;

first[i][j+1]='$';

f=1;

break;

}

}

}

}

for(i=0;i<nont;i++)

{

printf("\n\nThe first of %c -> ",first[i][0]);

for(j=1;first[i][j]!='$';j++)

{

printf("%c\t",first[i][j]);

}

}

getch();

}

Difference between malloc and alloc?

alloc is used as header file while using malloc and calloc functions in C prog.

The definition of malloc function is in the alloc.h file.

It's stdlib.h to be more precise

What is a difference between a high level programming language and a low level programming language?

The most basic difference is that the statements in a low level language can be directly mapped to processor instructions, while a single statement in a high level language may execute dozens of instructions.

Low level refers to the fact that this is a machine language, binary in form, generally meaning one low level command = one executed instruction.

The complexity arises when we need to enable a programmer to designate one high level instruction that performs several or many machine (low level) operations.

Low Level Languages: Assembler and Advanced Assembler - see Compiler Languages.

High Level Languages: RPG, COBOL, any that make machine level programming of a computer easier.

What is Chomsky's classification of languages?

I believe it has something to do with the articulatory aspect (as opposed to other's acoustic and perceptual classifications).

> No, it is not. This is a hierarchy of formal grammars that rule the production of (human, computer, nature, etc.) "assertions". This approach is focused on a generative view of the meaningful sentences: each one of those could be generated by rules defined by a grammar, or syntactical rules. The classification is ordered by levels of expressiveness and complexity. See the related link on Wikipedia for further information.

How can you make a turbo c program by using one for loop to sort 3 numbers in ascending order?

Use the insertion sort algorithm.

Insertion sort works on the premise that a set of 1 can always be regarded as a sorted set, thus in a set of n elements, we can divide the set in two, with a sorted set at the beginning (with 1 element) and an unsorted set at the end (with all other elements). We then take the first element of the unsorted set and insert it into the sorted set, repeating until the unsorted set is empty.

We take the first element out of the unsorted set by copying it to a temporary variable, thus creating a gap in its place. We then examine the element to the left of the gap and, if the value is greater than the temporary, we copy it into the gap, effectively moving the gap one place to the left. We stop moving the gap when we reach the start of the array or the element to the left of the gap is not greater than the temporary. We then copy the temporary into the gap, increasing the sorted set by one element and reducing the unsorted set by one element.

We can implement this algorithm using just one for loop:

void sort (int* a, unsigned s) { // assume a refers to an array of length s

for (int i=2; i<s; ++i) {

int t = a[i]; // temporarily store a[i] outside the array

int g = i; // index g is the "gap" in the array

while (0<g && t<a[g-1]) { a[g]=a[g-1]; --g; } // move the gap to the correct insertion point

a[g] = t; // insert the temporary

}

}

Thus, to sort 3 numbers:

int a[3] = {2, 3, 1}; // unsorted

sort (a, 3);

assert (a[0]==1);

assert (a[1]==2);

assert (a[2]==3);

What are the advantages of using functions to modularize a program?

Advantages of functions:

  1. Program development made easy : Work can be divided among project members thus implementation can be completed in parallel.
  2. Program testing becomes easy : Easy to locate and isolate a faulty function for further investigation
  3. Code sharing becomes possible : A function may be used later by many other programs this means that a c programmer can use function written by others, instead of starting over from scratch.
  4. Code re-usability increases : A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program. This is especially useful if the code involved is long or complicated.
  5. Increases program readability : It makes possible top down modular programming. In this style of programming, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. The length of the source program can be reduced by using functions at appropriate places.
  6. Function facilitates procedural abstraction : Once a function is written, it serves as a black box. All that a programmer would have to know to invoke a function would be to know its name, and the parameters that it expects
  7. Functions facilitate the factoring of code : Every C program consists of one main( ) function typically invoking other functions, each having a well-defined functionality.