NULL confusion in C - c

I am creating a simple "ascending" program. When I find smallest int in array of int I want to replace it with some other value so it won't come as smallest number again in the array. For that, I assigned that int NULL. But now the results are not as expected.
Please tell me if I am doing anything wrong. If so then what I should replace with the value of that int ?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[10],b,c=0,d=0;
printf("Enter number of values you want to enter \n");
scanf("%d",&b);
printf("Enter values \n");
for(int i=0;i<b;i++)
scanf("%d",&a[i]);
while(c<b)
{
for(int k=0;k<b;k++)
{
for(int j=0;j<b;j++)
{
if(a[k] > a[j])
{
d=1;
}
}
if(d!=1 && a[k]!=NULL)
{
c++;
printf("%d ",a[k]);
a[k]='\0' ; //assigning it as NULL
}
if(c >= b)
break;
d=0;
}
}
getch();
}

In C and related languages ints are not "nullable" - you could use a special value instead, e.g. a value that is well outside the expected range of your input data, such as INT_MAX:
#include <limits.h> // required header for INT_MAX et al
...
if(d!=1 && a[k]!=INT_MAX)
{
c++;
printf("%d ",a[k]);
a[k]=INT_MAX
}
However it would probably be a good idea to go back to the drawing board and see if you can come up with a better algorithm that doesn't require special values.

Read the differences between NULL and 0 and '\0' here. There is a type mismatch when you're trying a[k]!=NULL.
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a[10], b, c = 0, d = 0;
int k, j, i;
printf("Enter number of values you want to enter \n");
scanf("%d",&b);
printf("Enter values \n");
for(i = 0;i < b;i++)
scanf("%d",&a[i]);
while(c < b)
{
for(k = 0;k < b;k++)
{
for(j = 0;j < b;j++)
{
if((a[k] > a[j]) && a[j] != 0)
{
d=1;
}
}
if(d != 1 && a[k] != 0)
{
c++;
printf("%d ",a[k]);
a[k] = 0; //assigning it as NULL
}
if(c >= b)
break;
d=0;
}
}
return 0;
getch();
}
This code fixes the problem.
What you're missing is a[j] != 0 in if((a[k] > a[j]) && a[j] != 0). Also I don't suggest this, as it won't work if there are 0's in the array entered.

Related

How to check whether any data is provided in array or not in C?

I am making a program that sorts integers in ascending and descending order through bubble sort algorithm in C. So, I am providing a random data of 20 integers(fixed)first and then deciding in which manner to sort it, which is basically done through simple menu system which is like:
A. provide random data
B. Sort high to low
C. Sort low to high
*I want to print a message "Data not provided" if the user tries to sort without getting the random data first.
Code below:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void random_number_list(int array[]);
void low_to_high(int array[]);
void high_to_low(int array[]);
void display(int array[]);
int main(void)
{
int original_array[21];
char selection;
do
{
puts("----> Please make your selection from the following:\n\n"
" A.Define Random Number List\n"
" B.Sort Number List(High to Low)\n"
" C.Sort Number List(Low to High)\n"
" D.Exit ");
printf_s(" \nYour selection: ");
scanf_s("\n%c", &selection);
if (selection == 'A' || selection == 'a')
{
random_number_list(original_array);
}
else if (selection == 'B' || selection == 'b')
{
high_to_low(original_array);
}
else if (selection == 'C' || selection == 'c')
{
low_to_high(original_array);
}
else if (selection == 'D' || selection == 'd')
{
puts("\nThank you for using the application.\n");
return 0;
}
else
{
puts("\nSorry, input not understood. Please try again.\n");
}
}
while (selection != 'D');
}
void random_number_list(int array[])
{
srand(time(NULL));
printf("\n\nThe Random Data: ");
for (size_t i = 0; i < 20; i++)
{
array[i] = 1 + rand() % 100;
printf_s("%d,", array[i]);
}
puts("\n\n");
}
void low_to_high(int array[])
{
int i, j, temp;
for (i = 0;i < 20 - 1;i++)
{
for (j = i + 1;j < 20;j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
display(array);
printf("\n");
}
}
}
printf_s("\nSorted Data : ");
display(array);
puts("\n");
}
void high_to_low(int array[])
{
int i, j, temp;
for (i = 0; i < 20 - 1; i++)
{
for (j = i + 1; j < 20; j++)
{
if (array[i] < array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
display(array);
printf("\n");
}
}
}
printf_s("\nSorted Data : ");
display(array);
puts("\n");
}
void display(int array[])
{
for (size_t i = 0; i < 20; i++)
{
printf("%d,", array[i]);
}
}
What about using a boolean flag indicating whether option A was called? Initialize that flag with false and set it true in option A. Then in options B and C, test if the flag is true. If false, complain.
Showing us the code you have so far would be helpful.
I would include stdbool.h and create a boolean variable in the main function called something like is_generated set to false by default and set it to true when the option A is entered. Then you can check it instead of checking if original_array is equal to zero.
You can use the sizeof operator and divide the result by the size of an element.
size_t n = sizeof your_array

