Rough times trying to convert string to integers array [closed] - c

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 6 years ago.
Improve this question
Basically the program will ask for user credit card number, capture it inside a string, convert a string to an integer array (so I can validate credit card number, for later digit sums and multiplying).
I need a variable with integers array and the code below stores ASCII values.
Tried reading lots of posts, but didn't get it.
I'd appreciate any help, so I could sleep again =)
Cordially,
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
string cc_string;
printf("Please enter a credit card number:\n");
//Captures credit card string
cc_string = GetString();
// Array of credit card digits integers
int cc_digits[16];
for (int i = 0; i<= 15; i++)
{
cc_digits[i] = (int) cc_string[i];
//Just checking what value has been stored
printf("position %d with %d \n", i, cc_digits[i]);
}
//to be continued
}

Instead of cc_digits[i] = (int) cc_string[i] try cc_digits[i] = cc_string[i] - '0' If you just cast to int you'll get the ASCII code for the character, but if you subtract the code of character 0 then you should get the actual digit.

Instead of casting to int with (int), use atoi()

Found the solution, want to share with you guys.Thank you all for the help, time and learnings.
#include <cs50.h>
#include <stdio.h>
int main (void)
{
long long cc_num;
int array_dig[15];
int static sum_evens, sum_odds, sum_tot, valid = 0;
printf("Enter your credit card number for validation: \n");
cc_num = GetLongLong();
for (int i=15; i >= 0; i--)
{
array_dig[i] = cc_num % 10;
cc_num = cc_num / 10;
//Sanity check
printf("pos %d = %d\n", i, array_dig[i]);
}
//Summing digits
for (int j=0; j < 16; j++)
{
if (j % 2 == 0)
{
sum_evens += array_dig[j];
//Sanity check
printf("sum_evens = %d/n", sum_evens);
}
else if (j % 2 == 1)
{
if (array_dig[j] < 5)
{
sum_odds += 2 * array_dig[j];
//Sanity check
printf("sum_odds for char < 5 = %d\n", sum_odds);
}
else
{
sum_odds += (2 * array_dig[j]) % 10 + 1;
//Sanity check
printf("sum_odds for char >= 5 = %d\n", sum_odds);
}
}
}
sum_tot = sum_evens + sum_odds;
//Validation (if sum % 10 = 0 it is valid)
valid = sum_tot % 10;
printf("sum_tot = %d, valid = %d \n", sum_tot, valid);
if (valid % 10 == 0)
{
printf("Valid credit card \n");
}
else
{
printf("Invalid credit card\n");
}
}

Not so soon. =(
Program looses precision when passes values (digits) to the long long variable cc_num.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
long long cc_num;
char cc_num_str[15];
int static sum_evens, sum_odds, sum_tot, valid = 0;
int static size;
do
{
printf("Enter your credit card number for validation: \n");
cc_num = GetLongLong();
sprintf(cc_num_str, "%lld", cc_num);
size = strlen (cc_num_str);
}
while (cc_num < 1 || cc_num > 9999999999999999 || size < 13 || size > 16);
int array_dig[size];
for (int i = size - 1; i >= 0; i--)
{
array_dig[i] = cc_num % 10;
cc_num = cc_num / 10;
//Sanity check
printf("pos %d = %d\n", i, array_dig[i]);
}
//Summing digits
for (int j=0; j < size; j++)
{
if (j % 2 == 0)
{
sum_evens += array_dig[j];
//Sanity check
printf("sum_evens = %d/n", sum_evens);
}
else if (j % 2 == 1)
{
if (array_dig[j] < 5)
{
sum_odds += 2 * array_dig[j];
//Sanity check
printf("sum_odds for char < 5 = %d\n", sum_odds);
}
else
{
sum_odds += (2 * array_dig[j]) % 10 + 1;
//Sanity check
printf("sum_odds for char >= 5 = %d\n", sum_odds);
}
}
}
sum_tot = sum_evens + sum_odds;
//Validation (if sum % 10 = 0 it is valid)
valid = sum_tot % 10;
printf("sum_tot = %d, valid = %d \n", sum_tot, valid);
if (valid % 10 == 0)
{
//code that will verifies card type (to be written)
printf("Valid credit card \n");
}
else
{
printf("Invalid. \n");
}
return 0;
}
Here is the output:
Enter your credit card number for validation:
1234567809874366
pos 15 = 8
pos 14 = 3
pos 13 = 6
pos 12 = 9
pos 11 = 5
pos 10 = 8
pos 9 = 9
pos 8 = 0
pos 7 = 8
pos 6 = 7
pos 5 = 6
pos 4 = 5
pos 3 = 4
pos 2 = 3
pos 1 = 2
pos 0 = 1
sum_evens = 1/nsum_odds for char < 5 = 4
sum_evens = 4/nsum_odds for char < 5 = 12
sum_evens = 9/nsum_odds for char >= 5 = 15
sum_evens = 16/nsum_odds for char >= 5 = 22
sum_evens = 16/nsum_odds for char >= 5 = 31
sum_evens = 24/nsum_odds for char >= 5 = 32
sum_evens = 33/nsum_odds for char >= 5 = 35
sum_evens = 36/nsum_odds for char >= 5 = 42
sum_tot = 78, valid = 8
Invalid.

