I have a problem with a task on the computer language C - c

I would like to ask for assistance on a program I have to create on C.
The task is as it follows: To compile a program that enters integers m, n (m < n) and finds the number of all integers in this interval that are divisible by 3. The program displays all numbers that are in the interval and are not divisible by 3.
I managed to write the code on Python, but I have no idea how to do it on C.
I will appreciate every single help you send! Thanks in advance!

First, I suggest you have a look at C's printf, scanf and loops, and then you should be fine!
However, here is a way to do it (in case you need a peek):
#include <stdio.h>
int main(void) {
int m, n;
int counter = 0;
printf("Enter m: ");
scanf("%d", &m); // reads from the standard input and puts the value into m
/* The "%d" is to tell the program that we are going to read a signed decimal
* integer.
* Note: To keep the code simpler (i.e. without input checking or
* sanitization), we just assume that the user will input
* valid integers, i.e. two integers m and n such that m < n.
*/
printf("Enter n: ");
scanf("%d", &n); // same for n
/* Now you loop over all integers that are in the interval [m, n]
* int i = m is the initialization of the loop, i.e. where you want to start
* from.
* i <= n is the condition of the loop, i.e. while i is smaller or equal to n
* i++ is done in the end of an iteration, i.e. move onto the next integer
* at the end of each iteration.
*/
printf("The numbers not divisible by 3 are:\n"); // \n means end of line
for(int i = m; i <= n; i++) {
if(i % 3 == 0) {
counter++;
}
else {
/* Note: If you are not printing a string (for example an
* integer in our case), C also requires the format "%d" (opposed to
* Python where one would have written print(i + " ")).
*/
printf("%d ", i);
}
}
printf("\n");
printf("There are %d integers in [%d, %d] that are divisible by 3\n",
counter, m, n);
return 0;
}

Related

Loops running infinitely for big inputs

I am self learner, I am working on a population growth problem, and I came across the issue of loop running infinitely when I enter a big ending number that I want to reach.
#include <cs50.h>
#include <stdio.h>
int main(void) {
// TODO: Prompt for start size
int n;
do {
n = get_int("Enter the starting size of your llamas: ");
} while (n <= 8);
// TODO: Prompt for end size
int j;
do {
j = get_int("Enter the Ending size of your llamas: ");
} while (j <= n);
// TODO: Calculate number of years until we reach threshold
int k = 0;
do {
n = n + (n/3) - (n/4);
printf("The number is %i\n", n);
k++;
} while (n != j);
// TODO: Print number of years
printf("The number is %i\n", k);
}
The answer is supposed to be the number of years it takes to reach the end size llamas, but I am not able to put in big numbers of end size, can you help me figure out what is wrong, maybe in my math or a sign. Thanks in advance.
For large numbers, n is incremented by more than 1 at each iteration, so it is possible than it becomes larger than j without being equal to it first.
Change the test while(n != j); to while(n < j);

Floyd's Triangle right pattern

