All Integers have the same value - c

So I am working on some homework, in which I have to create a global array of 500 random integers between 0 and 99. Then, I have to count how many are greater than 75, and how many are less than 50.
Here is my code:
#include <stdlib.h>
#include <stdio.h>
static int ARRAY[500];
static char str[1];
void main() {
int i = 0;
for (i = 0; i < 500; i++) {
int r = rand() % 99;
ARRAY[i] = r;
}
int gt75 = count75();
int lt50 = count50();
printf("%d\n", str, gt75);
printf("%d\n", str, lt50);
}
int count75() {
int i = 0, counter = 0;
for (i = 0; i < 500; i++) {
int n = ARRAY[i];
if (n > 75) {
counter += 1;
}
}
return counter;
}
int count50() {
int i = 0, counter = 0;
for (i = 0; i < 500; i ++) {
int n = ARRAY[i];
if (n < 50) {
counter += 1;
}
}
return counter;
}
However, after compiling and running my program, I get the following output:
4225008
4225008
This can't be right, as the list should only have 500 elements in the first place. What am I doing wrong?

You have two errors.
First, int r = rand() % 99; should be int r = rand() % 100; Otherwise you just get numbers between 0 and 98.
Second, your printf statements are odd. They should be:
printf("Greater than 75: %d\n", gt75);
printf("Less than 50: %d\n", lt50);
In the current printf statements, the str is cast to an int, which is interpreting the str pointer as an int, thus your strange output.

You're printing a char array with printf using "%d", which is for printing integers. Use "%s" for printing char arrays:
printf("%s\n", str, gt75);
Or, if you're trying to print the value of gt75 as an integer:
printf("%d\n", gt75);
I do not know why you would pass str in this case, though.
When you use "%d", you are telling printf to interpret the input as an int. Since str is actually a char array, it does not output correctly. Instead, you're printing the memory location of str, which is the value of an array.

You are always printing the value of str, which is not an int.

Related

printing 2 characters and keeping them through dynamically allocated 2d array

