Array sorting using special XOR condition - c

I have a problem in understanding the condition of my program, I can hardly explain it in a sentence so I will explain the whole point of program.
So for my homework I got to make a program that will ask user to enter number N which will represent the number of elements in array, then user enters elements of that array (assuming that user will enter correct number of elements) program then needs compare every number from that array with a number X with XOR (^) Operator.
The task is to find a minimum value for that X in which will the resulting array have elements in ascending order. It sounds a bit complicated but this is how it should work:
You enter a number N: For example lets use 4.
Then you enter 1D array of 4 elements : Lets use 4 2 3 1
Then program needs to use a number X (do while loop) to test every number from
this array with that number and if that number is >= to the previous one, it
should continue to check the next and next until it reaches the number N
If every element is sorted in ascending(equal counts as ascending) order it
should display that number.
So for our example 4 2 3 1 when you use XOR operation with every one of them
with the X=6 you get array that looks like this 2 4 5 7 which is in ascending
order.
To explain: 4 in binary is 100 ; X in binary is 110 if you use XOR on
those you get 010 which is 2, and do as follows for the rest ( program does
everything)
So I made the program,everything works great returning good values for every example that we have for reference, my only problem is that I don't know when to stop looking for that number X, or how should I know that minimum X for that array of numbers doesn't exist. In that case my program runs forever and don't return any value,so basically an infinity loop.
I need to use code that is simple so nothing too complicated because this is a course "Introduction to programming" and they won't accept anything that was made using complex algorithms or something like that.
EDIt: The program should display -1 if there are no X.
Here is the code :
#include <stdio.h>
int main() {
int matrix[100];
int n;
int i;
int index=1;
int x=0;
int start=0;
int end=0;
printf("Enter N: ");
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&matrix[i]);
}
index=1;
x=0;
do {
start=matrix[index]^x;
if((matrix[index+1]^x) >= start)
index=index+1;
else x++;
if(index==n){
printf("X=%d",x);
end=1;
break;
}
} while(end!=1);
return 0; }

Related

Having trouble understanding the for loop

#include <stdio.h>
int n, a[100001], x, y;
int main() {
scanf("%d", &n);
while (n--) {
scanf("%d.%d", &x, &y);
a[x*1000+y]++;
}
for (int i = 0, c = 0; i <= 100000; i++) {
while (a[i]) {
--a[i], ++c;
printf("%d.%03d\n", i / 1000, i % 1000);
if (c == 7) return 0;
}
}
return 0;
}
This is the code that receives an integer n, then the program is expected to receive n number of double or integer variables.
The program is supposed to print out the smallest 7 variables among the input variables to 3 decimal points.
Now the question is i can't seem to figure out how this code in for loop
while (a[i]) {
--a[i], ++c; // <- specifically this part
printf("%d.%03d\n", i / 1000, i % 1000);
if (c == 7) return 0;
}
generates 7 smallest variables.
Any help would be much appreciated
Suppose 8.3 is an input, then you are storing the 8003rd index of the array to 1. i.e a[8003]=1. if 8.3 is input twice then a[8003] will be equal to 2.
So in the for loop when i=8003, a[8003] is non zero that that means there was an input 8.3. So it is considered in the top 7 smallest input values and the loop exits when count reaches 7.
As hellow mentioned, This is bad code and if you are a student, stay away from such programming style (Not just student, everyone should stay away).
What this code does is it creates sort of "Look-up" table.
Whenever a number is entered, it increases a count at that array instance.
e.g. If I input 3.2, it increments a[3002] th location. Code for this is:
scanf("%d.%d", &x, &y);
a[x*1000+y]++;
x = 3 and y = 2 so a[3*1000+2]++ --> a[3002] = 1
(Note: Code assumes that array a is initialized with 0 - another bad habit)
Now say I entered 1.9, code will increment a[1009]. If I enter 3.2 again, a[3002] will be incremented again.
This was input part.
Now code parses entire array a starting from 0. At first it will encounter 1009, code will print 1.9 and keep on parsing array.
When it finds 7 non=zero locations, loop exits.
When you enter same number again, like 3.2, while(a[i]) executes twice printing same number again.
As smaller number will be at lower location in array and array parsing starts from 0, it prints smallest 7 numbers. If you reverse the for loop, you can print 7 biggest numbers.
The answer here is how the input data is being stored.
User entered values populate array a. It does not store actual entered numbers, but a COUNT how many times the value was entered (code makes lots of assumptions about data sanity, but lets ignore that)
The data is naturally Sorted from smallest to largest, so to find 7 smallest inputs you just take first 7 values (iterations tracked by index i, c tracks how many values we already did print out) where the COUNT is not zero (a[i], non zero value indicates how many times user entered corresponding value)

