I wrote a program for bubble sort which is showing a run time error saying "NULL Pointer Assignment". The code is given below:
#include <stdio.h>
void main()
{
int a[6], j = 0, count = 0, i, temp;
printf("Enter the number");
for(i = 0; i< 4; i++)
{
scanf("%d", &a[i]);
}
while(count < 4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[++j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
count++;
}
printf("The sorted array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
But When I tried the below code then it runs successfully.
#include <stdio.h>
void main()
{
int a[6], count=0, i, temp;
printf("Enter the number");
for(i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
while(count<4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
count++;
}
printf("The sort array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
So I need the reason that why my code is showing error, and why the 2nd code is working. I am a new learner in C so please explain to me the reason briefly and simply.
The reason you are getting a NULL pointer exception is in the first program, by the completion of the first iteration of the while loop the value of j has become 4. In the second iteration of the while loop the j value is not reset and continues from 4. Trying to access a[j] when j is equal to 6 will result in a the said error.
for (i = 0; i < n - 1; i++) {
for (j = 0; j <= i; j++) {
if(a[j] > a[j + 1]) {
// swap
}
}
}
Something like this will do the job.
The reason is that you don't reset the variable ´j´ at the beginning of the outer while loop and j is increased in the inner for loop. So you are increasing j in each of the 4 outer while loop transitions for 4 times in the inner for loop. So j has already reached the value 4 after the first while loop round. In the second while loop round it will be incremented to 5, 6, 7, 8 etc. So just reset the variable j to 0 at the beginning of the while loop:
while(count<4)
{
j = 0;
for(...
By the way it's still not a good implementation because you are comparing the last value with an undefined value: if(a[3] < a[4]).
Whereas a[3] contains the last entered value the variable a[4] contains an undefined value. Therefore you should change the for loop to for(i=0;i<3;i++).
Related
I want to randomize a to p without repetition.
int main(){
int array2[4][4];
bool arr[100]={0};
int i;
int j;
srand(time(NULL));
for(i=0; i<=3; i++){
for(j=0; j<=3; j++){
int randomNumber1;
randomNumber1 = (rand() % (82-65+1))+65;
if (!arr[randomNumber1])
{
printf("%c ",randomNumber1);
array2[i][j]=randomNumber1;
}
else
{
i--;
j--;
arr[randomNumber1]=1;
}
}
printf("\n");
}
return;
the output still has repeat alphabet. I want to have the output in 4x4 with with all a to p without it repeating.
There are some errors in your code. IMHO the most serious is that arr[randomNumber1]=1; is is the wrong branch of the test. That means that your current code does not invalidate once a number was used but only if it has already been invalidated => if you control the arr array at the end of the program all value are still 0.
That is not all. When you get a duplicate, you should only reset the inner loop, and you are currently off by 2 in your maximum ascii code: you go up to R when you want to stop at P.
Your code should be:
for (i = 0; i <= 3; i++) {
for (j = 0; j <= 3; j++) {
int randomNumber1;
randomNumber1 = (rand() % (81 - 65)) + 65;
if (!arr[randomNumber1])
{
printf("%c ", randomNumber1);
array2[i][j] = randomNumber1;
arr[randomNumber1] = 1;
}
else
{
//i--;
j--;
}
}
printf("\n");
}
But this kind of code is terribly inefficient. In my tests it took 30 to 60 steps to fill 16 values, because random can return duplicates. This is the reason why you were advised in comments to use instead the modern algorithm for Fisher-Yates shuffle:
int main() {
int array2[16];
unsigned i, j, k=0;
// initialize array with alphabets from A to P
for (i = 0; i < sizeof(array2); i++) {
array2[i] = 'A' + i;
}
// Use Fisher-Yates shuffle on the array
srand(time(NULL));
for (i = 15; i > 0; i--) {
j = rand() % (i + 1);
if (j != i) {
int c = array2[i];
array2[i] = array2[j];
array2[j] = c;
}
}
// Display a 4x4 pattern
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
printf("%c ", array2[k++]);
}
printf("\n");
}
return 0;
}
Which shuffles the array in only 16 steps.
Here is the outline
// Need some #includes here - exercise for the reader
char items[] = "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(items);
srand(time(NULL));
while (len > 0) {
int r = rand() % len;
printf("%c", items[r]);
len--;
items[r] = items[len];
}
This should do the trick to print the whole alphabet in random order without repeats. Modify to do what you need it to do
So here is the code....
#include <stdio.h>
#include <stdlib.h>
int main() {
int a[20] = { 1, 2, 4, 5, 6, 7, 8, 9, 10 };
int new_num, n, i = 0;
for (i; i < 10; i++) {
//printf("the elements in the array are:");
printf("%d\n",a[i]);
}
printf("enter the index you want to insert the element");
scanf("%d", &n); //don't forget to add &
printf("Enter the element");
scanf("%d", &new_num);
for (i = 9; i >= n; i--) {
for (int j = 10; j > n; j--) {
a[j] = a[i];
}
}
a[n] = new_num;
printf("new array is:");
for (i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
return 0;
}
and here is the output...
Can anyone tell me what I did wrong?
I want to use a nested loop for shifting the elements to the next address, instead of using this syntax:
for (i = 9; i >= n; i--) {
a[i + 1] = a[i];
}
but the output seems a bit eerie as I have shown in the output image.
The problem is this snippet:
for (i=9;i>=n;i--){
for (int j=10;j>n;j--){
a[j]=a[i];
}
}
When i == 4, you're setting all elements of a for which the index exceeds 4 to the value of a[4] (which is 6). You probably want something closer to:
for (int j = 10; j > n; j++) {
a[j] = a[j - 1];
}
a[n] = new_num;
Also, you have a small bug in that you're assuming a is of length 10 but you're missing the value 3, so it only has 9 elements.
Edit: I just saw that you want to use a nested loop. Is that a hard requirement? A nested loop just isn't the right way to go here.
I am writing a program which determines the intersection of 2 integer arrays (size of 10 elements). I think I got every other parts covered except for sorting out duplicates. Does anyone know a way of checking duplicates without making a function or using an external C library?
#include <stdio.h>
#define SIZE 10
int main(void){
//Initialization
int array1[SIZE];
for (int i = 0; i < SIZE; i++)
{
printf("Input integer %d of set A: ", i + 1);
scanf("%d", &array1[i]);
}
int array2[SIZE];
for (int i = 0; i < SIZE; i++)
{
printf("Input integer %d of set B: ", i + 1);
scanf("%d", &array2[i]);
}
int intersection[SIZE];
for (int i = 0; i < SIZE; i++)
{
intersection[i] = '\0';
}
//Intersection check
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (array1[i] == array2[j])
{
intersection[i] = array1[i];
break;
}
}
}
//duplicate check
int count = SIZE;
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
if (intersection[i] == intersection[j])
{
for (int k = j; j < count; i++)
{
intersection[k] = intersection[k + 1];
}
count--;
}
}
}
//printing set
for (int i = 0; i < SIZE ; i++)
{
//printf("%d\n", intersection[i]);
if (intersection[i] != '\0')
{
printf("%d\n", intersection[i]);
}
}
return 0;
}
In the code above i was trying one method although it didn't work and instead made the program stuck after inputting all the elements. I am open to other methods as long it doesn't require an external library to run. Thanks
As i see it now , in the third loop where you checking your duplicates i thing that you have to increese k not i :
for (int k = j; j < count; k++), also you must decrise the size of j in your code under the count--;.So your code for checking duplicates seems right but , you want the intersection of this two arrays you made , so you dont have to check for duplicates because in the array intersection[SIZE] you will put only one number from the two arrays, so you will not have duplicates .You should check for duplicates if you wanted to make the union of this two arrays .I make some changings to your code acording what you want to create and this code here find the intersection from two arrays.Try this and delete the duplicate check because that makes your code to run to infinity . One last thing your intersection check must be replace whith this :
//Intersection check
int i = 0, j = 0,k=0; // k is for the intersection array !
while (i < SIZE && j < SIZE) {
if (array1[i] < array2[j])
i++;
else if (array2[j] < array1[i])
j++;
else if(array1[i]==array2[j]) // if array1[i] == array2[j]
{
intersection[k]=array2[j];
//printf("intersection[%d]=%d\n",i,intersection[i]);
intersectCount++;
k++;
i++;
j++;
}
}
printf("intersectCount=%d\n",intersectCount);
I wrote to program in C to attempt to print array elements in descending order. I wrote a nested loop which would find the maximum element of the array and the value of the element would be set to later 0. This process would be repeated for all the elements. However, in the output, I am getting the first 2-3 values as desired but the remaining values are garbage. Any suggestions?
int main() {
int i, j, n, k;
scanf("%d\n", &n);
int a[100], b[100];
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++) {
int max = a[i];
for (j = i; j < n; j++) {
if (a[j] > max) {
max = a[j];
b[i] = max;
}
}
for (k = 0; k < n; k++) {
printf("%d", a[k]);
if (a[k] == b[i]) {
a[k] = 0;
}
}
printf("\n");
}
for (i = 0; i < n; i++) {
printf("%d ", b[i]);
}
}
The main issue is that you only set b[i] = max; when you find a new max, but since you initialized max to be a[i] it could happen that it already holds the maximum value. So the if never executes, therefore b[i] is not written and there's garbage value in it. You should move this line from the if after that for loop.
Another issue is that you initialize j with i in this loop. You should initialize it to 0.
The changed part:
for (j = 0; j < n; j++) {
if (a[j] > max) {
max = a[j];
}
}
b[i] = max;
I need to create a program where user will input a number of integers and the program will output the fibonacci sequence number having the next larger number than the user input.
fibonacci sequence as follows:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
Example:
user inputs: [1, 9, 22]
output should be: 2, 13, 34
I cant seem to make the if loop stop once it has already acquired a value because the output will always display 4181, 4181, 4181.
My code is as follows below:
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, a[100];
int inputarray[3], j;
int outputarray[3];
a[0] = 0;
a[1] = 1;
for (i = 2; i < 20; i++) {
a[i] = a[i-1] + a[i-2];
}
for (i = 0; i < 20; i++) {
printf("%5d",a[i]);
}
for (j = 0; j < 3; j++) {
printf ("\nEnter numbers of input array:");
scanf ("%d", &inputarray[j]);
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 20; j++) {
if (a[j] > inputarray[i])
outputarray[i] = a[j];
}
}
for (i = 0; i < 3; i++) {
printf("%5d", outputarray[i]);
}
getch();
}
Add break statement because once you found required value, you don't have to keep looping for j
for (i=0; i<3; i++)
{
for (j=0; j<20; j++)
{
if(a[j] > inputarray[i])
{
outputarray[i] = a[j];
break;
}
}
}
I would be much easier if you did not use a for loop (because you don't want to iterate over a given amount of values). If your loop depends on a condition use a do-while/while loop.
for (i = 0; i < 3; i++) {
while (a[j] <= inputarray[i])
{
j++;
}
outputarray[i] = a[j];
}