I have to creat a program thats that asks from the user to enter a number of rows and then creats a floyd's triangle. The problem is i don't seem to manage to make this particular pattern:
1
2 3
4 5 6
7 8 9 10
I have only managed to creat the basic program
#include <stdio.h>
#include <stdlib.h>
int rows, r, c, a;
int number=1;
int main()
{
printf("Floyd Triangle\n");
printf("--------------");
printf("\nPlease enter an integer number of rows: ");
scanf("%d",&rows);
while(rows<=0)
{
printf("\nYou must enter an integer value: ");
scanf("%d",&rows);
}
for(r=1;r<=rows;r++)
{
for(c=1;c<=r;+c++)
{
printf("%d ", number++);
}
printf("\n");
}
there are no erros in my code so far
Just print some spaces before the first number in each row
// ...
for (r = 0; r < rows; r++) {
printsomespaces(r, rows); // prints some spaces depending on current row and total rows
for (c = 0; c < r; +c++) {
printf("%d ", number++);
}
printf("\n");
}
// ...
If you can't write your own function (no printsomespaces) use a loop instead:
//...
//printsomespaces(r, rows);
for (int space = 0; space < XXXXXXXX; space++) putchar(' ');
//...
where XXXXXXXX is some calculation using r and rows.
Try (untested) 2 * (rows - r) (2 is the width of each number: 1 for the number + 1 for the space).
i haven't learnt how to make my own functions yet. isnt there a way to accomplish this only by using loops?
There is. A main problem of this exercise is to compute the needed width of each column, which of course depends on the number in the bottom row. The count of digits of a number can be determined in various ways; perhaps the easiest is via the snprintf(char *s, size_t n, const char *format, ...) function, which
… returns the number of characters that would have been written
had n been sufficiently large…
If n is zero, nothing is written,
and s may be a null pointer.
// we need to compute the width the of widest number of each column
int width[rows];
const int max = rows*(rows+1)/2; // the greatest number
for (c=1; c<=rows; ++c) // see how many characters will be written
width[c-1] = snprintf(NULL, 0, "%d ", max-rows+c);
for (r=1; r<=rows; ++r, puts(""))
for (c=1; c<=rows; ++c)
if (c <= rows-r) // here comes an empty cell in this row
printf("%-*c", width[c-1], ' ');
else
printf("%-*d", width[c-1], number++);

For loop "<" vs "<=" print format issues in program

I am learning C on my own with a book and I cannot for the life of me figure out how to solve this exercise. I'm obviously looking at it in the wrong way or something. Here is an explanation below.
Listed below are some functions and the main function at the bottom. This program is compiled to generate a certain number of random numbers and determine the min and the max of the random numbers. If you copy and paste this code, you will see how it works. Anyways, an exercise asks me to go to the function "prn_random_numbers()" and change the for loop from "for (i = 1; i < k; ++i)" to for (i = 2; i <= k; ++i). This causes the first line format to print incorrectly. The exercise is to further modify the program in the body of the for loop to get the output to be formatted correctly.
To sum it up, the "prn_random_numbers()" function is written to print out 5 random numbers before moving to the next line. Hence the" i % 5" if statement. Now, for some reason, when you make the slight adjustment to the for loop, as the exercise asks above, it causes the first line to only print 4 numbers before moving to the next line. I have tried a number of things, including trying to force it to print the 5th number, but it only duplicated one of the random numbers. I even tried "i % 4" to see if it would print 4 numbers for each row, but it only prints 3 numbers for the first row instead of 4! So it always prints one less number on the first line than it is supposed to. I have n clue why it is doing that and the book does not give an exercise. Do you have any idea?
Bear with me if you think this is a stupid question. I am just learning on my own and I want to make sure I have a good foundation and understand everything as I learn it, before moving forward. I appreciate any help or advice!
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
the following proposed code:
properly initializes the random number generator
cleanly compiles
properly checks for and handles errors
performs the desired functionality
avoids having to list instructions twice
follows the axiom: Only one statement per line and (at most) one variable declaration per statement.
does not use undefined functions like: max() and min()
and now the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void prn_random_numbers(int k)
{
int count = 1;
int r;
int smallest;
int biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for ( int i = 2; i <= k; i++, count++)
{
if (count % 5 == 0)
{
count = 0;
printf("\n");
}
r = rand();
smallest = (r < smallest)? r : smallest;
biggest = (r > biggest)? r : biggest;
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main( void )
{
int n;
srand( (unsigned)time( NULL ) );
do
{
printf("Please enter a positive integer, greater than 0.\n");
printf("How many would you like to see? ");
if( scanf("%d", &n) != 1 )
{
fprintf( stderr, "scanf for number of random numbers failed\n" );
exit( EXIT_FAILURE );
}
} while( n < 1 );
prn_random_numbers(n);
// in modern C, if the returned value from `main()` is 0 then no `return 0;` statement needed
}
a typical run, no input problems is:
Please enter a positive integer, greater than 0.
How many would you like to see? 20
98697066 2110217332 1247184349 421403769 1643589269
1440322693 985220171 1915371488 1920726601 1637143133
2070012356 541419813 1708523311 1237437366 1058236022
926434075 1422865093 2113527574 626328197 1618571881
20 random numbers printed.
Minimum: 98697066
Maximum: 2113527574
Try to use a debugger to solve your problem, it's easy to use and really helpfull :)
SOLUTION:
Your i variable don't count the number of numbers because it is initialize at 1 (in the for statement), so you need to declare a new variable to count properly.
If you have still a problem:
void prn_random_numbers(int k)
{
int count = 1;
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 2; i <= k; i++, count++) {
if (count % 5 == 0) {
count = 0;
printf("\n");
}
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}

Why am I getting memory location values after printing prime numbers of a particular range?

I am solving this problem:
Peter wants to generate some prime numbers for his cryptosystem. Help
him! Your task is to generate all prime numbers between two given
numbers!
Input
The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
I am getting memory location values after I get prime numbers in the output.
Can you explain about how I can terminate after getting the final output.
Here is my code:
#include <stdio.h>
int main()
{
int t, i, m[10], n[10], j, k, l, isPrime;
// t is test case, m[] and n[] are the lower and upper value of the range of prime numbers
// isPrime is to check the condition True or False.
j = 0;
scanf(" %d \n", &t);
for(i=0; i<t; i++)
{
scanf("%d%d",&m[i],&n[i]);
}
while(j<=i)
{
for(k = m[j]; k<= n[j]; k++)
{ isPrime = 0;
for(l = 2; l<= (k/2); l++){
if(k%l == 0)
{
isPrime = 1;
break;
}
}
if(isPrime==0 && n[j]!= 1)
printf(" %d \n", k);
}
j++;
}
getch();
return 0;
}
You are using getch() which will stop the program until you press any key right after the execution of all your program. remove getch(), compile and run the .exe from the source folder file after closing the IDE.
Well, I executed the code, without getch() and it worked fine!

Returning to the start of a for loop in C

Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8

Resources