Hello I am trying to print something like this with 2d array.
Note that when user enters the same number, character should be printed above existing char.
EXPECTED RESULTS:
Input 1: 3 //user1 inputs 3
****
****
**x*
Input 2: 1 //user2 inputs 1
****
****
y*x*
Input 3: 1 //user1 inputs 1
****
x***
y*x*
current results:
enter first: 3
3***
***
**x
enter second: 1
1******
******
xx****
enter first: 2
2*********
*********
***xxx***
But keeping printed values on its previous places.
The problem is that they don't get printed in right order. And also it seems that I haven't done the best job with 2d array which is dynamically allocated.
Here is something what I've tried:
#include <stdio.h>
#include <stdlib.h>
int num(int term)
{
int number1;
int number2;
if(term==1)
{
scanf("%d", &number1);
return number1;
}
if (term==2)
{
scanf("%d", &number2);
return number2;
}
return 0;
}
void function(int a, int b, int result[], int size)
{
int i = 0;
int j = 0;
int desired_num = 0;
int count = 0;
int *arr[a];
for (i = 0; i < a; i++)
arr[i] = (int *)malloc(a * sizeof(int));
for (i = 0; i < a; i++)
for (j = 0; j < b; j++)
arr[i][j] = ++count;
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
for (int counter = 0; counter < size; counter++)
{
if (arr[i][j] == arr[a - 1][result[counter] - 1])
{
arr[i][j] = desired_num;
}
if (arr[i][j] == desired_num)
{
printf("%s", "x");
}
else
{
printf("*");
}
}
}
printf("\n");
}
}
int main()
{
int counter = 1;
int i = 0;
int given_number;
int array[20];
for (;;)
{
if (counter % 2 != 0)
{
printf("enter first: ");
given_number = num(1);
printf("%d", given_number);
}
else
{
printf("enter second: ");
given_number = num(2);
printf("%d", given_number);
}
array[i] = given_number;
function(3, 3, array, counter);
counter++;
}
return 0;
}
array[i] = given_number;
i is never changed from the value of 0. You are only ever overwriting the first element of array each iteration. The other 19 elements remain in an indeterminate state.
counter and array are passed to function, as size and result respectively:
This means as size is incremented, it is used as a bounds for accessing elements of result; elements that contain indeterminate values.
for (int counter = 0; counter < size; counter++)
{
if (arr[i][j] == arr[a - 1][result[counter] - 1])
This will surely lead to Undefined Behaviour as those indeterminate values are used to index arr, effectively accessing random memory offsets. This fact alone makes it hard to reason about the output you are seeing, as really anything is valid.
While perfectly valid, the variable-length array of dynamic allocations is a somewhat perplexing choice, especially considering you fail to free the memory allocated by malloc when you are done with it.
int *arr[a];
for (i = 0; i < a; i++)
arr[i] = (int *)malloc(a * sizeof(int));
int arr[a][b]; would work, given a and b are not stack-crushingly large values (or non-positive). You are, or would be, bounded by the size of array in main anyway.
The triply nested loop is confused at best. There is only logic for printing the x and * characters, so you obviously will never see a y.
For each element of arr, you iterate through each element of result. If the current element of arr equals the value of the column selected by the current value of result ([result[counter] - 1]) in the last row (arr[a - 1]) you print x, otherwise *.
Again UB from utilizing indeterminate values of result, but you can see you are printing a * b * size characters, plus newlines, each iteration.
This is severely flawed.
Some other things of note:
The two branches of the if .. else statement in the num function do the exact same thing, just with different identifiers.
The two branches of the if .. else statement in main are identical, other than the first printf in each, and the integer value passed to num, which have the same effect.
This means the only thing that needs to branch is the printf argument.
A generic function for getting an integer would work fine
int get_num(void)
{
int n;
if (1 != scanf("%d", &n)) {
fprintf(stderr, "Could not read input.\n");
exit(EXIT_FAILURE);
}
return n;
}
for use inside main
if (counter % 2 == 0)
printf("enter first: ");
else
printf("enter second: ");
given_number = get_num();
A small issue: printf("%d", given_number); is muddling the output slightly.
There is no reason to repeatedly generate the array. Initialize an array in main to serve as the state of the program. Over time, fill it with the users' selections, and simply print the array each iteration.
Make sure to always check the return value of scanf is the expected number of conversions, and ensure the integers provided by the users will not access invalid memory.
Here is a cursory example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EMPTY '*'
#define PLAYER_ONE 'X'
#define PLAYER_TWO 'O'
int get_num(void)
{
int n;
if (1 != scanf("%d", &n)) {
fprintf(stderr, "Could not read input.\n");
exit(EXIT_FAILURE);
}
return n;
}
int main(void)
{
const size_t rows = 6;
const size_t cols = 7;
char board[rows][cols + 1];
memset(board, EMPTY, sizeof board);
/* our rows are now strings */
for (size_t i = 0; i < rows; i++) {
board[i][cols] = '\0';
puts(board[i]);
}
unsigned char turn = 1;
while (1) {
printf("Player %s, Enter column #(1-%zu): ",
turn & 1 ? "One" : "Two", rows);
int input = get_num();
if (1 > input || input > cols) {
printf("Invalid column [%d]. Try again...\n", input);
continue;
}
size_t sel = input - 1;
if (board[0][sel] != EMPTY) {
printf("Column [%d] is full! Try again...\n", input);
continue;
}
size_t n = rows;
while (n--) {
if (board[n][sel] == EMPTY) {
board[n][sel] = turn & 1 ? PLAYER_ONE : PLAYER_TWO;
break;
}
}
for (size_t i = 0; i < rows; i++)
puts(board[i]);
turn ^= 1
}
}

Length of array of strings

How can we determine the length of an array of strings when we don't know the length?
For example in this piece of code:
#include <stdio.h>
int main() {
int n;
char names[3][10] = { “Alex”, “Phillip”, “Collins” };
for (n = 0; n < 3; n++)
printf(“%s \n”, names[n]);
}
n < 3 is assuming you know the length of the array but how can you determine it's length when we don't know?
I have tried a few alternatives such as:
int arraySize() {
size_t size, i = 0;
int count = 0;
char names[3][10] = { “Alex”, “Phillip”, “Collins” };
size = sizeof(names) / sizeof(char*);
for (i = 0; i < size; i++) {
printf("%d - %s\n", count + 1, *(names + i));
count++;
}
printf("\n");
printf("The number of strings found are %d\n", count);
return 0;
}
or
for (n = 0; n < sizeof(names); n++)
but they all error out.
Any help is appreciated.
I am not sure what you mean by they all err out.
There is a syntax issue in the code posted as you use guillemet characters instead of double quotes: “Alex” should be "Alex". This could be a side effect of your cut/paste method to post the code, but nevertheless a potential issue.
Your approach using size = sizeof(names) / sizeof(char*); is right but the type is incorrect: names[0] is not a char *, it is an array of 10 characters. You should use size = sizeof(names) / sizeof(names[0]); which works for all arrays, regardless of the type.
Here is a modified version where the length of the array is determined by the compiler:
#include <stdio.h>
int main() {
char names[][10] = { "Alex", "Phillip", "Collins" };
int i, length = sizeof(names) / sizeof(names[0]);
for (i = 0; i < length; i++)
printf("%d: %s\n", i + 1, names[i]);
return 0;
}
Notes:
you could use size_t instead of int for array length and index variables, but it is only necessary for very large arrays and the printf conversion specifier would be %zu for a value of type size_t.
it is less confusing to use length for the length of an array and reserve size for sizes in bytes obtained from sizeof().
first every string is ended with a special character '\0'
means
{'A','L','E','X','\0'}
even you haven't put '\0' there but compiler put it there for it convenient
int lenght(char *str){
int count = 0 ;
for(int i=0;str[i]!='\0';i++){
count++ ;
}
return count ;
}
use this function to count your string length
like :
int main(){
char names[3][10] = {"Alex", "Phillip", "Collins"};
printf(“%d \n”,lenght(names[1] );
return 0 ;
}

Why are only the first 2 outputs correct in my binary to decimal converter programm?

I have to program a converter which takes the strings from numbers[] and outputs them as decimals.
I am looping through size and index to then add up the current index to the power of its position and then sum it all up. Like: 101 = 1^2 + 0^1 + 1^0
So I am currently stuck with this:
#include <stdio.h>
#include <math.h> // Kompilieren mit -lm : gcc -Wall -std=c11 dateiname.c -lm
int main() {
char* numbers[] = {
"01001001",
"00101010",
"010100111001",
"011111110100101010010111",
"0001010110011010101111101111010101110110",
"01011100110000001101"};
// Add here..
int strlen(char *str){
int len=0;
for(;str[len]!='\0';len++){}
return len;
}
int sum = 0;
int length = sizeof(numbers) / sizeof(numbers[0]);
for( int i = 0; i < length; i++ ){
int size = strlen(numbers[i]);
for (int j = 0; j < size; j++) {
if(numbers[i][j] == '1'){
sum += 1 * pow(2,j-1);
}else{
sum += 0 * pow(2,j-1);
}
}
printf("%s to the base of 2 \nequals %d to the base of 10 \n\n",numbers[i], sum);
sum = 0;
}
return 0;
}
The output of the first two loops is correct which is 01001001 = 73 and 00101010 = 42. But, as soon the length get bigger, my output is completely wrong; e.g. 010100111001 = 1253 instead of 1337 and 011111110100101010010111 = 7645567 instead of 8342167.
There are a number of issues with your code. First and foremost, as pointed out in the comments, you are processing your binary digits from left-to-right, whereas you should be doing that right-to-left.
Second, declaring a function inside another one (as you have done for your strlen) is not Standard C (though some compilers may allow it). If you really can't use the standard strlen function (provided in <string.h>), then move your definition to outside (and before) the body of main.
Third, you shouldn't be using the pow function (which takes and returns double values) for integer arithmetic. Just use a running int variable and multiply that by two each time the inner for loop runs.
Fourth, your "0001010110011010101111101111010101110110" value will overflow the int type on most machines (assuming that is 32 bits), so try using long long int (most likely 64 bits) where necessary.
Finally, there's no point in adding 0 * x to anything, whatever x is, so you can do away with the else block.
Here's a working version (using the standard strlen):
#include <stdio.h>
#include <string.h> // For "strlen" - we don't need math.h if we don't use "pow".
int main(void) // For strict compliance, you should add the "void" argument list
{
char* numbers[] = {
"01001001",
"00101010",
"010100111001",
"011111110100101010010111",
"0001010110011010101111101111010101110110",
"01011100110000001101" };
long long int sum = 0; // So we can use more than 32 bits!
size_t length = sizeof(numbers) / sizeof(numbers[0]);
for (size_t i = 0; i < length; i++) {
int size = (int)strlen(numbers[i]); // strlen gives a "size_t" type
long long int p = 1;
for (int j = size-1; j >= 0; j--) { // Start at the END of the string and work backwards!
if (numbers[i][j] == '1') {
sum += p;
}
// No point in adding zero times anything!
p *= 2; // Times by two each time through the loop
}
printf("%s to the base of 2 \nequals %lld to the base of 10 \n\n", numbers[i], sum);
sum = 0;
}
return 0;
}
sizeof(); // it will give you the size of datatype (in bytes), not the length of a string.
You have to use string function instead.
length = strlen(numbers[0]);
Your function is quite bad, complicated and uses pow. You do not need to know the length of the string.
It can be done much easier:
unsigned long long bstrtoint(const char *str)
{
unsigned long long result = 0;
while(*str)
{
result *= 2;
result += *str++ == '1';
}
return result;
}
or for any base (lower than number of digits)
//bad digits considered as zeroes
static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUWXYZ";
unsigned long long strtoint(const char *str, unsigned base)
{
unsigned long long result = 0;
char *ppos;
while(*str)
{
result *= base;
result += (ppos = strchr(digits, toupper(*str++))) ? (ppos - digits < base) ? ppos - digits : 0 : 0;
}
return result;
}
Examples:
printf("%llu\n", bstrtoint("1111000011110000"));
printf("%llu\n", strtoint("0001010110011010101111101111010101110110", 2));
printf("%llu\n", strtoint("1dr45Xvy4", 36)); // base 36 number
https://godbolt.org/z/bsG5rfTsb
If you want to use your program layout and do it correctly:
int main(void) // For strict compliance, you should add the "void" argument list
{
char* numbers[] = {
"01001001",
"00101010",
"010100111001",
"011111110100101010010111",
"0001010110011010101111101111010101110110",
"01011100110000001101" };
unsigned long long sum = 0;
size_t length = sizeof(numbers) / sizeof(numbers[0]);
for (size_t i = 0; i < length; i++)
{
size_t size = strlen(numbers[i]); // strlen gives a "size_t" type
sum = 0;
for (size_t j = 0; j < size; j++)
{
sum *= 2;
if (numbers[i][j] == '1')
{
sum += 1;
}
}
printf("%s to the base of 2 \nequals %llu to the base of 10 \n\n", numbers[i], sum);
}
return 0;
}
but you do not have to integrate your string twice - strlen is not needed at all
int main(void) // For strict compliance, you should add the "void" argument list
{
char* numbers[] = {
"01001001",
"00101010",
"010100111001",
"011111110100101010010111",
"0001010110011010101111101111010101110110",
"01011100110000001101" };
unsigned long long sum = 0;
size_t length = sizeof(numbers) / sizeof(numbers[0]);
for (size_t i = 0; i < length; i++)
{
sum = 0;
for (size_t j = 0; numbers[i][j] != 0; j++)
{
sum *= 2;
if (numbers[i][j] == '1')
{
sum += 1;
}
}
printf("%s to the base of 2 \nequals %llu to the base of 10 \n\n", numbers[i], sum);
}
return 0;
}

Implement a reverse function to reverse an integer but the output here is always 0

I do not understand why the return .... does not work. Somehow, Output is always 0. Here the return call to atoi always outputs 0.
#include <stdio.h> //INCLUDES
#include <stdlib.h>
int reverse (int x); //Func Decls
int
main ()
{
printf ("%d", reverse (123)); //123=321, -123=-321, 120=21, 0=0
return 0;
}
int
reverse (int x)
{
int i, rem = 0;
char arr[15];
while (x % 10 != 0)
{
rem = x % 10;
arr[i] = ((char)rem);
x /= 10;
i++;
}
return atoi(arr); //OUTPUT = 0, does not return actual output
}
You don't need an array nor atoi function for this task, and the logic of while loop is not correct. A correct and simple one could be something like that (provided that no integer overflow occurs):
#include <stdio.h>
int reverse (int x)
{
int r = 0;
while (x != 0) {
r = 10 * r + x % 10;
x /= 10;
}
return r;
}
int main (void)
{
printf("%d\n", reverse(1234));
return 0;
}
The problem is the usage of atoi() function. The atoi() function basically converts a string with numeric characters codified in ASCII to an integer.
If you look the ASCII table, the numbers 1, 2 and 3 codify the characters '^A', '^B' and '^C', respectively. This means that, after the while loop in reverse() function, the string passed as argument to atoi() is not a numeric string, so zero is returned as an error. Also, the characters '1', '2' and '3' are codified as numbers 49, 50 and 51, respectively.
Now, I suggest you to change your entire implementation, because it does not make sense to receive an integer as input to operate with and, during the operation, convert it to string to return an integer again using atoi(). So, forget strings, ASCII, and atoi().
Lets start creating a loop to operate with each digit of the number, using the module operator, as you did.
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = x%10;
}
return result;
}
Then, to insert another digit to the result, do the opposite: multiply it by 10.
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = result*10 + x%10;
}
return result;
}
Now, cut the target digit out of the x, dividing it by ten.
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = result*10 + x%10;
x /= 10;
}
return result;
}
Finally, the entire code.
#include <stdio.h>
#include <stdlib.h>
int reverse (int x);
int main () {
printf ("%d\n", reverse(123));
printf ("%d\n", reverse(-123));
printf ("%d\n", reverse(120));
printf ("%d\n", reverse(0));
return 0;
}
int reverse (int x) {
int result = 0;
while ( x != 0 ) {
result = result*10 + x%10;
x /= 10;
}
return result;
}
And the result, as expected:
$ gcc -Wall -std=c99 -o program program.c
$ ./program
321
-321
21
0
$
Based on your code, you can fix your code a little bit to make it works. Below is my opinion:
#include <stdio.h> //INCLUDES
#include <stdlib.h>
int reverse (int x); //Func Decls
int main () {
printf ("%d", reverse (123)); //123=321, -123=-321, 120=21, 0=0
return 0;
}
int reverse (int x) {
int i, rem = 0;
int arr[15];
while (x != 0)
{
rem = x % 10;
arr[i] = rem;
x /= 10;
i++;
}
int result = 0;
for (int j = 0; j < i; j++) {
result = 10 * result + arr[j];
}
return result;
}
regarding:
int i, rem = 0;
and
arr[i] = ((char)rem);
the local variable i in not initialized!. on my system the result is a seg fault event.

