program that does not terminate - c

I wrote a program that should take an array of numbers and find the array index of the smallest number. However, when I type the numbers with spaces between and then press enter, the program keeps running. What can be the cause? Here is the code:
#include<stdio.h>
//read numbers to an array
//find minimum
//print the index of minimum
double findMinimum(int size,double array[]){
int n;
int minIndex=0;
for(n=1;n<size;size++){
if(array[n]<array[n-1]){
minIndex=n;
}
}
return minIndex;
}
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
double inArray[size];
printf("Enter an array of numbers:");
int k=0;
char c;
while(c!='\n'){
c=getchar();
if(c=='\n'){
break;
}
scanf("%lf",&inArray[k]);
k++;
size++;
};
int minIndex=0;
minIndex=findMinimum(size,inArray);
printf("The index of minimum number is %i",minIndex);
return 0;
}
I also took the part of the code that scans numbers to an array. I tried to change the while loop and used "break" statement, but the output gave all numbers in an array except the first one. Here is the code:
#include<stdio.h>
//read numbers to an array
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
double inArray[size];
printf("Enter an array of numbers ending with question mark:\n");
int k=0;
char c;
while(1){
c=getchar();
if(c=='?'){
break;
}
scanf("%lf",&inArray[k]);
k++;
size++;
};
int n;
for(n=0;n<size;n++){
printf("%f\n",inArray[n]);
}
return 0;
}
Thanks for help in advance!

for(n=1;n<size;size++){
if(array[n]<array[n-1]){
minIndex=n;
}
}
The issue in your code is you are incrementing size, thats why your loop is not terminating. increment n
Edit
you have initialized your 'n' with 1 , however arrays start with zero index thats why it misses the first element,
for(n=0;n<size;n++){
if(array[n]<array[minIndex]){
minIndex=n;
}
}

try this one :
for(n=1; n < size; n++){
if(array[n]<array[minIndex]){
minIndex=n;
}
}

Related

My c program keeps crashing and I do not know why

I am writing a program like hangman in c and I am trying to run it .The problem is that it's working fine until I give it a letter to quess the word but then it crashes with -1073741819 (0xC0000005). Can someone help me solve this, I think its something really small that I cant
see . Thank you for helping me!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Rules(void);
void maskWord (char starword[], int size);
int playRound(char starword[], char answer[]);
void updateStarWord(char starword[], char answer[], char userguess);
int occurancesInWord(char userguess, char answer[]);
int c=0;
char answer[128];
int N;
int main()
{
int ch,size;
char starword[1000];
do
{
printf("---Welcome to Hangman!---\n");
printf("1.Start Game\n2.Instructions\n3.Exit\n");
scanf("%d",&ch);
if(ch>0&& ch<4)
{
switch(ch)
{
case 1:
maskWord(starword,size);break;
case 2:
Rules();break;
}
}
else
system("cls");
}
while(ch!=3);
return 0;
}
void Rules(void)
{
do
{
do
{
printf("\nThe word to guess is represented by a row of dashes representing each letter of the word.");
printf("\nRules may permit or forbid proper nouns, such as names, places, brands, or slang.");
printf("\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions.");
printf("\nIf the suggested letter does not occur in the word, the other player draws one element of a hanged stick figure as a tally mark.\n");
}
while(getchar()!='\n');
}
while(getchar()!='\n');
}
void maskWord (char starword[], int size)
{
printf("Enter word to guess: ");
fflush(stdout);
scanf(" %s", answer);
int N = strlen(answer);
int mask[N];
for (int i=0; i < N; ++i)
{
mask[i] = 0;
}
playRound(mask,N);
}
int playRound(char starword[], char answer[])
{
// Loop over each round of guessing
int gameover = 0;
while (! gameover)
{
// Print word with *s for unguessed letters
printf("The word is : ");
for(int j=0; j < answer; ++j)
{
if (starword[j])
{
printf("%c", answer[j]);
}
else
{
printf("*");
}
}
printf("\n");
// Get player's next guess
char guess;
printf("\nGive a letter: ");
fflush(stdout);
scanf(" %c", &guess);
updateStarWord(starword,answer,guess);
}
}
void updateStarWord(char starword[], char answer[], char userguess)
{
// Mark true all mask positions corresponding to guess
int k;
for(k=0; k < answer; ++k)
{
if ((answer[k]) ==(userguess))
{
starword[k] = 1;
}
}
}
Your for loop doesn't make sense because the condition for terminating it is k < answer. You are comparing an integer (k) to a pointer (answer). The compiler should have warned you about this, so make sure your compiler warnings are turned on and you are paying attention to them. Pointers and integers are different things, and comparing them is almost never what you want to do.
If answer is null-terminated, you could probably replace that condition with answer[k]. Or maybe updateStarWord needs to take an argument that indicates the length of answer, and then the condition would be k < answer_length.

Path in a Heap takes too long time

This is a question from oj PAT
Insert a sequence of given numbers into an initially empty min-heap H. Then for any given index i, you are supposed to print the path from H[i] to the root.
However, my code always time out, i.e, it takes too long time. How to solve it?
main()
{
int i,*a,n,m,k,data;
scanf("%d%d",&n,&m);
a=malloc(n*sizeof(int));
a[0]=-10001; //
for(i=1;i<=n;i++)
{
scanf("%d",&data);
heapAdjust(a,data);
}
for(i=1;i<=m;i++)
{
scanf("%d",&k);
printf("%d",a[k]);
k=k/2;
while(1)
{
printf(" %d",a[k]);
if(k==1)
break;
k=k/2;
}
printf("\n");
}
free(a);
}
void heapAdjust(int a[],int data) // make heap
{
static int size=0;
int i;
i=++size;
for(;a[i/2]>data;i=i/2)
a[i]=a[i/2];
a[i]=data;
}
You are probably running into an infinite loop because k becomes zero at some point.
Try changing the break condition inside the while(1) loop from k == 1 to k <= 1 and see if that helps.

Output coming same every time

I wrote this program which takes n and k as input and then takes an array a[n] as input. The program must give the output as the total no of distinct integers in array a that are less than k and odd. But this program with every input is producing 0 as output.
#include<stdio.h>
int main()
{
long long int n,i,j,k,temp=-1;
scanf("%lld %lld",&n,&k);
long long int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
long long int cnt=0;
for(i=0;i<n;i++)
{
if(a[i]<k)
{
if((a[i]%2)==1)
cnt++;}
}
for(i=0;i<(n-1);i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
cnt--;
a[j]=temp;
--temp;
}
}
}
printf("%lld",cnt);
return 0;
}
scanf("%d", &a[i]);
Must be:
scanf("%lld", &a[i]);
check out the inner for loop, maybe you need to declare a variable and increment that and write and if statement that says, if variable==1 then print the desired value.
Not sure but might work.

Counting arguments passed to scanf() in C

Is there any way to Count number of arguments passed to scanf() in C ? Specially, while assigning int arrays through scanf().
Example:
int array[1000], i;
for(i=0;i<1000;i++)
scanf("%d",&array[i]);
I need to count how many values are inserted by user
I don't think there's a built in way to do this, but why not just create a counter that increments when scanf returns successfully and break the loop otherwise?
int scanf_counter = 0;
int array[1000], i;
for(i=0;i<1000;i++) {
if(scanf("%d",&array[i] > 0) {
scanf_counter++;
} else {
break;
}
}
Although I'm not sure I understand your question exactly because you could always just find the size of the array by doing this
int size = sizeof(array)/sizeof(array[0])
Look the scanf() fragment carefully, thus:
include
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}

Calculating Size of the Array

I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.

Resources