Understanding the arrays in C - c

I'm new to C and need some help to understand how this piece of code works. I know that it reads the values that the user writes, puts them into an array, and then prints them out.
But I don't understand why I need two "counters" (i and j) to do this. Can someone help me to figure it out?
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
int j=0;
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
while (j < 5)
{
j++;
printf ("\n%d\n", A[j]);
}
}

Technically, what you have aren't two counters, but two loops. If you wanted, to, you could just reuse i for the second loop as well, by doing something like this:
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
i = 0;
while (i < 5)
{
i++;
printf ("\n%d\n", A[i]);
}
As for why you have two loops, the reason is simple. The first loop (using i in your code), reads the 5 integers into the array A. After the first loop concludes, your array A holds the 5 int values, which you could've used however you wanted. In your case, you want to print those values. So what you do is use a loop for looping over the array elements and printing the values to the screen, one by one.

You don't need it, you can simply reset the first and reuse it. However you must increment your index only after having using it otherwise you will overflow the limit of the array :
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
while (i < 5) {
printf("Enter your %d number\n", i);
scanf("%d", &A[i]); // the last must be 4 not 5
i++; //<== increment here
}
i=0;
while (i < 5)
{
printf ("\n%d\n", A[i]); //idem
i++;
}
}

Related

How to split an array into two arrays, one for even and one for odd in C

I am doing an exercise that consists of a program that generates 100 random numbers ranging from 1 to 1000 and saves them in an array.
I have to separate this array into two arrays, one for even numbers and one for odd numbers and print the lists.
I have managed to separate into two arrays, but when they are empty, they invent them. How can i avoid it? Any clue to improve it?
Thank you so much.
That's my code:
#include<stdio.h>
#include<conio.h>
int main(){
int array100[100];
int arraypar[100];
int arrayimpar[100];
int i, n=0, m=0;
for(i=0;i<100;i++){
array100[i] = rand() % (1000 + 1);
printf("%i ", array100[i]);
}
printf("\n\n");
for(i=0;i<100;i++){
if(array100[i]%2==0){
m++;
arraypar[m] = array100[i];
}
else{
n++;
arrayimpar[n] = array100[i];
}
}
printf("\n\n Numeros pares: \n");
for(i=1;i<=100;i++){
printf("%i ", arraypar[i]);
}
printf("\n\n Numeros impares: \n");
for(i=1;i<=100;i++){
printf("%i ", arrayimpar[i]);
}
getch();
return 0;
}
Un-initialized variables can contain anything, it is better to start of by initializing.
This
int array100[100];
int arraypar[100];
int arrayimpar[100];
Should be:
int array100[100] = {0};
int arraypar[100] {0};
int arrayimpar[100] = {0};
And since C uses 0 base array indexing, you are probably seeing a run time error; Dereference of out-of-bounds pointer (or similar) if the code shown in your post is the actual code you are using.
This:
for(i=1;i<=100;i++){
^ ^^
printf("%i ", arraypar[i]);
}
Should be this:
for(i=0;i<100;i++){
^ ^
printf("%i ", arraypar[i]);
}
Same for the next for loop.
Also, a suggestion to help you troubleshoot. I would start off by initializing array100 with a known set of sequential values to easily test whether the values are being split properly:
int array100[100] = {1,2,6,4,5,6,7,8,9,10,
11,12,16,14,15,16,17,18,19,
20,21,22,26,24,25,26,27,28,29,
60,61,62,66,64,65,66,67,68,69,
40,41,42,46,44,45,46,47,48,49,
50,51,52,55,54,55,56,57,58,59,
60,61,62,66,64,65,66,67,68,69,
70,71,72,77,74,75,77,77,78,79,
80,81,82,88,84,85,88,87,88,89,
90,91,92,99,94,95,99,97,98,99,100};
Now run your program with the rand() section commented out to see what you get. If there are problems, they will be easier to see then looking at a collection of randomly generated numbers.
Index of array starts from 0 not 1, so your code below:
for(i=0;i<100;i++){
if(array100[i]%2==0){
m++;
arraypar[m] = array100[i];
}
else{
n++;
arrayimpar[n] = array100[i];
}
}
should change to:
for(i=0;i<100;i++){
if(array100[i]%2==0){
arraypar[m] = array100[i];
m++;
}
else{
arrayimpar[n] = array100[i];
n++;
}
}
So, when you print, you should print m even numbers and n even numbers instead of print all values in arraypar and arrayimpar.:
printf("\n\n Numeros pares: \n");
for(i=0;i < m;i++){ // if m==0, you print nothing
printf("%i ", arraypar[i]);
}
printf("\n\n Numeros impares: \n");
for(i=0;i< n;i++){ // if n == 0, then you print nothing
printf("%i ", arrayimpar[i]);
}
You allocate 100 places for the arrayimpar and arraypar (with indexes 0..99). Usable number of elements (those you want to read) in those arrays are: m(for arraypar) and n (for arrayimpar). Why not use those variables when printing those arrays:
printf("\n\n Numeros pares: \n");
for(i = 1; i <= m; i++){
printf("%i ", arraypar[i]);
}
printf("\n\n Numeros impares: \n");
for(i = 1; i <= n; i++){
printf("%i ", arrayimpar[i]);
}
Practically, this should work, but theoretically you could get one of the arrays completely full, and the other empty. When that happens, eventually you will access 101-st element (with index 100) which doesn't exist. Try to fill these arrays from index 0 instead of 1, so you could never access 101-st element.

