Serial numbers of equal numbers next to each other in array - c

#include <stdio.h>
void main(){
int i, j, n;
int num[5];
int serial;
for(i=0; i<5; ++i){
scanf("%d",&num[i]);
if(num[i]==num[i-1])
serial=i;
else
continue;
}
printf("Serial number of equal numbers next to each other:%d. %d.", serial-1, serial);
}
This may be hard to understand because I'm not a native English speaker.
If the numbers next to each other are equal the program should print the serial number of those numbers.
For example:
Input: 1 2 3 7 7 7 6;
Output: 3. 4. 5.
Input: 5 5 5 5 5
Output: 0. 1. 2. 3. 4.
I made some changes now it prints the serial of two equal numbers.
I: 1 2 2 3 4 - O: 1. 2.
But what if all the numbers are equal?

// ...
// deal with index 0
if (num[0] == num[1]) printf("0. ");
// deal with indexes 1 .. N - 2
for (int k = 1; k < n - 1; k++) {
if ((num[k - 1] == num[k]) || (num[k] == num[k + 1])) {
printf("%d. ", k);
}
}
// deal with index N - 1
if (num[n - 2] == num[n - 1]) printf("%d. ", n - 1);
// ... possibly with a printf("\n"); somewhere

You can solve this without storing the numers in an array, but you must keep track of how many equal numbers have been read before reading the present one:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i = 0; // running index
int prev = 0; // previously read number
int iprev = 0; // start of range of equal numbers previously read
int n; // currently read number
while (scanf("%d", &n) == 1) {
if (n != prev) {
if (i - iprev > 1) {
while (iprev < i) printf("%d\n", iprev++);
}
iprev = i;
prev = n;
}
i++;
}
if (i - iprev > 1) {
while (iprev < i) printf("%d\n", iprev++);
}
return 0;
}
You consider stretches of equal numbers only after you read a number that terminates the current range of equal numbers. When all numbers are different, the size of that range is 1 and we don't print anything. If the range is larger than 1, print all indices in question.
Because you don't notice a change after reading the last number, you must check the last range separately after the main loop.

If you can put a non-numeric character in the [0] element of your array, you won't need a different test for the first element
int main (void)
{
/* non-numeric in position 0 of data array */
char myList[] = {'.','1','2','2','3','4','4','4','5','6','6'};
int listSz = strlen(myList) -1;
int n;
/* check everything except last */
for (n = 1; n < listSz; n++) {
if(( myList[n] == myList[n +1]) || ( myList[n] == myList[n -1] )) {
printf("%d . ", n);
}
}
/* check last */
if( myList[listSz] == myList[listSz -1] ) {
printf("%d", n);
}
printf("\n");
}
Output: 2 . 3 . 5 . 6 . 7 . 9 . 10

Related

How can print numbers is separate lines?

