I am trying to find 6 number one is from 10-100 and the other five numbers are between 1-10
the articles that I read about generating new numbers was somehow complex for me to apply so I made a new simple way by obtaining a series of repetitions of these numbers and put them in two-dimensional array after that I used rand() as index to the first array parameter so I could find the random numbers but I have a problem ..I want to put the generated numbers in array because I want to use them later.
I'll be thankful if you explain in a simple way
include<sys/time.h>
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
#include<ctime>
#define max 1000
int main()
{
int o, gr1num1[max][1] ,n=6,q[max] ,i = 0, gr2num5[max][5];
while(1)
{
i++;
gr2num5[i][4] = rand() % 10+1 ;
if(i == 1000)
break;
}
if (gr2num5 [i][4]!=0)
srand(time(NULL));
printf("\ngroup 2 numbers %d ",gr2num5 [rand()%500][4]);
printf("\ngroup 2 numbers %d ",gr2num5 [rand()%500][4]);
printf("\ngroup 2 numbers %d ",gr2num5 [rand()%500][4]);
printf("\ngroup 2 numbers %d ",gr2num5 [rand()%500][4]);
printf("\ngroup 2 numbers %d ",gr2num5 [rand()%500][4]);
printf(" \n\n\n /// %d /// ",o);
while(1)
{
i++;
gr1num1[i][1] = rand() % 100+10;
if(i == 1000)
break;
}
printf("group 1 number %d",gr1num1 [rand()%500][1]);
}
First off you should go back and re-read your book on C for how to do loops as whilst syntactically correct, the way you're using those while loops isn't right.
This is how your first while loop should look. The increment of i happens at the end of the loop since the index of arrays starts at 0.
i=0;
while(i<max)
{
gr2num5[i][4]= rand() % 10+1 ;
i++;
}
But really it would be better done as a for loop like this as it wraps up the initialisation, conditional and incrementation all in one neat package. The first part - the initialisation - is important as for your second while loop, your value of i is still 1000 as you don't reset it to 0.
for(i=0;i<max;i++)
{
gr2num5[i][4]= rand() % 10+1 ;
}
But you're after 5 values, so you need to nest two loops within each other to populate the gr2num5 array like this.
for(i=0;i<max;i++)
{
for(j=0;j<5;j++)
{
gr2num5[i][j]=rand() % 10+1 ;
}
}
(NB: you'll define j at the top along side i)
Related
I was making a program in C Language that determines the most frequently appeared number in an array, and also outputting the smallest most frequently appeared number, however I am encountering a bug and I was not sure which part I did wrong.
Here is the example of the program input
2
8
1 1 2 2 3 4 5 5
8
5 5 4 3 2 2 1 1
The number 2 means to create 2 different arrays, the number 8 determines the size of the array. the number afterwards determine the numbers to be put inside of the array, and the program repeats itself by inputting the size of an array etc.
Here is the expected output :
Case #1: 2
1
Case #2: 2
1
The "Case #1: 2" means that the most frequently appeared number appeared 2 times in the array (number 1 2 and 5, each appeared twice in the array), while it prints number 1 because number 1 is the smallest number in the most frequently appeared. and the same goes on for case #2
However, in my program, when I input the second case, it does not properly print the smallest number, and instead just prints nothing. But weirdly enough, if I input a different number in the second array (instead of just the first array in reverse order) it prints the correct smallest number. Here is the example output that my program creates
Case #1: 2
1
Case #2: 2
Here is the code that I made :
#include <stdio.h>
int main(){
long long t, n;
scanf("%lld",&t); //masukkin berapa kali mau bikin array
for(int x=0;x<t;x++) {
scanf("%lld",&n); // masukkin mau berapa angka per array
long long arr[200000]={0};
long long i, count, freq=0, test=0;
for(i=0; i<n; i++){
scanf("%lld", &count); //masukkin angka ke dalem array
arr[count]++;
}
for(i=0; i<200000; i++){
if(arr[i]>0 && arr[i]>=freq){
freq=arr[i];
}
}
printf("Case #%d: %lld\n",x+1,freq);
int min;
for(i=0; i<200000; i++){
if (arr[i] > min){
min = arr[i];
printf("%lld",i);
test=1;
}
}
printf("\n");
}
return 0;
}
Your problem is here:
int min;
min is not initialized so when you do if (arr[i] > min){ you have no idea what value min has.
So do
int min = INT_MIN;
That said, you don't really need min. The first arr[i] that equals freq will tell you that i is the smallest number.
Further notice that
long long arr[200000]={0};
is a bad idea. Huge arrays should never be defined as local variables as it may lead to stack overflow. Make it a global variable or use dynamic allocation.
And you should change
arr[count]++;
to
if (count >= 200000)
{
// Too big - add error handling
...
}
else
{
arr[count]++;
}
And you don't need an extra loop for finding freq. Find freq when you get the input.
So I have a program to find the total number of ways in which an integer N can be expressed as the sum of "n" integers.
For example, 10 can be expressed as a combination of 2,3 and 5 as follows-
10 = 5 + 5
10 = 5 + 3 + 2
10 = 3 + 3 + 2 + 2
10 = 2 + 2 + 2 + 2 + 2
#include<stdio.h>
#include<stdlib.h>
int ways(int,int*,int);
int main() {
int n,num; //n is number of possible integers
scanf("%d",&n);
int*curr=(int*)malloc(n*sizeof(int)); //dynamically allocated array that stores all "n" integers in array form
for(int i=0;i<n;i++) {
scanf("%d",curr+i);
}
int t,N; //t is number of test cases
scanf("%d",&t);
while(t--) {
scanf("%d",&N); //for each test case, scans the number N that needs to be expressed as a sum of combinations those "n" integers
num=ways(N,curr,n);
printf("%d\n",num);
}
return 0;
}
int ways(int N,int*p,int size) {
int flag=1;
for(int i=0;i<size;i++) {
if(N/(*(p+i))!=0) {
flag=0;
break;
}
//Above loop says that if number N is less than all of the "n" integers, it
cannot be expressed as their sum. Hence, 0 will be returned if flag is 1
}
if(flag==1)
return 0;
if(N==0)
return 1;
int num=0,temp;
for(int i=0;i<size;i++) {
temp=*(p+i);
num=num+ways(N-temp,p,size); //GETTING RUNTIME ERROR AT THIS LINE
}
return num;
}
The program is getting SIGSEGV error at the recursive function call even for very small depth of recursion
In the first i loop in ways, you seem to be looking for a value in
array p that is smaller than N (though division is a horribly
inefficient way to test). Having found one, you do other things, then
use another i loop, losing the value of i you found in the first
one, and call ways recursively.
Now, note that you do no testing in the second loop. It’s entirely
possible to subtract something from N that is larger than N, get a
negative result, and pass that. This would cause infinite recursion, no?
A SIGSEGV error is a Segmentation fault error, which means that you are trying to access a memory location out of your programs reach.
This is most common due to de-referencing a null pointer or going over in your for loop. Try checking the logic of your code.
I think when you are typing *(p + 1), you are going out of bounds at some point. Try debugging with breakpoints or by outputting the value of *(p+1) in the for loop.
I was working on a program for my intro to C class (xtra credit assignment) and can't figure out how to discard duplicates numbers on an array. The problem asks to only print non duplicates; so I able to print the first number, compare the following and print if different, I discard the next if a duplicate, but the thing is I've only figured out how to compare the one number it following one, I figured I could do another for loop inside the for loop, but I'm getting super confused and just can't figure it out. I've already submitted my code last week, I've just been working on this trying to figure it out for myself so any help/guidance would be greatly appreciated.
"EDIT: Here's the problem: Use a single-subscripted array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print it only if it's not a duplicate of a number already read. Provide for the worst case in which all 20 numbers are different. Use the smallest possible array to solve this problem"
Thanks in advance, and any advice on how I'm writing my program would also be appreciated as I'm a total noob, and trying to be a good programmer with as little bad habits as possible.
#include <stdio.h>
#include <stdlib.h>
#define AS 20
void findDuplicate (int af[], int fAS);
int main(){
int a[AS], i , j, k;
int last = 0;
printf("Enter %d numbers between 10 and 100:\n", AS);
for (i = 0; i < AS; i++){
scanf("%d",&a[i] );
if (a[i] >= 10 && a[i] <= 100 ){
continue;
} else {
printf("You must enter values between 10 - 100\n");
i = i -1;
}
}
findDuplicate(a, AS);
system ("pause");
return 0;
}
void findDuplicate (int af[], int fAS){
int c;
printf("You entered ");
for (c=0; c < fAS; c++){
if (af[c] != af[c+1]){
printf("%d ", af[c]);
}
continue;
}
printf("\n");
}
You should first define an Array which can save as many variables as you want ..
Lets say you are comparing for 10-100 which means 91 possible different digits.
so , define array with the size of 91. and then do the scanning in for loop for 91 times to find out if you have that variable entered previously. If not then save it and display it ,else discard it.
I want to make a random number generator where the user specifies the range and amount of generated numbers. I want it to make every number unique (no repeat). This is what I've done so far (it generates but some of them repeat, why?)
#include <time.h>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
int main()
{
srand(time(NULL));
int start, stop, amount;
system("chcp 1250 >nul");
printf("Welcome to random number generator!\n");
printf("\nWhat range? \nFrom: "); scanf("%i", &start);
printf("To: "); scanf("%i", &stop);
printf("\nHow many numbers?: "); scanf("%i", &amount);
int number[amount];
for(int i=0; i<amount; i++)
{
number[i] = rand() % ((stop+1)-start) + start;
for(int j=i; j>-1; j--)
{
if(number[i]==number[j])
{
number[i] = rand() % ((stop+1)-start) + start;
}
}
printf("\n%i generated number: %i", i+1, number[i]);
Sleep(10);
}
getch();
}
Your "check for dupes" loop is incorrect. You might find a duplicate, but then you don't check if that re-generated number exists in the stuff you ALREADY tested.
e.g. consider an array like this. user asked for 5 numbers, range 1-10
number[0] = 5
number[1] = 6
number[2] = 2
number[3] = 8
Now you're working on number[4]. You generate 2... You scan the array backwards and find that 2 is a dupe. So you generate a new number... and generate 8. But you don't reset your j loop - you just keep working backwards, and never see that 8 was already in the array.
What you should have is something more like:
for(int j=i; j>-1; j--) {
if(number[i]==number[j]) {
number[i] = rand() % ((stop+1)-start) + start;
j = i; // RESET THE LOOP
}
}
And note that your code can easily produce an infinite loop. e.g. consider someone asking for numbers in a range 1-3, and generate 4 of them. 1,2,3,?. The condition can never be satisfied, because you can't have 1-3 without at least one repeat.
So, even if we assume that rand() is a perfect random number generator, the numbers would repeat.
Lets say you have to generate 100 numbers. Say your start = 1 and stop = 100.
you generate a first number from 1 to 100, then the second and so on.. The more numbers you've used so far, the easier it is to get a duplicate.
Then you find a duplicate with that inner for-loop. You generate a new number for
number[i], but you have no guarantee that this number's unique. You may as well end up
setting number[i] to another duplicate.
If you want your code to work, you have to keep changing number[i] as long as it has a duplicate.
That's regarding the bug in your code.
On the other hand, this code is horribly inefficient, so you should consider optimising it if you plan on running this procedure often.
Write a program that sums the sequence
of integers as well as the smallest in
the sequence. Assume that the first
integer read with scanf specifies the
number of values remaining to be
entered. For example the sequence
entered:
Input: 5 100 350 400 550 678
Output: The sum of the sequence of
integers is: 2078
Input: 5 40 67 9 13 98
Output: The smallest of the integers
entered is: 9
This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help
First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.
Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).
I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.
If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).
And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).
Update:
Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", ¤tNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
And here is the output from your sample data:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.
Read:
Assume that the first integer read
with scanf specifies the number of
values remaining to be entered
so it's not part of the sequence...
for the rest, it's your homework (and C...)
No. 5 is the number of integers you have to read into the list.
Jeebus, I'm not doing your homework for you, but...
Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:
Read integer
Loop that many times
** Read more integers
** Add
** Find Smallest
IF you're in C look at INT_MAX - that will help out finding the smallest integer.
Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.
-Adam
First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).
Then do a loop on the array to get the sum of to find the smallest value.
Hope that helps
wasn[']t looking for you guys to do the work
Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").
You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."
#include <stdio.h>
main ()
{
int num1, num2, num3, num4, num5, num6, i;
int smallestnumber=0;
int sum=0;
int numbers[50];
int count;
num1 = 0;
num2 = 0;
num3 = 0;
num4 = 0;
num5 = 0;
num6 = 0;
printf("How many numbers will be entered (max 50)? ");
scanf("%d", &count);
printf("\nEnter %d numbers then press enter after each entry: \n", count);
for (i=0; i < count; i++) {
printf("%2d> ", i+1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
smallestnumber = numbers[0];
for (i=0; i < count; i++) {
if ( numbers[i] < smallestnumber)
{
smallestnumber = numbers[i];
}
}
printf("the sum of the numbers is: %d\n", sum);
printf("The smallest number is: %d", smallestnumber);
}