What am I doing wrong (C arrays)? - c

I'm just a beginner at C.
I'm trying to make a simple program to arrange the user-entered digits in ascending order. I have figured out the solution but can't understand why my other code wouldn't work :(
-------------------------------------------------------------------------
working code:
-------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,j,num[10];
printf("Enter 10 numbers\n");
for (i=0;i<10;i++)
{scanf("%d",&num[i]);}
for (i=0;i<9;i++)
{
for (j=i+1;j<10;j++)
{
if (num[i]>num[j])
{
num[i]+=num[j];
num[j]=num[i]-num[j];
num[i]=num[i]-num[j];
}
}
}
printf("The numbers in ascending order are:");
for (i=0;i<10;i++)
{
printf(" %d",num[i]);
}
return 0;
}
-------------------------------------------------------------------------
code that won't work:
-------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,j,num[10];
printf("Enter 10 numbers\n");
for (i=1;i<=10;i++)
{scanf("%d",&num[i]);}
for (i=1;i<10;i++)
{
for (j=i+1;j<=10;j++)
{
if (num[i]>num[j])
{
num[i]+=num[j];
num[j]=num[i]-num[j];
num[i]=num[i]-num[j];
}
}
}
printf("The numbers in ascending order are:");
for (i=1;i<=10;i++)
{
printf(" %d",num[i]);
}
return 0;
}
In the latter program, numbers appear out of order, and there even are numbers that haven't been entered.
My question is, isn't it basically the same code? Just that in the latter program numbers would be stored from num[1] to num[10] instead of num[0] through num[9]?
Does it have something to do with array definitions?
It seems I have serious misconceptions, please help me out!

In C, when you have int num[10];, your indexes need to go from 0 to 9, never to 10. So look over your code, if any i or j ends up with a value of 10 any time during the program run, that's bad news.

Indexes in C go start from 0. so when you declare an array of size 10, and you try to get element at index 10, you're actually getting the 11th element. Since you haven't defined the 11th element, the array will most likely get some random numbers from memory, which is why you are noticing numbers you have note entered.
Since you are new to programming, I would suggest taking the time now to really learn about how C manages memory, and how different data structures access the memory. It might be a little boring now, but you'll save yourself some headaches in the future, and you will start to build good habits and good practices, which will lead to writing good, optimal code

for(i=0;i<9;i++) //**i<9**
for (j=i+1 ...)
If i=8 then j=9 , everything is OK.
In second code snippet:
for(i=0;i<10;i++) //**i<10**
for (j=i+1 ...)
If i=9 then j=10, so you try to access num[10] and it gives you error.
If you want to access num[10] then you must declare array int num[11] and then you can access num[10].
Array Basics
int num[10]
Capacity of array = 10
Every element of this array are integer.
First element index is 0. So If you want to access first element , num[0]
Last element index is 9. So If you want to access last element, index must be length of array - 1 , so num[9]
There are 10 elements in the array and they are :
num[0] , num[1] , num[2] , num[3] , num[4] , num[5] , num[6] , num[7] , num[8] and num[9]
You can learn further at http://www.cplusplus.com/doc/tutorial/arrays/

In your non-working example, you have invalid memory accesses. For example, when i = 9 and j = 10, you access num[10], which is invalid memory.

Welcome to programming! I believe you are a bit confused about how arrays are indexed in C.
Arrays in most languages (including C) are known as zero-indexed arrays. This means the start of an array is always at position 0. So if you make int num[10], trying to access num[10] isn't actually a valid call at all, because the start is num[0]. Hence you can only access from num[0] to num[9].
It's an easy mistake to make, even though I've been programming for years sometimes when it's been a long night I'll still make silly array indexing issues.

In your other code example, you were doing this:
int num[10];
for(int i = 1; i <= 10; i++) {
//...
}
That means you have an array with ten spaces [0-9], and for the last part of your for loop, you were trying to access num[10] which doesn't exist.
Your working example goes from 0-9 and never tries to read num[10], so it works.
Arrays in C, as in most languages, start with position 0 and count that as position one. So the last element of your array would be the size you entered when you declared the variable, minus one.

Related

