not getting the right counter inside my function array - c

function hot_days(), that has two parameters: the number of temperatures for the current month and an array in which the temperatures are stored. Search through the temp array and count all the days on which the noon temp exceeds 32. Return this count.
check my hot_days function in the end of the code. the icounter is not working and i think the problem is in the x < 32.
#include <stdio.h>
#include <conio.h>
#define HIGH 32
//function prototypes
void read_temps(int []);
void hot_days(int [], int []);
int main()
{
//Array
int TempsAry[31];
int hotAry[31];
//sending array
read_temps(TempsAry);
//sending hot array
hot_days(TempsAry, hotAry);
getch();
return 0;
}
void read_temps(int TempsAry [])
{
// variables
int tempnum ;
int x = 0 ;
int icount = 0;
while (x < 31)
{
// entering temperature
printf("Please enter today's temperature:\n ");
scanf("%d",&tempnum);
if (tempnum <= -500)
{
break;
}
TempsAry[x] = tempnum;
++x;
icount = icount +1;
}
//outputting array
for (x = 0 ; x<icount; ++x)
{
printf("%d\n",TempsAry[x]);
}
}
void hot_days(int TempsAry [], int hotAry [])
{
int x = 0 ;
int icount = 0;
while (x<31)
{
if (TempsAry[x] > HIGH)
{
hotAry[x] = TempsAry[x];
++icount;
}
++x;
}
printf("%d\n", icount);
}

There is nothing wrong in this code, its working properly. checkout the snippet at ideone.

while (x < 31)
{
// entering temperature
printf("Please enter today's temperature:\n ");
scanf("%d",&tempnum);
if (tempnum <= -500)
{
break;
}
here the loop breaks if you enter temprature <=-500. So if you entered value satisfying this condition as i'th temperature then the array temp_array[] will have garbage values after temp_array[i] since they will not be assigned value. This can result in your program to give random icount.
So make those remaining temp_array[] values 0.

You have a Sight issue with your code, If you're entering numbers less than 31, because the memory allocated for the array TempsAry[] contain raw values .So in function
void hot_days(int TempsAry [], int hotAry [])
the while loop
while (x<31)
{
if (TempsAry[x] > HIGH)
{
hotAry[x] = TempsAry[x];
++icount;
}
++x;
}
compares up to 31 elements even if the number of elements is less than 31, So this also includes the garbage values in the uninitialized memory, so the result obtained will be wrong
This can be eliminated by initializing the memory allocated for TempsAry to 0 in the main() function
int TempsAry[31];
int hotAry[31];
memset(TempsAry,0x00,sizeof(TempsAry));

You have uninitialized values in TempsAry. You are getting undefined behavior.
Change the line
int TempsAry[31];
to
int TempsAry[31] = {0};
which is equivalent to initializing with TempsAry with 31 comma separated zeros. More on that can be found at How to initialize an array in C

Related

How to compare user input to an array, checking to see if its less that last input

I have to request user input for 10 different numbers. I have to see if the user input is less than the last number entered (which was added to an array). I'm having trouble comparing it, as my logic seems sound but for whatever reason it wont keep lower numbers inputted earlier in the loop. Maybe you guys can take a look and see where the issue lies in my if statement. The getNum() function just gets user input and returns it if your curious. Thanks in advance!
#include <stdio.h> //including for the use of printf
/* == FUNCTION PROTOTYPES == */
int getNum(void);
/* === COMPILER DIRECTIVE - to ignore the sscanf() warning === */
#pragma warning(disable: 4996)
int main(void)
{
// defining varibles
int myArray[11] = { 0 };
int counter = 0;
int indexTracker = -1;
int numInput = 0;
int lowestNum = 0;
int lowestNumPlace = 0;
// printing as to why I need 10 numbers
printf("I require a list of 10 numbers to save the world!\n");
// while loop
// while 'counter' is less than or equal to 9, loop
while (counter <= 9)
{
// adding 1 to each varible, everytime the program loops
indexTracker += 1;
counter += 1;
// printing to request a number, giving which number they are
// inputting
// out of the list of 10
// calling getNum() for input, saving the number into the array
printf("Please enter a number for #%d: ", counter, "spot\n");
numInput = getNum();
myArray[indexTracker] = numInput;
if (numInput <= myArray[indexTracker])
{
lowestNum = numInput;
lowestNumPlace = indexTracker;
}
}
// printing the lowest value and its index
printf("The lowest number is: %d at index [%d].", lowestNum,
lowestNumPlace);
return 0;
}
You're always assigning a new value to lowestNum
numInput = getNum();
myArray[indexTracker] = numInput;
if (numInput <= myArray[indexTracker])
{
lowestNum = numInput;
lowestNumPlace = indexTracker;
}
... because after doing A=B, B<=A will logically always be true.
Try this instead:
numInput = getNum();
myArray[indexTracker] = numInput;
if (numInput <= lowestNum) // note, comparing to the lowest number, not the current one
{
lowestNum = numInput;
lowestNumPlace = indexTracker;
}

Understanding returning values functions C

I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}