The question to solve is that this code should get numbers in separate lines until 0 is given. Then it should print y number, y times. For example if number 3 is given, it should print 3, 3 times in separate lines.
I try to get the inputs from the user in separate lines. I mean one input in one line. Then print the numbers in separate lines. I don't know where to add \n to solve it.
This is my code:
#include <stdio.h>
int main() {
int y = 1;
while (y != 0) {
scanf("%d", &y);
if (y == (0)) {
break;
}
for (int i = 1; i <= y; i++) {
printf("%d\n", y);
}
}
}
I tried to add \n beside %d of scanf but it didn't work as I expected.
The output of this code is like this:
1
1
2
2
2
3
3
3
3
4
4
4
4
4
0
What I expect is that all the inputs should be given in separate lines before output is printed.
input like this:
1
2
3
4
0
output like this:
1
2
2
3
3
3
4
4
4
4
As #DavidC.Rankin explains below, if you want to retain the input it means you have to store it somewhere. It's usually in memory and either the original input string (char []) or you store the data in a format suitable for output like int input[LEN] that I use below.
Other options includes using a recursive function to store one number on the stack, or a file or an external service like a database (possible hosted in the cloud these days).
#include <stdio.h>
#define LEN 5
int main(void) {
// input
int input[LEN];
int i = 0;
for(; i < LEN; i++) {
if(scanf("%d",input + i) != 1) {
printf("scanf failed\n");
return 1;
}
if(!input[i])
break;
}
// output (copy of input other than 0)
for(int j = 0; j < i; j++) {
printf("%d\n", input[j]);
}
// output (repeated based on input)
for(int j = 0; j < i; j++) {
for(int k = 0; k < input[j]; k++) {
printf("%d\n", input[j]);
}
}
}
and example run:
1 # input
2
3
4
0
1 # output (copy of input other than 0)
2
3
4
1 # output (repeated based on input)
2
2
3
3
3
4
4
4
4
Here is the as close you can get with a recursive function and no arrays:
#include <stdio.h>
#include <stdlib.h>
void read_then_print() {
// input
int d;
if(scanf("%d", &d) != 1) {
printf("scanf failed\n");
exit(1);
}
if(d) {
// output before recursion
printf("%d\n", d);
read_then_print();
}
// output after recursion
for(int i = 0; i < d; i++) {
printf("%d\n", d);
}
}
int main(void) {
read_then_print();
}
and example session:
1 # input
1 # output before recursion
2 # input
2 # output before recursion
3 # ...
3
4
4
0
4 # output after recursion
4
4
4
3
3
3
2
2
1
#include<stdio.h>
int main()
{
int y;
do
{
scanf("%d",&y);
for(int i = 1;i <= y;i++)
{
printf("%d\n", y);
}
}while(y != 0);
}
Use this one this might solve your problem.
You want to gather all the input before processing the lines and printing the results. You can use an array to store the input numbers and process them once you read a 0.
Here is a modified version with this approach:
#include <stdio.h>
#define MAX_LINES 256
int main() {
int input[MAX_LINES];
int y, n = 0;
while (n < MAX_LINES && scanf("%d", &y) == 1 && y != 0) {
input[n++] = y;
}
for (int i = 0; i < n; i++) {
y = input[i];
for (int i = 0; i < y; i++) {
printf("%d\n", y);
}
}
return 0;
}

I don't understand why my for loop gives an awkward output