(C) Allow infinite of numbers to be entered, reverse the order of entered numbers & end program when 0 is entered

I'm working on a project at the moment where I have to allow a user to enter an infinite amount of numbers and reverse the order of those entered numbers and end the program if 0 is entered. I did something similar, except the one I did set the amount of numbers the user could enter, so for example in the code below, I allowed the user to enter only three numbers, reverse the order and end when -1 is entered.
#include <stdio.h>
#define MAX 3 // Defining max amount of numbers to be entered to 3
main()
{
int numbers[MAX], i, end;
printf ("Please enter %d integers:\n", MAX);
for (i = 0; i < MAX; i++){
scanf("%d", &numbers[i]);
if (numbers[i]==-1){ // Loop ends when -1 is entered
for (end=i; end<MAX; end++)
numbers[end]='\0'; // Nulls the value of blank locations in the array
i=MAX;
}
}
printf ("\nThe values in reverse order are:\n");
for (i = MAX-1; i >= 0; i--)
{
if(numbers[i]!='\0') // Will not print null values in the array
printf("\n%d ", numbers[i]);
}
return 0;
}
How can I go about achieving this? I'm guessing I won't be able to use an array, and I'm pretty new to this so...
No, arrays can't be grown dynamically (not without some extra tinkering, see comment below) so they can't hold an infinite amount of items.
You'll need some structure you can grow, C doesn't provide one so you'll have to use a third party implementation or write your own. A stack fits your problem the best.
Also, your loop will have to go on until -1 is entered. Either an infinite loop with a break statement, or a do-while loop that checks the entered number.
EDIT: The original question targeted C++, my original answer, below, is no longer relevant.
You want to look into C++'s STL. std::vector, std::deque or std::stack for example, would be useful in your case.
You can use a std::vector to do this.
Here's the declaration of your std::vector. Where the tells the vector you want it to be a vector of type int
std::vector<int> numbers;
Then to add to the end of the std::vector you use push_back(), which puts the integer onto the back of the array. The size of the vector will dynamically increase as you push more elements on to the back.
int input;
numbers.push_back(input);
Then to iterator through it you can use a reverse iterator or just iterate the same way you have been doing it using numbers.size() to find out how many elements are in the vector.