digit to integer in same order C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a function called fun(int num, int * array); which takes an int and int array as its arugments. I'm trying to convert int to the array.
When i run the program i don't get the array displayed properly
int fun(int num, int*array) {
int count =0;
while(num>0) {
num/= 10;
count++;
}
array[count];
// for loop works
}
When i print the array in the program i.e. everytime I run the program i get random digits.
What this line is supposed to do ?
array[count];
Since your integer array will change in your fun function, you have to allocate the memory (by using malloc, realloc, ...).
edit : plus, you already change the value hold by "num" when you count how many digit there are in "num".
Make a copy of "num" !
edit 2 : the more i look your function, the more it seem you will have problem using it.
Fisrt, you want to explode your integer into an array of int.
Okay, but integer have range, thus meaning integer have a maximum digit.
From my memories, there are 20 digit in an 64bit integer.
So you can simply use "int array[NB_DIGIT_INT_MAX];" with "#define NB_DIGIT_INT_MAX 21".
So, allocating is not necessary AND add complexity in your code (the caller will have to free after the function call).
Second, your fun function doesn't say how many case will hold your integer.
Let's say num = 12, your array will have "array[0] = 1, array[1] = 2", but how do you know where to stop ?
If num = 2345, how do you know that only the 4 first case in your array is legit ?
There are 2 way : You have an another variable that hold the actual size of the array, or you have a special value in your array that say "it's the end" (like '\0' for char array used as string).
You can use "-1".
Let's give a try, and don't hesitate to ask question if thing are unclear (english is not my motherlanguage)
Your array is not even allocated, this can not work as expected. You are even lucky not to have a segmentation fault. If you want to add an integer to an array making it grow, you need to allocate a larger array, copy the values and add the new one to the new array and delete the previous array, keeping array variable as a pointer to the new array. Moreover, you need to pass the size of the actual array as an argument of fun.
The count variable can be global, Initialize it outside all functions like this
short count;
The whole program could be modified like below
#include<stdio.h>
#include<stdlib.h>
short count;
void fun(int num, int **ptr) {
// You need a pointer to a pointer and return type can be void
int num_copy=num;
count=0; // Setting the count to zero
while(num_copy>0) {
num_copy/= 10; // Don't modify the original number
count++;
}
//Allocate enough memory to store the digits
*ptr=malloc(count*sizeof **ptr);
if(NULL==*ptr){
perror("Can't allocate memory");
exit(1);
}
// Then do the loop part with original num
for(int i=count -1; i>=0; i--) {
(*ptr)[i] = num%10;
num /= 10;
}
// By now you have an array 'array' of integers which you could print in main.
}
int main()
{
int number = 123456789;
int *array;
fun(number,&array); // &array is of type pointer to a pointer to integers
//Now print the individual digits
printf("Individual digits are : \n");
for(int i=count-1;i>=0;i--)
printf("%d\n",array[i]);
}
Looks to me like you are converting from an integer to digits. But I don't see where your code writes anything to the array.
If the array wasn't initialized before this, that would explain why it still contains random values.

Array printing strange numbers