C program to insert elements into an array until user inputs a 0 or less number

I'm trying to make a C program to insert elements into an array until user inputs a 0 or less number, as the title says. But when I print the array out, it doesn't show the numbers I inputted. I have tried using a while as well as do-while loops but without success.
#include <stdio.h>
int main() {
int data[100];
int i;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
int n = sizeof(data[i]);
for (int i = 0; i < n; i++) {
printf("%d ", &data[i]);
}
}
Try this:
#include <stdio.h>
int main() {
int data[100];
int i;
int counter = 0;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
counter++;
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
for (int j = 0; j < counter - 1; j++) {
printf("%d ", data[j]);
}
}
The problem was that you had printf("%d ", &data[i]); instead of printf("%d ", data[i]);.
And also you've trying to get the sizeof() of an element data[i], not the size of the whole array. That's why there's counter in my code.
int n = sizeof(data[i]);
this is wrong, you want
int n = i;
sizeof(data[i]) gives you the size of an int (4 on my machine)
On the other hand, you need to check the result of scanf, if a bad input is entered do not increment the counter, something like:
int i = 0;
while (i < 100)
{
int res = scanf("%d", &data[i]);
if (res == EOF)
{
break;
}
if (res == 1)
{
if (data[i] <= 0)
{
break;
}
i++;
}
else
{
// Sanitize stdin
int c;
while ((c = getchar()) != '\n');
}
}
Finally, scanf wants a pointer to the object, but this is not the case of printf:
printf("%d ", &data[i])
should be
printf("%d ", data[i])

C Program (Prime Number in a given range)