learning the basics of C programming which can clear my doubts on arrays and strings

I am new to C so this question may seem a bit stupid :P .
I have an array arr[] which stores numbers from 100 to 999.
Now, I have to take each element of the array and subtract the subsequent digits.
For example if I have a number in that array as 1234 then I need another array that stores 1,2,3,4 distinctly so that I can perform 1-2= -1, 2-3 =-1, 3-4= -1.
So if I change a data like 1234 to char through typecasting then how to store this char into an array and then break it into 1,2,3,4 so that I can call it in a for loop by arr[i].
#include <stdio.h>
#include<string.h>
int main()
{
int t,n,w;
int mod = 1000007;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&w);
int start = 1;
int end = 10;
int i,j,z;
for(i=0;i<=n-2;i++)
{
start = start*10;
end = end*100;
}
end--;
char arr[10000];
for(i= start;i<=end;i++)
{
scanf("%c",&arr[i]);
}
int len = strlen(arr);
int count = 0;
int Value=0;
for(i=0;i<len;i++)
{
char b[10000];
b[0] = arr[i] + '0';
char arr2[10000];
int g = strlen(b);
for(j=0;j<g;j++)
{
strncpy(arr2, b + j, j+1);
}
int k = strlen(arr2);
for(z=0;z<k;z++)
{
int u = arr2[z] - '0';
int V = arr2[z+1] - '0';
if(u>V)
{
Value = Value + (u-V);
}
else
{
Value = Value + (V-u);
}
}
if (Value == w)
{
count++;
}
}
int ans = count % mod;
printf("%d",ans);
}
return 0;
}
Actually its a question from codechef.com called weight of numbers in the easy section of the practice problems
you can split number by digits in this way
int num = 123;
int digits[3];
for (int i = 2; i >= 0; i--)
{
digits[i] = num % 10;
num /= 10;
}
Also if you'll cast num to char that wouldn't help you. You'll just get some character if you try to print it. Nothing more will change.

Resources