I'm working on a program to learn the concept of stack-array. I'm facing a error where the stack isn't displayed properly [display() function]. Where am i going wrong??
I tried checking the code twice. it doesn't display the output from display()
#include <iostream>
#include <conio.h>
#include <process.h>
using namespace std;
const int size =50;
int pop(int [] ,int&);
int push(int [] ,int , int);
void display(int [] ,int);
int main()
{
int s[size],item,top=-1,res;
char ch='y';
while (ch=='y'||ch=='Y')
{
cout<<"\n Enter the item for insertion: ";
cin>>item;
res=push(s,top,item);
if(res==-1)
{
cout<<"\nOVERFLOW!!!";
system("pause");
exit(1);
}
cout<<"\nThe stack is :"<<endl;
display(s,top);
cout<<"More elements??";
cin>>ch;
}
cout<<"Now deletion begins\n";
ch='y';
while(ch=='y'||ch=='Y')
{
res=pop(s,top);
if(res==-1)
{
cout<<"UNDERFLOW!!";
system("pause");
exit(1);
}
else
{
cout<<"\nElement deleted is: "<<res<<endl;
cout<<"\n The stack now is: "<<endl;
display(s,top);
}
cout<<"delete elements??";
cin>>ch;
}
getch();
return 0;
}
int push(int s[],int top,int ele)
{
if(top==size-1) return-1;
else
{
top++;
s[top]=ele;
}
return 0;
}
int pop (int s[],int &top)
{
int ret;
if(top==-1) return -1;
else
{
ret=s[top];
top--;
}
return ret;
}
void display (int s[], int top)
{
if(top==-1) return;
cout<< s[top]<<"<--"<<endl;
for(int i=top-1;i>=0;i--)
{
cout<<s[i]<<endl;
}
}
the display() function should display the array elements in form of a stack.
This is my code
import java.util.*;
class node{
public int data;
public node link;
public node()
{
data = 0;
link = null;
}
public node(int d, node l)
{
data = d;
link = l;
}
void setlink(node n)
{
link = n;
}
void setdata(int dat)
{
data = dat;
}
int showdata()
{
return data;
}
node showlink()
{
return link;
}
}
class stack{
node top;
int size;
stack()
{
top = null;
size = 0;
}
void push()
{
node npt = new node();
size++;
System.out.println("Enter the value you want to enter :");
Scanner sc = new Scanner(System.in);
int val;
val = sc.nextInt();
npt.setdata(val);
if( top == null )
{
top = npt;
}
else
{
npt.setlink(top);
top = npt;
}
}
void pop()
{
node npt = top;
top = npt.showlink();
size--;
}
void showstack()
{
node nptr = top;
int i = 1;
while( nptr != null )
{
System.out.println("Data at position "+ i + " is : " + nptr.showdata());
i++;
nptr = nptr.showlink();
}
}
}
class stacked{
public static void main(String args[])
{
stack obj = new stack();
int temp = 0;
while( temp != 1 )
{
System.out.println("-- Enter 1 to exit -- 2 to push -- 3 to pop -- 4 to show Stack --");
Scanner sc = new Scanner(System.in);
temp = sc.nextInt();
if(temp == 1)
{
break;
}
switch(temp)
{
case 2: obj.push();
break;
case 3: obj.pop();
break;
case 4: obj.showstack();
break;
}
temp++;
}
}
}
My question is in the function void push() in class stack what is the difference between "=" operator and setlink() function.
I mean why cannot we write npt = top; instead of npt.setlink(top); ?
What does "=" do and how is the referencing done?
Thanks
i am very new in programming and its my 2nd semester in my college an dour teacher teach us about linked list and malloc function where we can make a node dynamically and increase or decrease its size . our teacher teach us how to store a integer value in list like this
struct node
{
int num;
struct node *next;
}head;
but i want to store a string say "name" of students in linked list instead of integer .. so i want to know how to do this ..
i write this code for that
#include <stdio.h>
#include <conio.h>
struct node
{
char name[20];
int age;
struct node *next;
};
//
void addatbegin(struct node **q,char name [20],int age)
{
struct node *r;
r=(struct node *)malloc(sizeof(struct node));
r->name=name;
r->age=age;
r->next=*q;
*q=r;
}
//
void addatend(struct node **q,char name[20],int age)
{
struct node *temp,*r;
if(*q==NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
temp->name=name;
temp->age=age;
temp->next=NULL;
*q=temp;
}
else {
temp=*q;
while(temp->next!=NULL)
{
temp=temp->next;
}
r=(struct node *)malloc(sizeof(struct node));
r->name=name;
r->age=age;
r->next=NULL;
temp->next=r;
}}
void main()
{
struct node *head;
int age,ch;
char name[20];
head=NULL;
while(1)
{
printf("***** MENU ****** \n");
printf("1.Add at Begining of List\n");
printf("2.Add at End of List\n");
printf("3.Print the list\n");
printf("4.Exit\n \n");
printf("Enter Your choice:- ");
scanf(" %d",&ch);
switch(ch)
{
case1:printf("Enter Name:- ");
scanf(" %s",name);
printf("Enter Age:- ");
scanf(" %d",&age);
addatbegin(&head,name,age);
break;
}
getch(); }}
but its shwoing error lvalue missing
I want to arrange my link list (which contains char arrays) in ascending order. This program should allow the user to input some names and then display them in ascending order. I have used the strncpy function. There are no compilation errors.But instead of names, the output gives some integers (perharps addresses). Please help me! I am new to C!
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char name [10];
struct node
{
char nm [10];
struct node *next;
}*newnode, *prev, *temp, *display, *current, *list;
void createlist()
{
list=NULL;
};
void insert ()
{
newnode=(struct node*) malloc (sizeof (struct node));
printf("Enter the Name: ");
scanf("%s",&name);
strncpy(newnode->nm,name, 10);
newnode->next=NULL;
if (list==NULL)
{
list=newnode;
}
else if (name<list->nm)
{
newnode->next=list;
list=newnode;
}
else
{
temp=list;
int place;
place=0;
while (temp!=NULL && place ==0)
{
if (name>temp->nm)
{
prev=temp;
temp=temp->next;
}
else
{
place=1;
}
newnode->next=prev->next;
prev->next=newnode;
}
}
}
void displayname()
{
if (list==NULL)
printf("\n\nList is empty");
else
{
display=list;
while(display!=NULL)
{
printf("%d\n",display->nm);
display=display->next;
}
}
}
int main()
{
char choice;
choice=='y';
createlist();
do
{
insert ();
printf("Do you want to continue? ");
scanf("%s",&choice);
}while (choice='y'&& choice!='n');
displayname();
}
In the display function you have
printf("%d\n",display->nm);
The %d formatter outputs the argument as an integer. Use printf's %s formatter to get character arrays
printf("%s\n",display->nm);
You will still need to write the sorting code ... put the problem of outputtin numbers instead of text.
I'm making this game in MonoGame (basically Xna) that uses DynamicSoundEffectInstance class. MonoGame does not have an implementation of DynamicSoundEffectInstance yet, so I made my own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if MONOMAC
using MonoMac.OpenAL;
#else
using OpenTK.Audio.OpenAL;
#endif
using System.Threading;
namespace Microsoft.Xna.Framework.Audio
{
public sealed class DynamicSoundEffectInstance : IDisposable
{
private const int BUFFERCOUNT = 2;
private SoundState soundState = SoundState.Stopped;
private AudioChannels channels;
private int sampleRate;
private ALFormat format;
private bool looped = false;
private float volume = 1.0f;
private float pan = 0;
private float pitch = 0f;
private int sourceId;
private int[] bufferIds;
private int[] bufferIdsToFill;
private int currentBufferToFill;
private bool isDisposed = false;
private bool hasSourceId = false;
private Thread bufferFillerThread = null;
// Events
public event EventHandler<EventArgs> BufferNeeded;
internal void OnBufferNeeded(EventArgs args)
{
if (BufferNeeded != null)
{
BufferNeeded(this, args);
}
}
public DynamicSoundEffectInstance(int sampleRate, AudioChannels channels)
{
this.sampleRate = sampleRate;
this.channels = channels;
switch (channels)
{
case AudioChannels.Mono:
this.format = ALFormat.Mono16;
break;
case AudioChannels.Stereo:
this.format = ALFormat.Stereo16;
break;
default:
break;
}
}
public bool IsDisposed
{
get
{
return isDisposed;
}
}
public float Pan
{
get
{
return pan;
}
set
{
pan = value;
if (hasSourceId)
{
// Listener
// Pan
AL.Source(sourceId, ALSource3f.Position, pan, 0.0f, 0.1f);
}
}
}
public float Pitch
{
get
{
return pitch;
}
set
{
pitch = value;
if (hasSourceId)
{
// Pitch
AL.Source(sourceId, ALSourcef.Pitch, XnaPitchToAlPitch(pitch));
}
}
}
public float Volume
{
get
{
return volume;
}
set
{
volume = value;
if (hasSourceId)
{
// Volume
AL.Source(sourceId, ALSourcef.Gain, volume * SoundEffect.MasterVolume);
}
}
}
public SoundState State
{
get
{
return soundState;
}
}
private float XnaPitchToAlPitch(float pitch)
{
// pitch is different in XNA and OpenAL. XNA has a pitch between -1 and 1 for one octave down/up.
// openAL uses 0.5 to 2 for one octave down/up, while 1 is the default. The default value of 0 would make it completely silent.
return (float)Math.Exp(0.69314718 * pitch);
}
public void Play()
{
if (!hasSourceId)
{
bufferIds = AL.GenBuffers(BUFFERCOUNT);
sourceId = AL.GenSource();
hasSourceId = true;
}
soundState = SoundState.Playing;
if (bufferFillerThread == null)
{
bufferIdsToFill = bufferIds;
currentBufferToFill = 0;
OnBufferNeeded(EventArgs.Empty);
bufferFillerThread = new Thread(new ThreadStart(BufferFiller));
bufferFillerThread.Start();
}
AL.SourcePlay(sourceId);
}
public void Apply3D(AudioListener listener, AudioEmitter emitter)
{
Apply3D(new AudioListener[] { listener }, emitter);
}
public void Pause()
{
if (hasSourceId)
{
AL.SourcePause(sourceId);
soundState = SoundState.Paused;
}
}
public void Apply3D(AudioListener[] listeners, AudioEmitter emitter)
{
// get AL's listener position
float x, y, z;
AL.GetListener(ALListener3f.Position, out x, out y, out z);
for (int i = 0; i < listeners.Length; i++)
{
AudioListener listener = listeners[i];
// get the emitter offset from origin
Vector3 posOffset = emitter.Position - listener.Position;
// set up orientation matrix
Matrix orientation = Matrix.CreateWorld(Vector3.Zero, listener.Forward, listener.Up);
// set up our final position and velocity according to orientation of listener
Vector3 finalPos = new Vector3(x + posOffset.X, y + posOffset.Y, z + posOffset.Z);
finalPos = Vector3.Transform(finalPos, orientation);
Vector3 finalVel = emitter.Velocity;
finalVel = Vector3.Transform(finalVel, orientation);
// set the position based on relative positon
AL.Source(sourceId, ALSource3f.Position, finalPos.X, finalPos.Y, finalPos.Z);
AL.Source(sourceId, ALSource3f.Velocity, finalVel.X, finalVel.Y, finalVel.Z);
}
}
public void Dispose()
{
if (!isDisposed)
{
Stop(true);
AL.DeleteBuffers(bufferIds);
AL.DeleteSource(sourceId);
bufferIdsToFill = null;
hasSourceId = false;
isDisposed = true;
}
}
public void Stop()
{
if (hasSourceId)
{
AL.SourceStop(sourceId);
int pendingBuffers = PendingBufferCount;
if(pendingBuffers > 0)
AL.SourceUnqueueBuffers(sourceId, PendingBufferCount);
if (bufferFillerThread != null)
bufferFillerThread.Abort();
bufferFillerThread = null;
}
soundState = SoundState.Stopped;
}
public void Stop(bool immediate)
{
Stop();
}
public TimeSpan GetSampleDuration(int sizeInBytes)
{
throw new NotImplementedException();
}
public int GetSampleSizeInBytes(TimeSpan duration)
{
int size = (int)(duration.TotalMilliseconds * ((float)sampleRate / 1000.0f));
return (size + (size & 1)) * 16;
}
public void SubmitBuffer(byte[] buffer)
{
this.SubmitBuffer(buffer, 0, buffer.Length);
}
public void SubmitBuffer(byte[] buffer, int offset, int count)
{
if (bufferIdsToFill != null) {
AL.BufferData (bufferIdsToFill [currentBufferToFill], format, buffer, count, sampleRate);
AL.SourceQueueBuffer (sourceId, bufferIdsToFill [currentBufferToFill]);
currentBufferToFill++;
if (currentBufferToFill >= bufferIdsToFill.Length)
bufferIdsToFill = null;
else
OnBufferNeeded (EventArgs.Empty);
} else {
throw new Exception ("Buffer already full.");
}
}
private void BufferFiller()
{
bool done = false;
while (!done)
{
var state = AL.GetSourceState(sourceId);
if (state == ALSourceState.Stopped || state == ALSourceState.Initial)
AL.SourcePlay(sourceId);
if (bufferIdsToFill != null)
continue;
int buffersProcessed;
AL.GetSource(sourceId, ALGetSourcei.BuffersProcessed, out buffersProcessed);
if (buffersProcessed == 0)
continue;
bufferIdsToFill = AL.SourceUnqueueBuffers(sourceId, buffersProcessed);
currentBufferToFill = 0;
OnBufferNeeded(EventArgs.Empty);
}
}
public bool IsLooped
{
get
{
return looped;
}
set
{
looped = value;
}
}
public int PendingBufferCount
{
get
{
if (hasSourceId)
{
int buffersQueued;
AL.GetSource(sourceId, ALGetSourcei.BuffersQueued, out buffersQueued);
return buffersQueued;
}
return 0;
}
}
}
}
Now, I followed this tutorial on making dynamic sounds in Xna, which worked with my custom MonoGame class. However, when I run the project (Xamarin Studio 4, Mac OS X 10.8, with MonoGame 3.0.1), it throws this exception:
Buffer already full
Pointing at the code in my custom class:
public void SubmitBuffer(byte[] buffer, int offset, int count)
{
if (bufferIdsToFill != null) {
AL.BufferData (bufferIdsToFill [currentBufferToFill], format, buffer, count, sampleRate);
AL.SourceQueueBuffer (sourceId, bufferIdsToFill [currentBufferToFill]);
currentBufferToFill++;
if (currentBufferToFill >= bufferIdsToFill.Length)
bufferIdsToFill = null;
else
OnBufferNeeded (EventArgs.Empty);
} else {
throw new Exception ("Buffer already full."); //RIGHT HERE IS THE EXCEPTION
}
}
I commented out the exception, and ran it again. It played the sound, with pops in it, but it still played it. How can I clear the buffer, so it is not full? I followed this tutorial EXACTLY, so all the code I added to my project is in there.
Oh! Figured it out myself; I changed the pending buffer count from 3 to 2. My final submit buffer code was:
while(_instance.PendingBufferCount < 2)
SubmitBuffer();
Where the 2 is, used to be a 3. Now it no longer throws the exception.