unfortunately... I asked about exactly this question yesterday about another error, hopefully, I don't have those errors anymore but I still have this awkward output, like some sort of numbers depending on the array element like -4221565 or -4647963, etc... Until now I think that my array appending part works correctly, I tried that. But I guess something wrong about the -1 in the condition but I can't name it. For loop is also another place I would say ok. I am trying to solve this since 3.00 AM then procrastinate it, then tried it... And the deadline is 7.04.2020(TODAY) 22.00 so I am starting to getting crazy. Any help would be appreciated.Thanks.So this is the question(İnputs does not have to be 15 it can be up to 15):
You have to transport a maximum of 15 different loads from one port to another. The carrying capacity of a cargo ship, which will transport those loads, is 50 tons. Loads are enumerated and the information about the weight of every load is given as input.
Suppose that the weight of every load is smaller than or equal to 50 tons and greater than 0.
You will read the weight of every load from the input in a single line. Your input will end with a -1. You will print the number of trips necessary.
Sample Input:
50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 -1
Output:15
Input:
20 25 25 36 37 25 20 10 50 9 16 45 32 10 25 -1
Output:
11
Input:
14 16 50 10 10 19 45 40 32 24 25 47 10 12 25 -1
Output:
9
Input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -1
Output:
3
Here is my code:
#include <stdio.h>
int main()
{ int w,i,sum,index;
int list[15];
w = 1;
index = 0;
do
{ scanf("%d",&w);
list[index] = w;
index++;
}while(w != -1);
sum = 0;
for(i = 0;i < 15;i++)
{
sum +=list[i];
}
sum = sum / 50;
printf("%d",sum);
return 0;
}
in your code you are passing boundaries of array -1 will be 16th element of array which wrong. you need at least int list[16];.
but your solution is wrong , you are divining loads to place them in cargo ship which judging by given input and output. for example if there are 30 and 10 in one ship you can't divide a 20 load to two 10 loads in order to place max of 50 ton in the ship.
what you need is :
consider a ship with 0 ton
add load to it while sum of load are lower or equal to 50
if with new load added sum of current ship goes upper than 50 counter_ship++ and then add that load to a new load.
int main(void) {
int w;
int sum = 0;
int ship_counter = 0;
scanf("%d", &w);
while (w != -1) {
if (sum + w > 50)
{
ship_counter++;
sum = 0;
}
sum += w;
scanf("%d", &w);
}
if (sum != 50)
ship_counter++;
printf("%d", ship_counter);
return 0;
}
You need to sort the array. Then you need to check against a threshold amount. If it surpasses that you add a container.
#include <stdio.h>
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// Function to perform Selection Sort
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 2; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n-1; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element
// with the first element
swap(&arr[min_idx], &arr[i]);
}
}
int main()
{ int w,i,sum,index;
int list[15];
w = 1;
index = 0;
do
{ scanf("%d",&w);
list[index] = w;
index++;
}while(w != -1);
selectionSort(list,index);
for (int i = 0; i < index; i++)
printf("%d ", list[i]);
printf("\n");
int ans=0;
int threshold=0;
for(int i=0; i<index; ++i){
if(threshold + list[i]<=50){
threshold+=list[i];
}
else {
threshold = list[i];
++ans;
}
}
ans++;
printf("%d", ans);
return 0;
}
Change the do-while loop to a while like this:
while(w != -1 && index < 15)
{ scanf("%d",&w);
list[index] = w;
index++;
}
This way you avoid writing beyond array's boundary.
Then, the condition of the for loop could be:
for(i = 0;i < index; i++)
(value of index comes from the previous loop, and it's only up to the next item of the last inserted).
So you 're summing up the items that actually had an input, not the whole array.
Of course you could do without an array, as others commented.
Hope that helps
Your code has several issues, and I didn´t felt well to improve what still got logical issues in it, so I do something I normally do not (because apparently you seem to be very stressed about that and you are in a hurry) and provide you my own version of how I did the task:
#include <stdio.h>
#define MAX_LOADS 15
#define MAX_CAP 50
int main()
{
int w[MAX_LOADS+1];
int trips = 0;
int i = 0;
int sum = 0;
int max = 0;
int loads = 0;
int rest = 0;
printf("Enter the Weights of the Loads:\n");
while(i < (MAX_LOADS + 1))
{
scanf(" %d",&w[i]);
printf(" ");
if(w[i] == -1)
{
break;
}
sum = sum + w[i];
loads++;
i++;
}
printf("\n");
printf("%d Loads have a weight of %d tons.\n", loads, sum);
if(sum <= MAX_CAP)
{
printf("The amount of needed trips are: 1");
}
else
{
for(int i = 0; i < loads; i++)
{
if(w[i] == MAX_CAP)
{
w[i] = 0;
trips++;
continue;
}
else if(w[i] < MAX_CAP && w[i] > 0)
{
rest = MAX_CAP - w[i];
w[i] = 0;
for(int j = 0; j < loads; j++)
{
if(i == j)
continue;
if(w[j] == rest)
{
w[j] = 0;
break;
}
else if(w[j] < rest && w[j] > 0)
{
rest = rest - w[j];
w[j] = 0;
}
if(rest == 0)
{
break;
}
}
trips++;
}
}
printf("The amount of needed trips are: %d", trips);
}
return 0;
}
Output / Execution 1:
Enter the Weights of the Loads:
10 20 40 -1
3 Loads have a weight of 70 tons.
The amount of needed trips are: 2
Output / Execution 2:
Enter the Weights of the Loads:
50 50 50 50 50 -1
5 Loads have a weight of 250 tons.
The amount of needed trips are: 5
Output / Execution 3:
Enter the Weights of the Loads:
10 10 10 10 10 -1
5 Loads have a weight of 50 tons.
The amount of needed trips are: 1
#include <stdio.h>
#define MAX_SIZE 15
int main()
{
/* Let's define variables here. */
int i=0,j=0 ;
int input;
int weights[MAX_SIZE];
int numberOfTrips = 0;
int sum = 0;
/* Inputs is taken here from usre, Max = 15 */
printf("Input:\n");
scanf("%d",&input);
while(input != -1){
if (i< MAX_SIZE){
if (input <= 50 && input>= 0){
weights[i] = input;
i = i +1;
} else printf("Wrong Input! \nPlease Enter value between 0 and 50\n");
}
else printf("You reach MAX_SIZE, please Enter -1 to see the Output");
scanf("%d",&input);
}
printf("\n");
/* We are going will count the number of trips necessary*/
if(input == -1){
if (weights[0] != 0){
/* Let's test the first value*/
numberOfTrips = numberOfTrips +1;
}
sum= weights[0];
for (j = 1; j<i; ++j){
sum = sum +weights[j];
if (sum>50){
numberOfTrips = numberOfTrips +1;
sum = weights[j];
}
}
}
/*Finally, let's print the output here.*/
printf("Output:\n");
printf("%d",numberOfTrips);
return 0;
}

I want to get the inverse of an array while the user input the value

I create a program that get the input of array element size of 10. Everything getting will with the sum of even and odd number. but when it comes to the inverse it didn't work.
i created two arrays where the first getting the value from the user and second copying the element starting from end of the first array..
#include <stdio.h>
int main (){
int array[10] , i , odd =0 , even =0;
int array1[10],b;
for (i=0 ; i < 10 ; i ++){
printf("Insert number %d: ",i);
scanf("%d",&array[i]);
}
for (i=0; i < 10 ; i++){
if ( array[i] % 2 == 0){
even = even + array[i];
}
else
odd = odd + array[i];
}
printf("\n The Sum of Even Numbers in this Array = %d ", even);
printf("\n The Sum of Odd Numbers in this Array = %d ", odd);
for ( i = 10 , b =0; i>0; i-- , b++)
{
array1[b] = array[i];
}
printf("\nReverse Order:\n");
for ( b = 0 ; b< 10;b++ )
{
printf(" %d",array[b]);
}
return 0;
}
The input will be: 2 3 5 4 6 12 3 7 4 9
What I expect the out put for the reverse is: 9 4 7 3 12 6 4 5 3 2
But it gave me same value as : 2 3 5 4 6 12 3 7 4 9 .
Any Idea for how doing this reverse.?
In addition to the answer by #Yunnosch that identifies the problems in your current implementation, you can refactor (rearrange) your code to sum even and odd and reverse array into array1 in a single loop. The only other loop you need is the loop to iterate over array1 outputting the reversed array.
With a bit of re-arranging, you could do something similar to:
#include <stdio.h>
int main (void) {
int array[] = { 2, 3, 5, 4, 6, 12, 3, 7, 4, 9 }, /* array */
array1[sizeof array/sizeof *array], /* array1 */
even = 0, odd = 0; /* even/odd */
size_t n = sizeof array/sizeof *array; /* no. elem in array */
for (size_t i = 0; i < n; i++) { /* loop over each element in array */
array1[i] = array[n - i - 1]; /* reverse into array1 */
if (array[i] & 1) /* check if odd (bit-0 == 1) */
odd += array[i]; /* add value to odd */
else /* even */
even += array[i]; /* add value to even */
}
/* output results */
printf ("even sum: %d\nodd sum : %d\n\nreversed: ", even, odd);
for (size_t i = 0; i < n; i++)
printf (" %d", array1[i]);
putchar ('\n');
}
(note: you can either use if (array[i] % 2) or if (array[i] & 1) to test whether the element is odd or even. Anding with 1 simply checks whether bit-0 is 1, if it is, it's an odd number. Modern compilers will optimize to remove the division inherent to modulo, so whichever you prefer should pose no penalty)
Example Use/Output
$ ./bin/revarr
even sum: 28
odd sum : 27
reversed: 9 4 7 3 12 6 4 5 3 2
Look things over and let me know if you have questions.
You are outputting the array which you never tried to inverse.
printf(" %d",array[b]);
should be
printf(" %d",array1[b]);
Aside, the input by David C. Rankin:
Also for ( i = 10 ... and array1[b] = array[i]; assigns from beyond the end of array. It should e.g. better be
for ( i = 10 , b =0; i>0; i-- , b++)
{
array1[b] = array[i-1];
}

How to find all subsets whose sum adds up to the value of a target value using dynamic programming in C

So I have been trying to do a variant of the subset sum problem, which I want to do using dynamic programming. So what I am aiming for is for example, to have an input of
m = 25 // Target value
n = 7 // Size of input set
and the input set to be for example {1, 3, 4, 6, 7, 10, 25}. So the wanted output would be something like
{1, 3, 4, 7, 10} and {25}.
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Get input sequence
int n = 7; // Size of input set
int m = 25; // Target value
int *S; // Input set
int **C; // Cost table
int i,j,potentialSum,leftover;
S=(int*) malloc((n+1)*sizeof(int));
C=malloc((m+1)*sizeof(int*));
for (int rows = 0; rows<=m; rows++) {
C[rows] = malloc((m+1)*sizeof(int));
}
if (!S || !C)
{
printf(" FAILED %d\n",__LINE__);
exit(0);
}
S[0] = 0;
S[1] = 1;
S[2] = 3;
S[3] = 4;
S[4] = 6;
S[5] = 7;
S[6] = 10;
S[7] = 25;
// Initialize table for DP
C[0][0]=0; // DP base case
// For each potential sum, determine the smallest index such
// that its input value is in a subset to achieve that sum.
for (potentialSum=1; potentialSum<=m; potentialSum ++)
{
for (j=1;j<=n;j++)
{
leftover=potentialSum-S[j]; // To be achieved with other values
if (leftover<0) // Too much thrown away
continue;
if (C[leftover][0] == (-1)) // No way to achieve leftover
continue;
if (C[leftover][0]<j) // Indices are included in
break; // ascending order.
}
C[potentialSum][0]=(j<=n) ? j : (-1);
}
// Output the input set
printf(" i S\n");
printf("-------\n");
for (i=0;i<=n;i++)
printf("%3d %3d\n",i,S[i]);
// Output the DP table
printf("\n\n i C\n");
printf("-------\n");
for (i=0;i<=m;i++)
printf("%3d %3d\n",i,C[i][0]);
if (C[m][m]==(-1))
printf("No solution\n");
else
{
printf("\n\nSolution\n\n");
printf("(Position) i S\n");
printf("------------------\n");
for (i=m;i>0;i-=S[C[i][0]])
printf(" %3d %3d\n",C[i][0],S[C[i][0]]);
}
}
This will output the following
i S
-------
0 0
1 1
2 3
3 4
4 6
5 7
6 10
7 25
i C
-------
0 0
1 1
2 -1
3 2
4 2
5 3
6 4
7 3
8 3
9 4
10 4
11 4
12 5
13 4
14 4
15 5
16 5
17 5
18 5
19 6
20 5
21 5
22 6
23 6
24 6
25 6
Solution
(Position) i S
------------------
6 10
5 7
3 4
2 3
1 1
Program ended with exit code: 0
My problem is that I can only output one solution, and that is the solution that needs the smaller values and goes up to 25, so when 25 is used it isn't in the solution. The C array in the code is a 2-D array, since I thought I could maybe do another backtrace while computing the first one? I couldn't figure out how to do so, so I left C[i][0] fixed to the first column, just to demonstrate a single solution. Any tips in the right direction would be greatly appreciated. I found a solution using Python, but the problem is solved recursively, which I don't think helps me, but that code is here.
Thanks for all the help in advance.
I did not fully understand your code. But here is a C code which finds all the subsets that sum to target.
#include <stdio.h>
int a[] = { 0, 1, 3, 4, 6, 7, 10, 25 }; //-- notice that the input array is zero indexed
int n = 7;
int target = 25;
int dp[8][26];
int solutions[1 << 7][8]; //-- notice that the number of subsets could be exponential in the length of the input array a.
int sz[1 << 7]; //-- sz[i] is the length of subset solutions[i]
int cnt = 0; //-- number of subsets
void copy(int srcIdx, int dstIdx){
int i;
for (i = 0; i < sz[srcIdx]; i++)
solutions[dstIdx][i] = solutions[srcIdx][i];
sz[dstIdx] = sz[srcIdx];
}
//-- i, and j are indices of dp array
//-- idx is the index of the current subset in the solution array
void buildSolutions(int i, int j, int idx){
if (i == 0 || j == 0) return; // no more elements to add to the current subset
if (dp[i - 1][j] && dp[i - 1][j - a[i]]){ // we have two branches
cnt++; // increase the number of total subsets
copy(idx, cnt); // copy the current subset to the new subset. The new subset does not include a[i]
buildSolutions(i - 1, j, cnt); //find the remaining elements of the new subset
solutions[idx][sz[idx]] = a[i]; // include a[i] in the current subset
sz[idx]++; // increase the size of the current subset
buildSolutions(i - 1, j - a[i], idx); // calculate the remaining of the current subset
}
else if (dp[i - 1][j - a[i]]){ // we only have one branch
solutions[idx][sz[idx]] = a[i]; // add a[i] to the current subset
sz[idx]++;
buildSolutions(i - 1, j - a[i], idx); // calculate the remaining of the current subset
}
else buildSolutions(i - 1, j, idx); // a[i] is not part of the current subset
}
int main(){
int i, j;
// initialize dp array to 0
for (i = 0; i <= n; i++)
for (j = 0; j <= target; j++) dp[i][j] = 0;
//-- filling the dp array
for (i = 0; i <= n; i++)
dp[i][0] = 1;
for (i = 1; i <= n; i++){
for (j = 1; j <= target; j++){
if (j < a[i])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - a[i]];
}
}
//-- building all the solutions
for (i = 0; i < sizeof(sz); i++) sz[i] = 0; //-- initializing the sz array to 0
buildSolutions(n, target, 0);
//-- printing all the subsets
for (i = 0; i <= cnt; i++){
for (j = 0; j < sz[i]; j++){
printf("%d ", solutions[i][j]);
}
printf("\n");
}
}
If you have any questions about the code, do not hesitate to ask.

How to print ring type output in c?

I have c program problem to print the ring type output.
When user enter the number 5, then program output is look like;
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
I use following logic but i really failed i not have any idea.
int main()
{
int a[50],i,j=0,n,k;
printf("Enter the number=");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(i>n)
{
j=j+5;
}
else if(i>((2*n)-1))
{
j--;
}
else if(i>((3*n)-2))
{
j=j-5;
}
else if(i>(4*n-4))
{
j++;
}
}
}
Sorry for asking whole program logic but
,I really dont have any idea,Please help me.....
here's what you are looking for
#include <stdio.h>
#define max 25
int main()
{
int spiral[max][max] = {{0}}; // initializing array with 0
int r, c, i = 0, j = -1, count = 1;
printf("\nEnter the row and column for spiral matrix:\n");
scanf("%d%d", &r, &c);
while (count <= r * c) // this loop executes till all the blocks of
{
// array r*c are filled with 0
while (j < c - 1) // Filling the location from left to right
{
// with value of variable count
if(spiral[i][j+1]!=0) // Here we are checking if that location
break; // is already occupied
spiral[i][++j] = count++;
}
while (i < r - 1) // Filling the location from top to bottom
{
if (spiral[i+1][j] != 0)
break;
spiral[++i][j] = count++;
}
while (j > 0) // Filling the location from right to left
{
if(spiral[i][j-1] != 0)
break;
spiral[i][--j] = count++;
}
while (i > 0) // Filling the column from bottom to top
{
if (spiral[i-1][j] != 0)
break;
spiral[--i][j] = count++;
}
}
for (i = 0 ; i < r ; i++)
{
for (j = 0 ; j < c ; j++)
{
printf("%3d",spiral[i][j]); // print the matrix
}
printf("\n");
}
return 0;
}
reference is here from more details
A simple way to solve this problem is to allocate an array of size N*N and to populate it with a straight forward loop that follows the spiral. Then you can print the array contents N elements per row.

Resources