Towers of Hanoi code in c language using stacks?
#include <iostream.h>
// a disk with a value , which is an element of the stack ,tower in this case
class Disk
{
public:
int value;
Disk* next;
};
class Tower //a stack data structure representing a tower
{
public:
int size;
Disk* current;
Tower()
{
size=0;
current=NULL;
}//default constructor
int peep();
bool push(int);
bool pop();
bool isEmpty();
int getTowerSize();
void printTowerSize();
void printTowerDisks();
void printTowerMenu();
};
int Tower::peep()
{
return this->current->value;
}
bool Tower::push(int ele)
{
Disk* temp;
temp=new Disk;
if(current==NULL)
{
temp->next=NULL;
}
else
{
temp->next=current;
}
temp->value=ele;
this->current=temp;
size++;
return false;
}
bool Tower::pop()
{
if(isEmpty())
{
cout<<"\nTower is Empty\n";
return false;
}
else
{
current=current->next;
size=size--;
}
return true;
}
bool Tower::isEmpty()
{
if(getTowerSize()==0)
return true;
return false;
}
int Tower::getTowerSize()
{
return size;
}//returns size of the Tower
void Tower::printTowerSize()
{
cout<<"\nThe Size of the Tower:"<<size<<"\n";
}//print the Tower size
void Tower::printTowerDisks()
{
if(this->isEmpty())
{
cout<<"-----\n";
cout<<" "<<endl;
cout<<"-----\n";
return;
}
Disk *curr2;
curr2=this->current ;
cout<<"-----\n";
cout<<"Tower\n";
cout<<"-----\n";
int i=0;
while(curr2 !=NULL)
{
if(i>4)
break;
i++;
cout<<" |"<<curr2->value<<"|\n";
curr2=curr2->next;
}
}// print the Tower
void createSourceTower(Tower *source,int numberOfDisks)
{
for(int i=numberOfDisks;i>0;i--)
{
source->push(i);
}
}
void moveDisk(Tower *source,Tower *dest) // movinng a disk from source to destionation
{
dest->push(source->current->value );
source->pop();
}
void hanoi( int N, Tower *source, Tower *dest,Tower *aux ) // move N disks from source to destination
{
if (N > 0 )
{
hanoi(N - 1, source, aux, dest); //move n-1 disks from source to auxxilary (sub problem)
moveDisk(source,dest); //move nTH disk from source to destination
hanoi(N - 1, aux, dest, source); //move n-1 disks from auxillary to destination (sub problem)
}
}
void main()
{
Tower *source,*destination,*auxillary;
//Towers required for the 3 towers source destination and auxillary
source=new Tower;
destination=new Tower;
auxillary=new Tower;
//take number of disks from user
int numberOfDisks;
cout<<"Enter number of Disks in the source Tower";
cin>>numberOfDisks;
//inserting the disks into the source tower
createSourceTower(source,numberOfDisks);
cout<<"==============================================="<<endl;
cout<<"Initial Scenario of the Towers "<<endl;
cout<<"Source"<<endl;
source->printTowerDisks ();
cout<<"Auxillary"<<endl;
auxillary->printTowerDisks ();
cout<<"Destination"<<endl;
destination->printTowerDisks ();
hanoi( numberOfDisks,source, destination, auxillary );
cout<<"==============================================="<<endl;
cout<<"Final Scenario of the Towers "<<endl;
cout<<"Source"<<endl;
source->printTowerDisks();
cout<<"Auxillary"<<endl;
auxillary->printTowerDisks ();
cout<<"Destination"<<endl;
destination->printTowerDisks ();
cout<<"==============================================="<<endl;
}
What is the difference between static global and local global variable?
First, lets speak about the scope of a variable. The scope of a variable is the section of the application that can see and manipulate that variable. If the variable is declared in a procedure when that procedure is called, only that procedure can use that variable. Hence that variable is considered "Local".
Now Static. Static variables are variables that are created with the static key word as in:- function ab(var1 as integer)as integer static iTotal as integer itotal =iTotal + var1 (rest of ccode goes here) end function
Now when this function is called the first time, iTotal will be assigned the value of var1. The next time the function is called, iTotal will retain the previous value and the new value of var1 will be added to it. Hope this helps. (theTeacha)
Static variables life time is not under any scope.It initializes only one time from creation to delete.let me explain by a pgm.
void main()
{
int a=1;
static s=1;
int k=0;
for(k=0;k<1;k++)
{
i++;
s++;
main();
}
printf("%d is i",&i);
printf(%d is S",&s);
getch();
}
Output will be
2 is i
3 is s
It Shows that local variable initialize every time the function call.But Static variable initializes only once
<><><>
For a variable, static means it keeps its value even when the enclosing code is not active--out of scope. A static variable is assigned to a fixed memory location when the program runs, so it is possible to examine a static variable at any time the program is active, even when the function where the var is declared is not active. A local variable is dynamically allocated storage space when a function is called, and its storage is given up when the function ends, so it only exists while the function is executing.
For a function, static declaration means it can only be called from functions in the same file (in C).
What is a no args constructor?
No args means no arguments. Just like any regular method, a constructor can have zero or more arguments.
No args means no arguments. Just like any regular method, a constructor can have zero or more arguments.
No args means no arguments. Just like any regular method, a constructor can have zero or more arguments.
No args means no arguments. Just like any regular method, a constructor can have zero or more arguments.
What is the function of the pointer in an ocular lens?
To indicate something visible in the microscope, like say a part of that paramecium your teacher tells you to locate, or as a point of reference, if your subject is moving, or even as a means to make an estimated measurement of something, although a micrometer is better in this case.
What Is a translating program which translates entire source program into machine language program?
High-level source code is converted to native machine code either by an interpreter or a compiler. Interpreted code requires a runtime in order to perform the conversion each time the program is executed whereas compiled code typically produces a standalone machine code program that can be executed without further interpretation. There are some exceptions, most notably Java which is first compiled to Java byte code which is then interpreted by the Java virtual machine on each execution.
An interpreter always converts high-level code to native machine code but, because it must perform the conversion while the code is executing via the interpreter, interpreted code executes much more slowly than native machine code.
Technically, a compiler is simply a program that converts high-level code to a lower-level code. That lower-level code could be another high-level language. For example, a C++ source could be compiled to produce a C source. However, converting the other way around (such as from C to C++) can only be done manually because humans can think in abstract terms far more easily than machines can.
Low-level assembly language source are converted to machine code using an assembler. Machine code can also be disassembled to produce an assembly-like source known as a disassembly, however the resultant code is extremely low-level because there are no named variables (only memory offsets) and all user-comments will have been stripped out during assembly or compilation.
It depends on how you implement your stack.
The most simple method is (for a stack of 42 int, no checks) :
int *stack.
int *stack_pointer;
/* create stack */
stack_pointer = stack = malloc(42 * sizeof (int));
/* insert (push) element */
*stack_pointer++ = element;
/* extract (pop) element */
element = *--stack_pointer;
Program in c to find the value of nCr using function?
/*
* Purpose : Calculate the factorial of a number
* Inputs : int x -- the number of interest
* Outputs : x! if x is non-negative, -1 otherwise
*/
int factorial (int x)
{
int x_factorial = x;
if (x > 0)
{
while (x > 1)
{
x_factorial *= --x;
}
return x_factorial;
}
else if (x = 0)
return 1;
else
return -1;
}
/*
* Purpose : Calculate the binomial coefficient nCr
* Inputs : int n -- the set size
* int r -- how many to choose
* Outputs : The binomial coefficient nCr if r is valid, -1 otherwise
*/
int nCr (int n, int r)
{
if (r >= 0 && n >= r)
return factorial(n) / (factorial(r) * factorial(n - r));
else
return -1;
}
Check whether the string is palindrome or not without using library functions?
void main()
{ char a[30],b[30];
int i,j,f=1;
printf("\nEnter a string");
gets(a);
for(i=0;a[i]!=\0;i++);
for(j=0;i!=0;i--)
{ b[j++]=a[i];
}
b[j]=\0;
for(i=0;a[i]!=\0;i++)
{ if(a[i]!=b[i])
{ f=0;
break;
}
}
if(f==0)
printf("NOT PALINDROME");
else
printf("PALINDROME");
getch();
}
Syntax error may happen.
How many compiler in c plus plus?
They are completely unrelated. Java was designed as an attempt to improve C++, and C# was designed as an attempt to improve Java, so they have many things in common. They are not, however, the same language.
Volatile variables are variables that may change value while they are being operated upon. For instance, a hardware clock is constantly updated by the operating system, thus its value is constantly changing. If you refer to the value, you must declare it volatile because the value is outwith the control of the program.
How do you write a program in C to swap two variables using a function?
#include<iostream>
void swap(int* x, int* x){
(*x)^=(*y)^=(*x)^=(*y);
}
int main()
{
int a, b;
a=10;
b=20;
std::cout<<"Before swap: a="<<a<<", b="<<b<<std::endl;
swap(&a,&b);
std::cout<<"After swap: a="<<a<<", b="<<b<<std::endl;
return(0);
}
Write a c program to determine the size of an array?
using sizeof operator the size of whole array can be calculated, then divide it with the zise of the datatype(E.g. for int =4, char =2....etc.)
Example:
#define Narray (sizeof(array)/sizeof(array[0]))
What is time complexity of stack?
All major queue operations (push, pop and front) are constant time operations.
How to write a program in C programming language to multiply two polynomials?
#include <stdio.h>
#include <conio.h>
#define MAX 10
struct term
{
int coeff ;
int exp ;
} ;
struct poly
{
struct term t [10] ;
int noofterms ;
} ;
void initpoly ( struct poly *) ;
void polyappend ( struct poly *, int, int ) ;
struct poly polyadd ( struct poly, struct poly ) ;
void display ( struct poly ) ;
void main( )
{
struct poly p1, p2, p3 ;
clrscr( ) ;
initpoly ( &p1 ) ;
initpoly ( &p2 ) ;
initpoly ( &p3 ) ;
polyappend ( &p1, 1, 4 ) ;
polyappend ( &p1, 2, 3 ) ;
polyappend ( &p1, 2, 2 ) ;
polyappend ( &p1, 2, 1 ) ;
polyappend ( &p2, 2, 3 ) ;
polyappend ( &p2, 3, 2 ) ;
polyappend ( &p2, 4, 1 ) ;
p3 = polymul ( p1, p2 ) ;
printf ( "\nFirst polynomial:\n" ) ;
display ( p1 ) ;
printf ( "\n\nSecond polynomial:\n" ) ;
display ( p2 ) ;
printf ( "\n\nResultant polynomial:\n" ) ;
display ( p3 ) ;
getch( ) ;
}
/* initializes elements of struct poly */
void initpoly ( struct poly *p )
{
int i ;
p -> noofterms = 0 ;
for ( i = 0 ; i < MAX ; i++ )
{
p -> t[i].coeff = 0 ;
p -> t[i].exp = 0 ;
}
}
/* adds the term of polynomial to the array t */
void polyappend ( struct poly *p, int c, int e )
{
p -> t[p -> noofterms].coeff = c ;
p -> t[p -> noofterms].exp = e ;
( p -> noofterms ) ++ ;
}
/* displays the polynomial equation */
void display ( struct poly p )
{
int flag = 0, i ;
for ( i = 0 ; i < p.noofterms ; i++ )
{
if ( p.t[i].exp != 0 )
printf ( "%d x^%d + ", p.t[i].coeff, p.t[i].exp ) ;
else
{
printf ( "%d", p.t[i].coeff ) ;
flag = 1 ;
}
}
if ( !flag )
printf ( "\b\b " ) ;
}
/* adds two polynomials p1 and p2 */
struct poly polyadd ( struct poly p1, struct poly p2 )
{
int i, j, c ;
struct poly p3 ;
initpoly ( &p3 ) ;
if ( p1.noofterms > p2.noofterms )
c = p1.noofterms ;
else
c = p2.noofterms ;
for ( i = 0, j = 0 ; i <= c ; p3.noofterms++ )
{
if ( p1.t[i].coeff p2.t[j].exp )
{
p3.t[p3.noofterms].coeff = p1.t[i].coeff + p2.t[j].coeff ;
p3.t[p3.noofterms].exp = p1.t[i].exp ;
i++ ;
j++ ;
}
else
{
p3.t[p3.noofterms].coeff = p1.t[i].coeff ;
p3.t[p3.noofterms].exp = p1.t[i].exp ;
i++ ;
}
}
else
{
p3.t[p3.noofterms].coeff = p2.t[j].coeff ;
p3.t[p3.noofterms].exp = p2.t[j].exp ;
j++ ;
}
}
return p3 ;
}
What is better turbo c or dev C?
Depends upon the personal opinion. They both are different IDE. Dev C used the MICGW compiler while Turbo C uses Borland compiler. Hence due to this, certain inbuilt functions will not work in Dev C. clrscr() is one such function. However Turbo C is outdated and does not use follow many of the programming standards.
Write a program to compare two strings?
Registers used: ax,ds,si,di,cl
flags affected: zf,cf
program:
assume cs:code,ds:data
code segment
mov ax,data
mov ds,ax
mov si,offset str1
mov di,offset str2
mov cl,count
cld
rep cmpsb
hlt
code ends
data segment
str1 db 04h,05h,07h,08h
count equ 04h
org 0010h
str2 db 04h,06h,07h,09h
data ends
end
result:
input: str1 (ds:0000h) = 04h,05h,07h,08h
str2 (ds:0010h) = 04h,06h,07h,09h
How do you access extern variable in c?
The usual method: with its name:
extern int errno;
errno= 17;
C program for optimal merge pattern?
#include<iostream.h> #include<conio.h> void main() { clrscr(); int i,k,a[10],c[10],n,l; cout<<"Enter the no. of elements\t"; cin>>n; cout<<"\nEnter the sorted elments for optimal merge pattern"; for(i=0;i<n;i++) { cout<<"\t"; cin>>a[i]; } i=0;k=0; c[k]=a[i]+a[i+1]; i=2; while(i<n) { k++; if((c[k-1]+a[i])<=(a[i]+a[i+1])) { c[k]=c[k-1]+a[i]; } else { c[k]=a[i]+a[i+1]; i=i+2; while(i<n) { k++; if((c[k-1]+a[i])<=(c[k-2]+a[i])) { c[k]=c[k-1]+a[i]; } else { c[k]=c[k-2]+a[i]; }i++; } }i++; } k++; c[k]=c[k-1]+c[k-2]; cout<<"\n\nThe optimal sum are as follows......\n\n"; for(k=0;k<n-1;k++) { cout<<c[k]<<"\t"; } l=0; for(k=0;k<n-1;k++) { l=l+c[k]; } cout<<"\n\n The external path length is ......"<<l; getch(); }
Write a program that accepts two numbers a and b and checks whether or not a is divisible by b?
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main (void) {
char arry[100];
int i,count=0;
float a,b;
printf("Enter a 2 Number ");
scanf("%d %d",&a,&b);
if(a%b == 0){printf("its divisible");} else {printf("its not divisible"); }
getch();
return 1;
}
What are the different types of c preprocessor directives?
As the name indicates the C PreProcessor is the preprocessor for C programming language and is used by the compiler automatically to transform the program before actual compilation. It processes the preprocessor directives (file inclusion, macro definition and conditional compilation) in the source code. It is also known as a macro processor.