Checking array for identical numbers and their value

As part of a program that I have to make, one of the function that I need to program should check if the array has any identical numbers that are the same, and if one of them is bigger/equals to a given number.
The given number is also the amount of numbers in the array
This is what I have so far:
int checkarray(int *arr, int num)
{
int check = num;
int check2 = num;
int *lor;
int *poi;
int *another;
another = arr;
lor = arr;
poi = arr;
int check3 = num;
for ( ; num > 1; num--) {
for ( ; check3 >= 0; check3--) {
if (*arr == *poi)
return 0;
poi++;
}
arr++;
poi = another;
}
for ( ; check2 > 0; check2--) {
if (*lor >= check)
return 0;
lor++;
}
return 1;
}
I know that I made too many pointers/int for the function, but that's not the problem..
The part of checking for a given value works fine if I'm not mistaken so I think you can ignore that part (that's the last 'for' loop)
I know it should be easy but for some reason I just can't get it to work...
Edit:
I'll give an example: If the array is 0 1 2 3 1 the function will return 0, cause the second and the last number are identical. The function will also return 0 if the given number is 5, and one of the numbers is bigger or equals to 5, for example 0 1 2 5 4.
Otherwise, the function returns 1.
I create a new array where I'm going to save the numbers so I can check if you have a repeat number in the array. I also have one more argument in the function to know the size of the array.
#include <stdio.h>
#include <stdlib.h>
int checkArray(int *arr, int size, int number){
int i,j;
int *countArray = calloc(size,sizeof(int));
for(i=0;i<size;i++){
if(arr[i]>=number){ //Check >= number
free(countArray);
return 0;
}
for(j=0;j<i;j++){ //Check repeat number
if(countArray[j]==arr[i]){
free(countArray);
return 0;
}
}
countArray[j]=arr[i]; //no repeat number so we save it.
}
free(countArray);
return -1; //Error
}
int main(){
int arr[6] = {0,8,2,3,4,1};
printf("Result %d",checkArray(arr,6,5));
}
I hope this can help you.
Update without new array
int checkArray(int *arr, int size, int number){
int i,j;
for(i=0;i<size;i++){
if(arr[i]>=number){
return 0;
}
for(j=0;j<i;j++){
if(arr[i]==arr[j]){
return 0;
}
}
}
return -1; //Error
}
Change your upper for loop to:
for ( ; num > 0; num--) {
if(arr[i]>=number){
return 0;
}
int check3 = num;
poi=arr+1;
for ( ; check3 > 0; check3--) {
if (*arr == *poi)
return 0;
poi++;
}
arr++;
}
and remove the bottom one.
The mistakes here are as following:
1- You need to change the lines:
int check3 = num;
for ( ; num > 1; num--) {
to be:
for ( ; num > 1; num --) {
int check3 = check; // Move to inside loop to reset each time for a fresh inner loop and use check instead of num to reset the value
2- You need to change the line:
for ( ; check3 >= 0; check3--) {
To be
for ( ; check3 > 0; check3--) { // Because `>=0` means attempting to read past the array
3- poi should be initialised every time in the loop as arr+1 to skip comparing the same member of the array to itself, and to skip re-comparing members more than one time.
I suggest re-writing the method with better code style to enable easier detection of such errors and typos

Find character frequency in a string

Im trying to find character frequency in a string,i wrote the following code,but it does'nt show any output.All im trying is to fill the character array with respective counts.
When i tried to debug,it some how gives output,but prints some garbage value.
#include<stdio.h>
/* Program for printing character frequency in string */
charcount(char *,int *);
int main()
{
int n,i=0;
printf("Enter n :");
scanf("%d",&n);
char var[n];
int count[100]; // array for storing character frequency
printf("Enter string :");
fflush(stdin);
scanf("%s",var);
charcount(var,count); // calling frequeny function
for(i=0;i<strlen(count);i++)
{
printf("%d\n",count[i]);
}
getch();
return 0;
}
charcount(char *p,int *q)
{
for(;*p;p++)
{
q[*p]++;
}
}
You have few problems in your code:
count array is not initialized.
You are applying strlen() on an integer array.
count array should be 256 (count[256]) to cover all possible ascii chars. For example, if your input is abcd you'll go out of bound of array as d is 100.
You are printing the wrong count:
printf("%d\n",count[i]); should be printf("%d\n",count[var[i]]);
Declare proper prototype for charcount().
After fixing these:
#include<stdio.h>
/* Program for printing character frequency in string */
void charcount(char *,int *);
int main()
{
int n,i=0;
printf("Enter n :");
scanf("%d",&n);
char var[n];
int count[256]={0}; // array for storing character frequency
printf("Enter string :");
scanf("%s",var);
charcount(var,count); // calling frequeny function
for(i=0;i<strlen(var);i++)
{
printf("%d\n",count[var[i]]);
}
return 0;
}
void charcount(char *p,int *q)
{
for(;*p;p++)
{
q[*p]++;
}
}
Make sure to compile in C99 or C11 (e.g. gcc -std=c99 file.c) mode as VLAs are not supported in earlier standards of C.
You need to initialize your count array. Otherwise it will have garbage values in it by default. You can initialize the whole array to 0 like so:
int count[100] = {0};
Your count array may not be large enough to hold all printable values (even assuming ASCII), and it should be 0 initialized. Your for loop should be checking against the length of var, not count, since you cannot sensibly treat the count integer array as a string.
int count[1<<CHAR_BIT] = {};
/*...*/
for(i=0;i<strlen(var);i++)
{
printf("%d\n",count[var[i]]);
}
Well, it really depends on what you want to output. If you intend to output all of count, then:
for(i=0;i<sizeof(count)/sizeof(count[0]);i++)
{
printf("%d\n",count[i]);
}
int count is nothing but a hashmap
Your code will not work for this string "abcd"
count['a'] = val // Works fine ASCII value of a is 97
count['b'] = val // Works fine ASCII value of a is 98
count['c'] = val // Works fine ASCII value of a is 99
count['d'] = val ; // Undefined Behaviour ASCII value of d is 100
The size should be equal to ASCII set length
int count[128] = {};
JAVA program to print "*" as much times as the occurrence of a character in String.
Or char_in_String : frequency of char_in_String
Instead of * you can print frequency count
public class CharFreq
{
public static void main(String[] args)
{
String s = "be yourself "; System.out.println(s);
int r=0;
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++)
{
int cnt = 0;
if (str[i] != ' ')
{
for (int j = 0; j < str.length; j++)
{
if (str[i] == str[j])
{
cnt++; r=j;
}
}
if(i==r)
{
System.out.print(str[i] + ":");
for (int k = 1; k <=cnt; k++)
System.out.print("*");
System.out.println();
}
}
}
}
}
Output:
be yourself
b:*
y:*
o:*
u:*
r:*
s:*
e:**
l:*
f:*
Your count[100] is not large enough. Assume you only enter "A - Z" or "a - z" it's still not large enough because 'z' is 122, then your charcount will increase count[122].
You should consider change int count[100] to int count[128] = { 0 }

Binary operation, need help

I am about to create a function for a program, this is part of a program and is meant to be a bitmap that holds controls of which memory address is free for use (this has nothing to do with this function to do). The bitmap is bit[64] which holds 8 x 64 bits, the function under is taking a parameter number that is the number of data blocks the function should occupy. In array data_blocks[] should the number to the data block that has bit value 0(free).
Execution of this program gives some strange outputs, and data_blocks[] gives values beyond the length of 512. Can someone please give me a hand? Thanks
#include <stdio.h>
#include <string.h>
void occupyDataBlocks(int number)
{
int ab = number;
char bit[512/8];
int bitNum = 0;
int count;
int data_blocks[ab];
int b;
for(bitNum = 0; bitNum < (sizeof(bit)/sizeof(char)); bitNum++) {
char x = bit[bitNum];
for(count = 0; x != 0; x >>= 1 ) {
if(!(x & 0)) {
data_blocks[count] = count;
}
if(count == number) {
break;
}
count++;
}
if(count == number) {
break;
}
}
if(count == number) {
int a;
for(a = 0; a < 5; a++) {
printf("%d\n", data_blocks[a]);
}
} else {
printf("Not enough data blocks\n");
}
}
int main(void)
{
occupyDataBlocks(3);
return 1;
}
k, where to start ...
1) "sizeof(char)" is most likely 1. So you have a 512-byte array, not a 64-byte array.
2) "bit" array is not initialized.
3) the assignment "char x = bit[bitNum]; " should occur inside the loop.
4) "strlen(bit)" does not do what you think it does. It interprets "bit" as a text string. You probably want do use "sizeof(bit)/sizeof(char)".
5) "(x & 0)" always evaluates to 0. What are you trying to do? If you're trying to test the bit, you want to do "!(x & 1)".
6) "int data_blocks[number]": does this even compile? You can't allocate a local array like that if its size is not known at compile time.
7) if(count == number) {
break;
}
only breaks you out of the inner loop. The outer loop continues on uninterrupted.
8) Do you really want to reset "count" to 0 every iteration of the outer loop? Do you want the code to find 3 free locations somewhere in the array, or 3 free locations in a single byte?

Resources