guys... I am kinda new in programming, so I would ask you this : I ´ve made program for user that would like to write down position of something. I assume , that this should be done using array. It looks like this :
#include <stdio.h>
int main()
{
int positionA[1][1];
int i;
int j;
printf("Insert postitions x and y : \n");
for ( i=0;i<2;i--)
{scanf("%d", &i);
for ( j=0;j<2;j--)
{
scanf("%d", &j);
}
printf("%d", positionA[i][j]);
}
return 0;
}
Please, dont be mad on me ,if I have this program made bad.
Well and problem is, that I insert numbers like 2,5 . And at the output it appears like 1695956464 .
Sorry for bad English :P. And thanks for help !
int positionA[1][1];
Declares a 1-by-1 array. That is, positionA[0][0] is its only element. You later address positionA[1][1], which is outside its bounds. In C, an array with a size of, say, 10, allows indexes from 0 to 9 (that's 10 elements, starting with zero).
Also, NEVER mess with your loop variables inside the loop:
scanf("%d", &j);
assigns the input value to the variable j, which is your loop index, causing you to loop unknown number of times, and access the array way out of bounds.

Print the number that appears the maximum number of times in the sequence

Recently I have gone through a problem like this
Write a program to read a sequence of N integers and print the number that
appears the maximum number of times in the sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range [-100,100]
I have writen the following code:
main()
{int arr[201],max=0,maxelement,n,i,num;
int t;
scanf("%d",&n);
int *storenum=(int *)malloc(sizeof(int)*n);
for(i=0;i<201;i++)
{
arr[i]=0;
}
for(i=0;i<n;i++)
{
scanf("%d",&num);
storenum[i]=num;
if(num<=100 && num>=-100)
{
arr[num+100]=arr[num+100]+1;
}
}
for(i=0;i<n;i++)
{
int t=storenum[i]+100;
if(arr[t]>max)
{ maxelement=storenum[i];
max=arr[t];}
}
printf("\n\n%d",maxelement);
getch();
}
Now I think this code is not optimized one...I want to have a solution that would have less time and space complexity and better solution.
You don't have to iterate through all N items a second time, just iterate through the 201 counts looking for the largest.
Your code looks very close to optimal. It can be made only a little better given your constraints.
Use memset when you mean memset. Yes the compiler will pick it up 99% of the time, but why bother?
for(i=0;i<201;i++) arr[i]=0; // becomes
memset(arr, '\0', sizeof(arr))
The count for any given item can be no larger than 10000. That means it can be held in a ushort!
int arr[201]; // becomes
uint16_t arr[201];
Your second loop should go from for(i = -100; i <= 100; i++) instead, and just loop over arr.
Your code is butt-ugly. Use a consistent indentation, brace style, and don't cram 50 declarations on the same line. Spaces are okay between elements. arr should probably be named something meaningful, I like counts. It kind of looks like you're trying to use gnu style C, but K&R works too, really just pick any style guide and glance through it.

Finding all possible words from inputted phone number [duplicate]

This question already has answers here:
Generating all Possible Combinations
(12 answers)
Closed 9 years ago.
I have a problem that I need some help in figuring out. I was hoping I could get a few pointers on a better way to approach what i'm doing. My main issue is a few lines below (//This is whats hanging me up) and described at the bottom of page.
I need to permutate all possible outcomes of a phone number: (not just dictionary words)
I.E. 222-2222
Should output a list 3^7 long with all the possible permutations of a,b,c
I.E.
AAAAAAA
AAAAAAB
AAAAAAC
AAAAABA // THIS IS WHATS HANGING ME UP
AAAAABB
AAAAABC
AAAAACA // HERE TOO AND SO ON
MY CODE (purposely shortened for testing) GIVES ME:
AAAA
AAAB
AAAC
AABC
AACC
ABCC
ACCC
BCCC
CCCC
I'm a beginning programming student so my knowledge goes as far as using for, while, if, statements and grabbing individual chars from the array.
Here's what my code looks like so far: (this is a part of a function. Code missing)
char alphaFunc(char n[]){
int d1=n[0]-48;
int d2=n[1]-48;
int d3=n[2]-48;
int d4=n[3]-48;
int d5=n[4]-48;
int d6=n[5]-48;
int d7=n[6]-48;
int a=0,b=0,c=0,d=0,e=0,f=0,g=0;
int i=0;
char charArray[10][4]={ {'0','0','0'},{'1','1','1'},{'A','B','C'},
{'D','E','F'},{'G','H','I'},{'J','K','L'},{'M','N','O'},
{'P','R','S'},{'T','U','V'},{'W','X','Y'} };
while(i <=14){
printf("%c%c%c%c\n", charArray[d1][a],
charArray[d2][b],charArray[d3][c],charArray[d4][d],
charArray[d5][e],charArray[d6][f],charArray[d7][g]);
g++;
if(g==3){
g=2;
f++;
}
if(f==3){
f=2;
e++;
}
if(e==3){
e=2;
d++;
}
I'm not exactly looking for someone to do this for me I just need a little help in figuring out which sort of statement will work b/c when you have a digit get to CharArray[d-][a] location [3] and reset it to [0] it sends you to a different part of the loop. (hope that makes sense).
Since the values of charArray are constant, I would recommend making it a global variable, rather than declaring it in your function. In addition, since some numbers have 4 letters, whereas others have 3, you may want to look into using a jagged array to represent it.
As far as printing the permutations you can get from a phone number, I think recursion is going to be your friend. Assuming you can store the phone number in an int array, the following should work:
public void printPermutations(int[] phoneNumber)
{
printPermutations(phoneNumber, 0, String.Empty);
}
private void printPermutations(int[] phoneNumber, int index, string permutation)
{
if(index >= phoneNumber.Length)
{
// If we've reached the end, print the number
printf(permutation + "\n");
}
else
{
// Otherwise, generate a permutation for each
// character this digit can be
int digit = phoneNumber[index];
char[] chars = charArray[digit];
for (int i = 0; i < chars.Length; i++)
{
printPermutations(phoneNumber, index+1, permutation + chars[i]);
}
}
}

Simply C loop is driving me nuts

So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The problem I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.
the code I wrote is this:
int i, input, array[10];
for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}
EDIT: added array definition.
any suggestions or hints would be very highly appreciated.
Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?
Perhaps in this case it would tell you what's going wrong. The docs are here.
Returns the number of fields
successfully converted and assigned;
the return value does not include
fields that were read but not
assigned. A return value of 0
indicates that no fields were
assigned.
This code working good.
If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.
You need the right #include and a proper main. The following works for me
#include <stdio.h>
int main(void) {
/* YOUR CODE begin */
int i, input, array[10];
for (i = 0; i < 10; i++) {
scanf("%d", &input);
array[i] = input;
}
/* end of YOUR CODE */
return 0;
}
i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array

Resources