Problem in printing inverse array of an input array

#include <stdio.h>
#include <conio.h>
void main()
{
int arr[5], new[5], i, j;
printf("ENTER ANY FIVE NUMBERS:");
scanf("%d%d%d%d%d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
for(i=0; i<5; i++)
{
for(j=5; j>=0 ;--j)
{
new[i] = arr[j];
printf("%d", new[i]);
printf(" ");
}
}
getch();
}
The above code is of a simple problem, which asks to take inputs of numbers in an array and show the inverse array of the input. I tried to solve it myself and wrote the above code. But the compiler is showing the result multiple times, I mean, the result should have only 5 numbers but the output shows series of numbers.
Here is one problem:
for(j=5;j>=0;--j){
new[i]=arr[j];
^ out of bounds access to arr[5]
Change it to
for(j=4;j>=0;--j){ // 4 instead of 5
new[i]=arr[j];
That said, if all you want is to print an array in reverse order, simply do:
for(j=4;j>=0;--j){
printf("%d", arr[j]);
printf(" ");
}
printf("\n");
No need for two loops and no need for the extra array new
If you really want a "reversed copy" do:
for(j=4;j>=0;--j){
new[4-j] = arr[j];
printf("%d", arr[j]); // or printf("%d", new[4-j]);
printf(" ");
}
printf("\n");

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

Segmentation fault in my program

My sorting program results in a "segmentation fault 11":
#include <stdio.h>
int main()
{
// Asking user for number of inputs in an array
int n;
do {
printf ("enter the number of intigers you want to sort\n");
scanf("%d",&n);
}while (n<=1);
int sort [n];
printf ("please enter %d numbers\n",n);
for (int i=0; i<n; i++) {
scanf("%d",&sort[i]);
}
printf("you entered\n ");
for (int i=0; i<n; i++) {
printf(" %d ",sort[i]);
}
printf("\n");
int k,c,i,x;
for (i=0;i<n;i++) {
if (sort[i]<sort[i-1]){
k=i-2;
while (sort[k]>sort[i]){
k--;
}
k++;
x =sort[i];
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
}
}
printf ("Sorted numbers :-\n");
for (int i=0; i<n; i++) {
printf ("%d ",sort[i]);
}
printf ("\n");
return 0;
}
Now I have looked up the internet and found that it is caused because a variable has value that exceeds the system's memory limit. But cannot understand that concept.
for (i=0;i<n;i++)
{
if (sort[i]<sort[i-1])
You are accessing array out of its bounds.Maybe you want to start your loop from 1.Also
k=i-2;
while (sort[k]>sort[i])
will access index beyond 0 for example if i is 0 or 1 or 2
k = i - 2; looks unstable for low values of i.
sort[i - 1] is undefined when i is zero.
The thing causes the behaviour of sort[k] to be undefined.
Moral of the story: check all the array indexes before attempting to retrieve an array element. Your debugger will help you here.
In addition to all said before:
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
i can be 0 -> c can be 0 -> sort[c-1] would also result in accessing array out of bounds.
There is no need to initialize c=i twice. It is enough to do it in the loop-declaration

Understanding my mistake with for-loop

I'm new to C and I'm trying to practice my knowledge by doing programs by my own without the use of the internet. I'm stuck with a small and probably dumb mistake but i can't seem to understand what it is. I'm trying to build an hour glass but before i do so i need to understand printing triangles. I'm really going step by step with this and I have tried to understand my mistake for very long with this.
I have my code below and I'm trying to print j where i need j to print normally 12345 then 1234, 123 etc.. but when I use temp-- it skips by printing 123,1,1 and closes the program.
Can somebody have a look at it and tell me what the problem with me second for loop?
#include <stdio.h>
int main()
{
int i,j,k,num, temp=0;
printf("Enter a number: ");
scanf("%d", &num);
temp=num;
for (i=1; i<=num; i++) // Step1: Take care of the rows --> check
{
for (j=1; j<=temp; j++)
{
printf("%d", j);
temp-=1;
}
printf("\n");
}
}
You both increment j and decrement temp which leads to odd effects. You probably don't want to decrement temp. Or you need to reset temp before the inner loop, rather than before the outer loop.
Or, indeed, you do not really need temp at all. Here are two variants of the code, one creating a triangle growing, and one creating a triangle shrinking. Neither needs temp (though t-dn.c could use a variable in place of the expression num - i + 1, but the compiler will probably handle that anyway — it is a basic optimization).
t-up.c
#include <stdio.h>
int main(void)
{
int i,j,num;
printf("Enter a number: ");
scanf("%d", &num);
for (i=1; i<=num; i++)
{
for (j=1; j<=i; j++)
printf("%d", j);
printf("\n");
}
}
t-dn.c
#include <stdio.h>
int main(void)
{
int i,j,num;
printf("Enter a number: ");
scanf("%d", &num);
for (i=1; i<=num; i++)
{
for (j=1; j<=num-i+1; j++)
printf("%d", j);
printf("\n");
}
}
Example output
$ ./t-up
Enter a number: 5
1
12
123
1234
12345
$ ./t-dn
Enter a number: 5
12345
1234
123
12
1
$
t-ok.c
Another variant, keeping the temp variable around:
#include <stdio.h>
int main(void)
{
int i,j,num,temp;
printf("Enter a number: ");
scanf("%d", &num);
temp=num;
for (i=1; i<=num; i++)
{
for (j=1; j<=temp; j++)
printf("%d", j);
printf("\n");
temp--;
}
}
It produces the decreasing pyramid I believe you want. It places the decrement outside the inner loop.
You're decrementing your j-loop condition within the j-loop. This means that every time you print a number, you also decrease the size of your loop (not at all what you want). To fix this, you need to move your temp-=1 from
for (i=1; i<=num; i++) // Step1: Take care of the rows --> check
{
for (j=1; j<=temp; j++)
{
printf("%d", j);
temp-=1;
}
printf("\n");
}
to
for (i=1; i<=num; i++) // Step1: Take care of the rows --> check
{
for (j=1; j<=temp; j++)
{
printf("%d", j);
}
temp-=1;
printf("\n");
}
This decreases the size of your j-loop AFTER you've finished going through it, so you should wind up with the right amount of numbers.
You could even do away with your temporary variable by reversing the i-loop like such
for ( i = num ; i > 0 ; i-- ) {
for ( j = 1 ; j <= i ; j++ ) {
printf("%d", j);
}
printf("\n");
}
for a simpler code.

Resources