Related

The code runs well but I'm a beginner and I want to make it more user friendly just out of curiosity.... How to make it more user friendly?

#include<stdio.h>
int main(){
int i, n;
long sum=0;
puts("Enter the number: ");
scanf("%d", &n);
for(i=1; i<=n; i++){
sum = sum + (i * i);
printf("(%d * %d) = %d\n", i, i, (i*i) );
}
printf("\nThe sum of the series is %ld\n", sum);
return 0;
}
suppose I enter the input as 5, then the operation goes like this 1 * 1 = 1, 2 * 2 = 4, 3 * 3 = 9, 4 * 4 = 16, 5 * 5 = 25..... and then, I want to show the sum of every individual product...
I want the output to be like this:
(1 * 1) = 1
(2 * 2) = 4
(3 * 3) = 9
(4 * 4) = 16
(5 * 5) = 25
The sum of the series is 1 + 4 + 9 + 16 + 25 = 55
For a start, you can do it in the loop itself:
printf("\nThe sum of the series is ");
for (i = 1; i <= n; i++){
sum = sum + (i * i);
// Don't print a leading + for the first number to avoid
// "The sum of the series is + 1 + 4 + 9 + 16 + 25 = 55"
if (i > 1) {
printf(" + ");
}
// Print the current term
printf("%d", i * i);
}
printf(" = %ld\n", sum);
This outputs, for
n = 2:
The sum of the series is 1 + 4 = 5
n = 5:
The sum of the series is 1 + 4 + 9 + 16 + 25 = 55
But it also outputs, for
n = 0:
The sum of the series is = 0
n = 1:
The sum of the series is 1 = 1
Handling user input is up to you.
If you also wants to output the middle terms, you can iterate over the terms twice:
for (int i = 1; i <= n; i++){
sum = sum + (i * i);
printf("(%d * %d) = %d\n", i, i, i*i);
}
printf("The sum of the series is ");
for (int i = 1; i <= n; i++){
if (i > 1) printf(" + ");
printf("%d", i*i);
}
printf(" = %ld.\n", sum);
Outputs
(1 * 1) = 1
(2 * 2) = 4
(3 * 3) = 9
(4 * 4) = 16
(5 * 5) = 25
The sum of the series is 1 + 4 + 9 + 16 + 25 = 55.
Here's my attempt at your requirements.
I saved every product in its own array during the loop, then print them one by one again in the final line.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned i, n; // no negative numbers used
long unsigned sum = 0;
long unsigned parcel[2000]; // could use VLA or dynamic memory
printf("Enter the number: "); // write the input on the
fflush(stdout); // same line as the prompt
if (scanf("%u", &n) != 1) {
fprintf(stderr, "Input error.\n");
exit(EXIT_FAILURE);
}
if (n > 2000) {
fprintf(stderr, "Sorry, max number is 2000.\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) { // I like to start for loops at 0
long unsigned product = (i + 1) * (i + 1);
sum = sum + product;
printf("(%u * %u) = %lu\n", i + 1, i + 1, product);
// save product for final output
parcel[i] = product;
}
printf("\nThe sum of the series is %lu", parcel[0]);
// exception for starting for loops at 0: the 0th element was printed above
for (i = 1; i < n; i++) printf(" + %lu", parcel[i]);
printf(" = %lu\n", sum);
return 0;
}
There is a few things you could do just as a suggestion for beginner legibility
sum = sum + (i * i);
i*i can be pulled out to
int iSquared = i * i;
then store
int nextProduct = sum + iSquared;
and finally simplify the summation with
sum += nextProduct
Bringing it all together you'd have
#include<stdio.h>
int main(){
int i, n;
long sum=0;
puts("Enter the number: ");
scanf("%d", &n);
for(i=1; i<=n; i++){
int iSquared = i * i;
int nextProduct = sum + iSquared;
sum += nextProduct;
printf("(%d * %d) = %d\n", i, i, iSquared);
}
printf("\nThe sum of the series is %ld\n", sum);
return 0;
}
It's highly debatable if this is more user friendly honestly, but I still think it's more clear to have each step broken out logically especially when first trying to learn C++ or programming in general.