I have started learning C language. I wrote this program to find all prime numbers between the given range but I am unable to get the expected output.
Can anyone tell me what's wrong with this program please?
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++) {
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
getch();
}
I just suggest getting rid of that count variable.
How do you know if a number N is prime? If for every j in the range (2 to N-1) you have N%j != 0.
So:
In the inner loop, use j from 2 to N-1 (instead of from 1 to N as you used tio do). In fact N%1 and N%N will be 0
The first time you find a j so that N % j == 0 break. You are sure it's not prime
Why incrementing count? For a prime number the j counter will be equal to i (because you looped until j<i, and the last j++ made j
equal to i). So just check for j == i and print the prime number i
#include <stdio.h>
#include <conio.h>
int main( void )
{
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
// Was for(j=1; j<=i; j++)
for(j=2; j<i; j++)
{
if(i % j == 0)
{
//Was count++;
break;
}
}
//Was if(count==2)
if(j == i)
{
printf("%d\t",i);
}
}
getch();
return 0;
}
Here you are.
#include <stdio.h>
int main( void )
{
printf( "Enter the range of numbers (two unsigned integer numbers): " );
unsigned int first = 0, last = 0;
scanf( "%u %u", &first, &last );
if ( last < first )
{
unsigned int tmp = first;
first = last;
last = tmp;
}
do
{
int prime = first % 2 == 0 ? first == 2 : first != 1;
for ( unsigned int i = 3; prime && i <= first / i; i += 2 )
{
prime = first % i != 0;
}
if ( prime ) printf( "%u ", first );
} while ( first++ != last );
putchar( '\n' );
return 0;
}
The program output might look like
Enter the range of numbers (two unsigned integer numbers): 0 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
As for your program then you need re-initialize the variable count before the inner loop
for(i=min; i<=max; i++) {
count = 0;
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
And the inner loop is inefficient.
Need to reset the value of count. It starts at count=0, then for any inputs, the loops will count up. The For each outer loop index, it will go like this:
1 (1%1=0 --> count++, count = 1)
2 (2%1=0 --> count++, and 2%2=0 --> count++, count = 3)
3 (3%1=0 --> count++, and 3%3=0 --> count++, count = 5)
etc... until max is reached.
You can use a simple isprime function to check whether a number is prime or not and then call the function for the given interval.
To find whether a number is prime or not , we can use a simple primality test to check it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isprime(int n)
{
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(int i = 5;i*i <= n;i += 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int main()
{
int a,b;
printf("Enter the first number :");
scanf("%d",&a);
printf("Enter the second number :");
scanf("%d",&b);
for(int i = a;i <= b;i++)
{
if(isprime(i)) printf("%d ",i);
}
return 0;
}
There is a simple change you should do:
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
count=1;
for(j=2; j<=i; j++)
{
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
}
My answer may be a bit late, but since it's the same issue, i'll write it here in case it helps someone else coming to this thread in the future.
My code is written from the POV of a beginner (No complex functions or data types are used) as this is a code that mostly they will get stuck on.
Working:
User inputs the range.
Using the for loop, each number in the range is sent to the isprime function which returns TRUE or FALSE after checking the condition for being a prime number.
if TRUE : program prints the number.
if FALSE : program skips the number using continue function.
#include<stdio.h>
int isprime(int num);
int main() {
int min, max;
printf("Input the low number: ");
scanf("%d", &min);
printf("Input the high number: ");
scanf("%d", &max);
for(int i = min; i<=max; i++) {
if(isprime(i) == 1) {
printf("%d ", i);
}
else if(isprime(i) == 0){
continue;
}
}
return 0;
}
int isprime(int num) {
int count = 0;
for(int i=2; i<=(num/2); i++) {
if(num % i == 0 ) {
count ++;
}
else{
continue;
}
}
if(count>0){
return 0;
}
else if (count == 0){
return 1;
}
}

C program for assigning elements of a matrix without letters

I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.

function trouble about find largest in array

write a program that enter a series of integer(stores in array),then sorts the integer by calling the function selection_sort. When given an array with n elements, selection_sort must do the following:
1.search the array to find the largest,then move it to the last position.
2.call itself recursively to sort the first n-1 elements of the array.
following is my code i think the code is errors everywhere i hope some master can help me
#include <stdio.h>
int selection_sort(int a[])//this function have error that "i"and"count"is undeclared
{
int max = 0;
for (i = 1; i <= count; i++)// continuous compare to final
{
if (a[i] > max)
{
max=a[i];
}
}
a[count] = a[i]; //put the max to last position
count--;
}
int main(void)
{
int a[100] = { 0 },i=0,count=0;
while (1)
{
scanf("%d",&a[i]);
if (a[i] = '\n') { break; }//this line have error because '\n' not "int" so when i "enter" it would not break
i++;
count++; //counting how many integer i scanf
}
selection_sort();//call this function (i don't know well about function so i don't known where to put is correct )
return 0;
}
You have to compare. BUt you are assigned..
change this if (a[i] = '\n') { break; } to if (a[i] == '\n') { break; }.
You should change follows in your code.
1) change your function call..
2) declare count and i in function..
3) for taking values in to array,follow other method..
Try yourself...
Here is the complete code.Basically there are many syntax and logical error in your code. Consider this as refer and compare with your original source.
int selection_sort(int a[], int count){
int max = 0, i =0;
for (i = 0; i < count; i++){
if (a[i] > max)
{
max=a[i];
}
}
a[count] = max;
count--;
return 0;
}
int main(void) {
int a[100] = { 0 },i=0,count=0;;
printf ("Enter the total num\n");
scanf("%d",&count);
if ( ( count ) >= (sizeof(a)/sizeof(a[0])) )
return -1;
while (i < count){
scanf("%d",&a[i]);
i++;
}
selection_sort(a, count);
printf ("\nmax:%d\n", a [count]);
return 0;
}

Resources