Display number in vertical format [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 8 years ago.
Improve this question
I'm new to C. I have a class assignment to display a number in a vertical format. If the user enters 5678, the instructor want it to display vertically to the screen in a single column as:
8
7
6
5
Second part of assignment is to find the largest divisor of the same number.
I'm totally lost. I'm getting the NUM value from another function. formula seems to work on even numbers, but on odd.
int divisor (int NUM)
{
int index, count=0;
for(index=2;index<=(NUM/2);index=index+1)
{
if(NUM%index==0)
count++;
}
printf("\n\nThe largest divisor of %d is %d\n",NUM, index-1);
return(index);
}
To display the number vertically:
1. get least significant digit,
2. print it and print new line,
3. shift number to the right by one digit
4. goto 1
Algorithm terminates when the number is zero. Call the input number n; getting the least significant (rightmost) digit can be done with n % 10. Right shift can be done with n = n / 10.
For the second part, observe that the largest divisor cannot be more than n/2 (because n = 2 * n/2). So try all number from n/2 down to 1 and break once you find a divisor. You will find the largest divisor because you are considering numbers in decreasing order. To check that x divides y use y % x == 0.
A second way it to check numbers from sqrt(n) down to 1. If m divides n, we can write n = m * k for some k. Now you take max(m, n/m) and continue.
Hope this helps :)
For the first part, there are many ways to approach this. But, without using too many of the standard library functions which seems to be a level appropriate for the question, I think the easiest way would be to take the numbers as a character array. Then access each value through it's index in the character array. This requires only the stdio.h header file. Some quick notes: simply use printf to print the value contained at each index, and throw the newline \n character at the end. If you wanted convert the string to an integer, you can do that very easily using the function atoi() which can be found in stdlib.h. If you want to print out backward, you can simply traverse the array backward.
void displayvert(char str[])
{
int i;
for (i = 0; str[i] != '\0'; ++i) {
printf("%c\n", str[i]);
}
}
Also many ways to approach the second, but in this case for the second question I think I'd use the modulus operator and track the highest value where the result is zero. In order for this to work with the single user provided input, I actually needed atoi() which is in the stdlib.h header. Basically, starting from the value one you'll increase the value up the integer just below the value of 'num' itself. And, if the remainder is zero when you when you divide by it (the purpose of using the modulus operator) then you know it's divisible. Because we're ascending from 1 to the number itself, the last value to return a remainder of zero is the greatest common divisor.
void getgcd(int num)
{
int i, gcd;
// remember, you can't do x % 0!
for (i = 1; i < num; i++) {
if ((num % i) == 0 ) {
gcd = i;
}
}
printf("The greatest common divisor is: %d\n", gcd);
}
Main function and prototypes here so you can see how it all tied together. A couple of quick notes (1) 11 digits was arbitrary; but it's important to note that we used 10 digits for the total input value (you can add checks to this to enforce) and reserved the 11th (at index 10) to allow space for the null terminating character \0. (2) Use scanf to grab input; note that because character arrays do not require the address operator & because it defaults to that.
#include <stdio.h>
#include <stdlib.h>
void displayvert(char str[]);
void getgcd(int num);
int main()
{
char input[11]; // additional character added for \0
printf("Please enter a value up to 10 digits: ");
scanf("%s", input);
displayvert(input);
getgcd(atoi(input));
return 0;
}

Sucessive integers using C programming