for loop unexpectedly jumping down in value

Goldbach's conjecture states that every even integer over 4 is the sum of two primes, I am writing a program in C to find these pairs. To do this it first finds all the primes less than a user given number. I have a for loop to iterate from 4 to the user given number and find the pairs within the loop body. When that loop gets to about around 40, suddenly jumps back down by about 30 and then continues to iterate up (with user input 50 it jumped from 38 to 9, with input 60 it jumped from 42 to 7). I can't figure out why this is happening. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <unistd.h>
struct pair{
int a;
int b;
}pair_t;
int main(){
int N;
int numPrimes = 1;
int *primes = malloc(100*sizeof(int));
int isPrime = 1;
primes[0] = 2;
int timesRealloc = 0;
int availableSlots = 100;
printf("Please enter the largest even number you want to find the Goldbach pair for: \n");
scanf("%d", &N);
struct pair pairs[N/2 + 4];
int j = 0;
int i;
for (i = 3; i <= N; i+=2){
j = 0;
isPrime = 1;
while (primes[j] <= sqrt(i)) {
if (i%primes[j] == 0) {
isPrime = 0;
break;
}
j++;
}
if (isPrime == 1){
primes[numPrimes] = i;
numPrimes++;
}
if (availableSlots == numPrimes){
timesRealloc++;
availableSlots += 100;
primes = realloc(primes, availableSlots*sizeof(int));
}
}
printf("The largest prime I found was %d\n", primes[(numPrimes-1)]);
int k;
for (i=4; i<=N; i+=2){
printf("i is %d, N is %d\n", i, N);
if (i > N){ break; }
for (j=0; j<numPrimes; j++){
for (k=0; k<numPrimes; k++){
int sum = primes[j] + primes[k];
if(sum == i){
pairs[i].a = primes[j];
pairs[i].b = primes[k];
}
}
}
}
for (i=4; i<=N; i+=2){
printf("%d is the sum of %d and %d\n", i, pairs[i].a, pairs[i].b);
}
return 0;
}
You attempt to be space efficient by compressing the pairs array to just hold every other (even) number and start from 4 instead of zero. However, you miscalculate its size and then when you go to use it, you treat it like it hasn't been compressed and that there's a slot for every natural number.
The code suffers from having the prime array calculation in main() along with the other code, this is best separated out. And when it looks for pairs, it doesn't quit when it finds one, nor when it starts getting sums greater than the target. My rework below attempts to address all of these issues:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define INITIAL_SLOTS (100)
struct pair {
int a;
int b;
} pair_t;
int compute_primes(int limit, unsigned **primes, int size) {
int numPrimes = 0;
(*primes)[numPrimes++] = 2;
for (int i = 3; i <= limit; i += 2) {
bool isPrime = true;
for (int j = 0; (*primes)[j] <= i / (*primes)[j]; j++) {
if (i % (*primes)[j] == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
(*primes)[numPrimes++] = i;
}
if (numPrimes == size) {
size *= 2;
*primes = realloc(*primes, size * sizeof(unsigned));
}
}
return numPrimes;
}
int main() {
int N;
printf("Please enter the largest even number you want to find the Goldbach pair for: \n");
scanf("%d", &N);
unsigned *primes = calloc(INITIAL_SLOTS, sizeof(unsigned));
int numPrimes = compute_primes(N, &primes, INITIAL_SLOTS);
printf("The largest prime I found was %d\n", primes[numPrimes - 1]);
struct pair pairs[(N - 4) / 2 + 1]; // compressed data structure
for (int i = 4; i <= N; i += 2) {
int offset = (i - 4) / 2; // compressed index
bool found = false;
for (int j = 0; ! found && j < numPrimes; j++) {
for (int k = 0; ! found && k < numPrimes; k++) {
int sum = primes[j] + primes[k];
if (sum == i) {
pairs[offset].a = primes[j];
pairs[offset].b = primes[k];
found = true;
} else if (sum > i) {
break;
}
}
}
}
for (int i = 4; i <= N; i += 2) {
int offset = (i - 4) / 2; // compressed index
printf("%d is the sum of %d and %d\n", i, pairs[offset].a, pairs[offset].b);
}
free(primes);
return 0;
}
OUTPUT
> ./a.out
Please enter the largest even number you want to find the Goldbach pair for:
10000
The largest prime I found was 9973
4 is the sum of 2 and 2
6 is the sum of 3 and 3
8 is the sum of 3 and 5
10 is the sum of 3 and 7
12 is the sum of 5 and 7
14 is the sum of 3 and 11
...
9990 is the sum of 17 and 9973
9992 is the sum of 19 and 9973
9994 is the sum of 53 and 9941
9996 is the sum of 23 and 9973
9998 is the sum of 31 and 9967
10000 is the sum of 59 and 9941
>

Split digits in array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm totally beginner and I have problem in C. So I have array:
A[5] = {14, 2, 7, 3, 2};
And I want make something like this:
A[6] = {1, 4, 2, 7, 3, 2};
From 14 to 1, 4. Any idea how to do that?
So I making the problem from Cs50. Here is a link: https://docs.cs50.net/2018/x/psets/1/credit/credit.html
And here is my code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <math.h>
int main(void)
{
long long cc_number = 0;
do
{
printf("Number: ");
cc_number = get_long_long();
}
while(cc_number <= 0);
int num_of_digits = 0;
long long valid = cc_number;
while(valid > 0)
{
valid /= 10;
num_of_digits++;
}
if (num_of_digits != 13 && num_of_digits != 15 && num_of_digits != 16 ) //checking if number have more or less than 13,15,16 digits
{
printf("Number is invalid!\n");
}
long long k = 1; //create array for store each number from the card
int A[16], d, num = 0;
for(num = 0; num < 16; num++)
{
d = (cc_number/(1*k)) % 10;
A[num] = d;
k *=10;
}
///////////////////////////////////////////////////////////////////////
if (num_of_digits == 16)
{
for (int i = 0; i < 16; i = i + 2)
{
A[i] *= 2; // multiplay each second digit by 2
printf("this is %i\n", A[i]);
}
}
else if (num_of_digits == 15 || num_of_digits == 13 )
{
int sum = 0;
for (int i = 1; i < 15; i = i + 2)
{
int y = A[i];
A[i] *= 2; // multiplay each second digit by 2
if (A[i] > 9) // try to split digit from array
{
y = A[i] % 10;
A[i] /= 10;
}
sum += A[i];
printf("this is %i\n", A[i]);
}
printf("this is sum %i\n", sum);
}
///////////////////////////////////////////////////////////////////////////
}
And this is what i want to do:
For the sake of discussion, let’s first underline every other digit,
starting with the number’s second-to-last digit:
378282246310005
Okay, let’s multiply each of the underlined digits by 2:
7•2 + 2•2 + 2•2 + 4•2 + 3•2 + 0•2 + 0•2
That gives us:
14 + 4 + 4 + 8 + 6 + 0 + 0
Now let’s add those products' digits (i.e., not the products themselves) together:
1 + 4 + 4 + 4 + 8 + 6 + 0 + 0 = 27
Now let’s add that sum (27) to the sum of the digits that weren’t multiplied by 2:
27 + 3 + 8 + 8 + 2 + 6 + 1 + 0 + 5 = 60
Yup, the last digit in that sum (60) is a 0, so my card is legit!
Assuming you want to create an array of single digit integers from array of multi-digit integers
#include <stdio.h>
#define MAX 1024
void printarr(int *a, int n) { // function to print array
for(int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
int main() {
int a[5] = {14, 2, 7, 3, 2};
int b[MAX];
int k = 0;
printarr(a, 5);
char s[MAX]; // char buffer to store char array
for(int i = 0; i < 5; i++) {
sprintf(s, "%d", a[i]);// convert int to char array
int j = 0;
while(s[j]!='\0') { // for each digit, create a new integer
b[k++] = s[j++] - '0';
}
}
printarr(b, k);
return 0;
}
Output:
14 2 7 3 2
1 4 2 7 3 2
Else for specific case
#include <stdio.h>
#define MAX 1024
void printarr(int *a, int n) { // function to print array
for(int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
int main() {
int a[5] = {14, 2, 7, 3, 2};
int b[6];
printarr(a, 5);
b[0] = 1;
b[1] = 4;
for(int i = 2; i < 6; i++) {
b[i] = a[i - 1];
}
printarr(b, 6);
return 0;
}
Output:
14 2 7 3 2
1 4 2 7 3 2
Here is a solution that does not use strings.
First of all, we have to determine how long the new array will be. To this end, we determine how many digits each entry has. For n > 0 the number of digits is ⌊log10(n) + 1⌋.
After that, we extract the digits. 123 can be split into its digits by using integer division / and modulo % (remainder of integer division):
123 % 10 = 3 least significant digit
123 / 10 = 12
repeat
12 % 10 = 2 second least significant digit
12 / 10 = 1
repeat
1 % 10 = 1 third least significant digit
1 / 10 = 0
end
As you can see, the digits are extracted from the back, therefore we also fill the output array from the back.
#include <stdio.h>
#include <math.h>
int digitCount(int n) {
if (n)
return (int) log10(n) + 1;
return 1;
}
int main() {
int inputLength = 5;
int input[] = {14, 1, 9, 0, 5819};
int outputLength = 0;
for (int i = 0; i < inputLength; ++i)
outputLength += digitCount(input[i]);
int output[outputLength];
int o = outputLength;
for (int i = inputLength - 1; i >= 0; --i) {
int n = input[i];
do {
output[--o] = n % 10;
n /= 10;
} while (n);
}
while (o < outputLength) {
printf("%d ", output[o++]);
}
}
clang -lm file.c && ./a.out prints 1 4 1 9 0 5 8 1 9.

How do I find matching values within an array and store them in a new array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I can find duplicate values in an array, however the program gets stuck when I have more than 2 sets of duplicating values.
So for example, if I give the input:
10 1 2 3 4 5 10 10 10 10 10
(note the first digit [10] indicates how many numbers are in the array, and it is assumed all number will be in ascending order)
I get the correct score output of
Run {10,10,10,10,10} scoring 50.
(runCount (5) * runNumber (10) = 50)
If I have more than 2 repeating elements in the array, for example -
10 5 5 5 5 5 10 10 10 10 10
the scores are all muddled
Run {5,10,10,10,10,5,5,5,5} scoring 45.
As the scores for {5,5,5,5,5} should be lower than {10,10,10,10,10}, ideally, the program would print the values with the highest score.
Run {10,10,10,10,10} scoring 50.
How do I make it so it only uses the highest values? I couldn't quite get the break function to work correctly.
Please let me know if you have any ideas? My code is below.
I can only use arrays, loops, and if/else
//Game that calculates the highest score based on array inputs
#include <stdio.h>
#define MAX_PLAYERS 13
#define TRIPLE 3
int main(void) {
int nPlayers, i, j, k;
int gameNumbers[MAX_PLAYERS];
int runCount, runCounter, runNumber, runScore;
int runScores[MAX_PLAYERS] = {0};
//read in numbers
scanf("%d", &nPlayers);
i = 0;
while (i < nPlayers) {
scanf("%d", &gameNumbers[i]);
i = i + 1;
}
//Calculates Run Scores
//A run is when there are duplicates of the same number in a row
runCounter=0;
runNumber=0;
runScore=0;
j=0;
for (i=(nPlayers-1); i>=1; i--) {
if(gameNumbers[i] - gameNumbers[i-1] == 0) { //compares highest number to previous number to find equality
runScores[j]=gameNumbers[i];
j++;
runCounter++;
runCount=(runCounter+1);
runNumber=(gameNumbers[i]);
runScore=(runCount*runNumber);
}
}
//Run Score
printf("runCounter:%d, runCount=%d, runNumber=%d, runScore=%d\n", runCounter, runCount, runNumber, runScore);
printf("runScores[]=");
i=0;
while (i<runCount) {
printf("%d ", runScores[i]);
i++;
}
printf("\n");
//Print run scores
printf("Run {%d", runNumber);
j=0;
while (j < runCounter) {
printf(",%d", runScores[j]); //loop prints remainder of the stored run scores array
j++;
}
printf("} scoring %d.\n", runScore);
return 0;
}
Like this:
#include <stdio.h>
#include <limits.h>
int main(void){
int n;
scanf("%d", &n);
int numbers[n];
for(int i = 0; i < n; ++i) {
scanf("%d", &numbers[i]);
}
int hi_score = INT_MIN, dupCount = 0 , theNumber;
for(int i = 0; i < n; ++i){
int counter = 0, score;
for(int j = i + 1; j < n && numbers[i] == numbers[j]; ++j){
++counter;
}
if(counter > 0){
score = (counter + 1) * numbers[i];
if(hi_score <= score){//= : when 4 4 4 4 4 5 5 5 5, 4 < 5
theNumber = numbers[i];
dupCount = counter + 1;
hi_score = score;
}
i += counter;
}
}
if(dupCount > 0){
int new_array[dupCount];
printf("Run {");
for(int i = 0; i < dupCount; ++i){
if(i)
putchar(',');
printf("%d", new_array[i] = theNumber);
}
printf("} scoring %d.\n", hi_score);
}
return 0;
}
Or try sth like this:
#include<stdio.h>
#include<stdlib.h>
void generateScore(int*, int , int* , int* );
int main(){
int number = 0;
int times = 0;
int array[10] = {10, 10, 10, 10, 10, 4, 4, 10, 10, 10};
generateScore(array, 10, &number, &times);
printf("number: %d \t times:%d", number, times);
return (0);
}
void generateScore(int* array, int size, int* number, int* times) {
*number = array[0];
*times = 1;
int i;
for(i = 1 ; i < size && array[i] == *number; i++) {
*times = *times + 1 ;
}
if(size <= i) {
return;
}
int number2 = array[i];
int times2 = 1;
i++;
for(; i < size; i++){
if(array[i] == number2){
times2 = times2 + 1;
} else {
if((*times * (*number)) < (number2 * times2)) {
*times = times2;
*number = number2;
}
number2 = array[i];
times2 = 1;
}
}
if((*times * (*number)) < (number2 * times2)) {
*times = times2;
*number = number2;
}
}
int array[10] = {5 5 5 5 5 10 10 10 10 10};
generateScore(array, 10, &number, &times);
void generateScore(....){
int sum=0;
int preSum=0;
int index=-1;
int k;
for(i=0;i<size;i++)
{
k=i;
sum=0;
while(((k+1)<size)&&(array[k]==array[k+1]))
{
sum=sum+array[k];
k=k+1;
}
if(sum>presum){
index=k-1;
presum=sum;
}
i=k;
}
var num = presum/array[index];
//now your sum in presum which is present num times in your array whose last index in array is index
}
for more see here

Sub Grouping algorithm

Recently, someone asked me to make a C program that "groups" (his words, not mine!) numbers into pairs.
Here's how it works.
First, the user inputs the maximum range:(let's say) 10
Now, user inputs a number: (let's say) 4.
Then, the program groups 4 and 5 together. (ie. n and n+1)
Next User Input: 8
The program groups 8 and 9 as well.
Now, this goes on.
Exceptions: If the user enters a number that has already been grouped, like 4,5,8 or 9. Then the group which it belongs to gets removed altogether. Also, the program invalidates inputs that require pairing with numbers that are already paired. Eg. If 4 and 5 are paired, 3 is not a valid input.
Also, entering the extremes (here, 1 and 10) is not allowed.
I made the above program in C, using Visual Studio 2013. I have provided the code below.
My questions are:
A) How could I have made my code considerably better?(Apart from initializing the array AFTER accepting the max input)
B) More importantly, can someone tell me what this algorithm is? Is this a standard problem? Does it have any real world application/implementation? Or is it just some random idea?
#include<stdio.h>
#inlcude<conio.h>
#define array_size 10
int group[array_size][2] = { 0 };
int n = 0, max=0, search = 0, max_mem = 0;
int tcount = 2;
void sort(int x[][2]);
void print_groups();
void test_print();
void main()
{
group[0][0] = 0;
group[0][1] = 1;
printf("Enter a number:");
scanf_s("%d", &max);
max_mem = (max/2)+1;
if (max_mem > array_size)
{
printf("Not enough memory assigned!");
return;
}
else
{
group[max_mem-1][0] = max;
}
print_groups();
test_print();
while (1)
{
printf("Enter a number:");
scanf_s("%d", &n);
if ((n <= 1) || (n >= max-1))
{
printf("Invalid entry!");
continue;
}
search = 0;
for (int i = 1; i < max_mem; i++)
{
for (int j = 0; ((j < 2)&&(search!=1)); j++)
{
if (n == group[i][j])
{
group[i][0] = 0;
group[i][1] = 0;
search = 1;
}
if (group[i][0]==n+1)
{
printf("Already group exists -> (%d,%d)", group[i][0], group[i][1]);
//getch();
search = 1;
}
}
}
if (search != 1)
{
group[1][0] = n;
group[1][1] = n + 1;
}
printf("\nSorting!\n");
sort(group);
//clrscr();
print_groups();
test_print();
}
}
void sort(int x[][2])
{
int i, j, t[1][2];
for (i = 1; i <= max_mem - 2; i++)
for (j = 2; j <= max_mem-1 - i; j++)
if (x[j - 1][0] >= x[j][0])
{
t[0][0] = x[j - 1][0];
x[j - 1][0] = x[j][0];
x[j][0] = t[0][0];
t[0][1] = x[j - 1][1];
x[j - 1][1] = x[j][1];
x[j][1] = t[0][1];
}
}
void print_groups()
{
printf("The group is:\n%d ", group[0][1]);
for (int i = 1; i < max_mem-1; i++)
{
if (group[i][0] != 0)
{
printf("(");
printf("%d,", group[i][0]);
printf("%d", group[i][1]);
printf(")");
}
}
printf(" %d.", group[max_mem - 1][0]);
printf("\n");
}
void test_print()
{
printf("Array Formation:\n");
for (int i = 0; i < array_size; i++)
{
printf(" %d,%d ", group[i][0], group[i][1]);
}
printf("\n");
}
Sounds like it's just some random idea. You can simplify your code by using a one-dimensional array, where each entry in the array is
0 for numbers not in a group
1 for the first number of a group
2 for the second number of a group
For example, if array[4] is 1 and array[5] is 2, then 4 and 5 are a group.
When the user enters a new number, it's easy to update the array. Here's an example in pseudo-code of how the array would be updated if the user enters the number 7
if (array[7] == 0 and array[8] == 0)
array[7] = 1, array[8] = 2
else if (array[7] == 0 and array[8] == 1)
input is invalid
else if (array[7] == 1)
array[7] = 0, array[8] = 0
else if (array[7] == 2)
array[6] = 0, array[7] = 0

Resources