Example input: 20 10 5 20 2 20 20 20 2 2 0
Output:
(20*5)
(10*1)
(5*1)
(2*3)
I just started programming this semester and need help on a project. I apologize if my question is unclear.
So basically I have to input positive integers till I enter "0" would end the program. I'm not allowed to use arrays(whatever that means).
#include <stdio.h>
int main ()
{
int number, count=0
while(1)
{
scanf("%d",&number);
if (number!=0)
{
count++; continue;
}
else
{
printf("%d*%d",number,count);
break;
}
return 0;
}
How do I store these multiple numbers so that I wouldn't overlap the previous number and to increment duplicate numbers by 1 every time it's entered? I can't ask my professor for help; he just tells me to google it.
"A certain engineering apparatus is controlled by the input of successive numbers (integers).
If there is a run of the same number, the apparatus can optimize its performance. Hence we
would like to arrange the data so as to indicate that a run is coming. Write a C program that
reads a sequence of numbers and prints out each run of numbers in the form (n∗m) where
m is the number repeated n times. Note that a run can consist of just a single number. The
input numbers are terminated by a zero, which halts the apparatus."
This assignment seems to be based on half-baked knowledge of run length encoding (RLE). Anyway, here's a pseudo-code which does what it asks.
in = read next number from input
current_num = in // let the 1st number in list be current_num
count = 1
loop
in = read next number from input
if (in == 0) break // we are done, get out of loop
else if (in == current_num) count += 1
else // run has ended, print it and start new run
print current_num * count
current = in
count = 1
end loop
print current_num * count // we exited the loop before printing the last run
// so do it outside the loop
You can implement it in code and then "optimize" it to remove repeated code, and take care of corner cases (such as "empty" input, single number input, etc.)
Edit Just to be clear, the assignment asks for a 'run' of numbers, but the sample output shows a 'count' of numbers. These two are not the same.

Displaying primes from 2-10,000 in C

I'm struggling with this (optional) problem my professor recommended I try. Basically, my task is to write a program which displays all prime integers from 2-10,000 using my own user-defined function to determine prime-ness. It sounded simple enough but I'm having major difficulties debugging my program. For some reason, my code only displays 2 and 3 before ending.
#include<stdio.h>
//function declaration
int prime(int);
//main body
int main(void)
{
int x=2, y;
for (x=2;x<=30;x++)
{
y=prime(x);
if (y!=0)
printf("%d\n", x);
}
getchar();
return(0);
}
//function definition
int prime(int x)
{
int y;
for (y=2; y<=(int)sqrt(x); ++y)
{
if (x%y==0)
return 0;
}
if (y==(int)sqrt(x))
return 1;
}
Instead of returning 1 if x is prime, my prime checking function seems to return a random large number (2686xxx) but that shouldn't be an issue because all primes return 0. If I run something like:
if (y==0)
printf("%d\n", x);
I see a list of all non prime numbers. If I run something like:
printf("%d %d\n", x, y);
I see a list of all integers from 2-10,000 and the result of my prime checking function (0 for non-primes, 2686xxx for primes).
Why doesn't the opposite (y!=0) display a list of prime numbers? What is causing my code to stop after just displaying 2 and 3? Why is my prime function returning a weird integer instead of 1? Finally, I'm still a beginner but how can I write better code in general? I don't think I'm breaking any of the standard accepted practices but how can I make my code more clean or efficient?
Thanks in advance for the help!
Your loop continues if y==(int)sqrt(x). So when it finishes, they're not equal. What you wanted is:
if (y>=(int)sqrt(x))
return 1;
But this is not needed at all. Just return 1; is sufficient. You've already returned zero if the number isn't prime.
If you wanted only a single return statement:
int prime(int x)
{
bool isPrime = true;
int y;
for (y=2; y<=(int)sqrt(x); ++y)
{
if (x%y==0)
{
isPrime = false;
break;
}
}
return isPrime;
}
Don't use the sqrt() function. In mathematics if you have 'x = sqrt(y)'. If you square both sides you will get something like this 'x * x = y'. This expression in c is tremendously faster than the sqrt function. Thus instead of doing:
y <= (int)sqrt(x)
Have you for loop guard be something like this:
y * y <= x
Here is a running example of your problem:
Primes 2 -> 10000
At the end of your prime function just return 1. If it wasn't prime it would have returned 0 earlier. Right?
As it is you've made a function which sometimes returns nothing at all. Which means that it returns whatever random value happens to be in the register.
You can use sieve of eratosthenes or sieve of atkin to mark all the prime numbers in an array and then display the prime numbers. It will be time efficient although it incurs some space complexity.
e.g if you want to display prime numbers from 1 to 10
Leave of 1. Its not a prime. Its neither prime nor composite.
So start from 2.
consider this array of size 10 = 2 3 4 5 6 7 8 9 10
Traverse from 2. If an element is not highlighted highlight all its multiples.
i.e for 2 highlight its multiples 4 6 8 10
==> 2 3 4 5 6 7 8 9 10
For 3 do the same
==> 2 3 4 5 6 7 8
9
10
Then do it for the rest of the no.s i.e. 5 and 10 (Here 7 dont have multiple)
Finally print the non highlighted elements. 2,3,5,7.
Repeat this procedure for any other ranges.
Since you are interested in writing computer programs for prime numbers, perhaps you would like to turn this paper into a computer program. It deals with prime numbers and is similar to the sieve you were trying to create in C.
https://graviticpropulsion.files.wordpress.com/2015/04/prime-number-theory.pdf
I'm not sure if it is faster or less memory intensive, but I'm curious myself how high of a prime number it can find before it becomes too intensive for a computer.

Resources