how to print the number of times code looped? - c

i have wrote a simple code that prints all the prime numbers from the number that has entered. I would like to print how many prime numbers are printed. I think its print("%d",c++); but i dont know where to put it. I have tried putting it right before return 0; at the end of prime method but it does not work. The prime numbers print just fine but the counter does not print.
void main(void){
int pri;
scan("%d",&pri);
prime(pri);
}
void prime(int n){
int m,i,c,x;
for(m = 1;m<=n;m++){
c = 0;
for(i=2;i<=m/2;i++){
if(m%i==0){
c++;
break;
}
}
if(c==0 && m!= 1){
printf("%d ",m);
}
}
print("the count is: ");
print("%d",c);
return 0;
}
If I input 100 I want the output to be:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
61 67 71 73 79 83 89 97
The count is 25.

Add a variable count since c is not your count. It is a local test variable whether a prime has been found. add int count = 0; in front of the for loop and print it instead of c at the end. In the if statement where you print the single primes, add count++;.
int n = 100; // for copy paste purposes
int m,i,c,x;
int count = 0;
for(m = 1;m<=n;m++){
//c = 0;
for(i=2;i<=m/2;i++){
if(m%i==0){
c++;
break;
}
}
if(c==0 && m!= 1){
printf("%d ",m);
count++;
}
}
printf("\nthe count is: %d\n", count);

There are quite a few things your program should take care of most importantly it should compile first which I highly doubt it does at this point.Anyway below is a working example for it, with modifications
#include <stdio.h>
void prime(int ); // prototype
//void main(void){
int main(void){
int pri;
//scan("%d",&pri);
scanf("%d",&pri);
prime(pri);
return 0;
}
void prime(int n)
{
int m,i,c,count = 0; // your counter
for(m = 1 ; m <= n ; m++ ) {
c = 0;
for( i = 2 ; i <= m/2 ; i++ ) {
if( m%i == 0 ) {
c++;
break;
}
}
if( c == 0 && m != 1 ){
printf("%d ",m);
count = count + 1; // keep counting
}
}
//print("the count is: ");
printf("\nthe count is: ");
//print("%d",c);
printf("%d",count);
// return 0;
}
Note - better formatting the key.

Related

Counting the number of zero in an integer

The program would ask the user an integer input.
and it counts how many zero the int has.
constraints: use while loop
ex:
input: 2400
count: 2
now I have no problem in that part, only when the user would input a zero.
supposed it counts 1.
ex:
input 0
count: 1
but then the program returns count 0.
here's the code:
int main(){
int n, counter = 0;
printf("Enter the number: ");
scanf("%d", &n);
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
printf("%d", counter);
return 0;
}
Use functions.
int countZeroes(int x)
{
int result = !x; // if x == 0 then result = 1
while(x)
{
result += !(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
printf("%d\n", countZeroes(0));
printf("%d\n", countZeroes(1000));
printf("%d\n", countZeroes(-202020));
}
https://godbolt.org/z/91hKr46eo
You have while(n != 0) this does so when you enter just 0 it doesn't run. So the counter that you have set to 0 at the beginning is still 0
Here is what I would have done :
int main()
{
int num, count = 0;
scanf("%d",&num);
if (num == 0) {
printf("1");
return 0;
}
while(num != 0) //do till num greater than 0
{
int mod = num % 10; //split last digit from number
num = num / 10; //divide num by 10. num /= 10 also a valid one
if(mod == 0) count ++;
}
printf("%d\n",count);
return 0;
}
Just don't forget to consider everything that can happen with a condition that you set
**Fixed it
A different version that prints the integer as a string, and looks for '0' characters in it. Tested.
#include <stdio.h>
#include <string.h>
int main(void)
{
int input = 0;
int zeroes = 0;
char *foundpos, teststring[100];
scanf("%d", &input);
sprintf(teststring, "%d", input);
foundpos = strchr(teststring, '0');
while (foundpos != NULL) {
++zeroes;
foundpos = strchr(foundpos + 1, '0');
}
printf("%d contains %d zeroes", input, zeroes);
}
Just count the zero digits you get between \n chars.
#include <stdio.h>
int main()
{
int ndigs = 0, c;
while ((c = getchar()) != EOF) {
switch (c) {
case '0': ndigs++;
break;
case '\n': printf(" => %d zero digs", ndigs);
ndigs = 0;
break;
}
putchar(c);
}
}
sample output:
$ ./a.out
123001202010
123001202010 => 5 zero digs
^D
$ _
No need to convert digits to a number, to convert it back to decimal digits. You can improve the program counting digits until a nondigit is detected, then output. But there's no need to convert a decimal representation of a number (in base 10) to internal representation to then get the digits you have destroyed (in the conversion) back again to count them.
As earlier mentioned, the problem is with the loop:
while(n != 0){
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
}
It doesnt do anything in case n == 0. But replacing it with n > 0 is not a good solution because ints can be negative too.
You should use do{}while() construction instead, it will always do one iteration of loop no matter what condition you put there. Notice that no matter what you get as a number, it is still a number so you can do one iteration of loop either way.
Just do as follows:
do{
if(n % 10 == 0){
counter ++;
n=n/10;
}else{
break;
}
} while( n != 0 );
This should work(if i didnt mess up the braces/semicolumns).

Why %d is showing 0 in my c program output?

The program is to find the largest number amongst all the entered integers. It asks the user to enter a number 10 times or press 0 to quit, whichever is earlier. But, the output is not as expected. I will appreciate it if you can help a newbie.
#include <stdio.h>
int main()
{
int num[10];
int max, a;
for (a = 0; a < 10; a++)
{
printf("Enter the integer: ");
scanf("%d", &num[a]);
if (num[a] == 0)
break;
}
for(a = 0; a < 10; a++)
{
num[0] = max;
if(max < num[a])
{
num[a] = max;
}
}
printf("This is the largest integer: %d", max); //The output is coming wrong here.
return 0;
}
Don't use num[0], you are overwriting it with max variable which is not initialized, so it is 0.
Use max to the minimum type variable (INT_MIN with limits.h header file) or initalize it to max = num[0] after input is captured.
#include <limits.h>
int max = INT_MIN;
Also you need to change your second for loop as follows so as to update the max variable as you iterate, and not the num[] variables. Loop variable starts with 1 if you already assumed max to be first element before, else loop variable will start with 0.
for(a = 1; a < 10; a++) // a=0 if max was initialized to INT_MIN above
{
if(num[a]>max)
{
max = num[a];
}
}
You never assign the max variable.
What you want to do is to check if the value entered is greater than each one you've previously entered, so you would need to use the following condition:
if (num[a] > max)
max = num[a];
You also need to initialize max to some value (let's say, if you expect to have only positive integers, it could be 0, but have a look at Jigsaw answer for a better solution): int max = 0;.
And eventually add an if-condition that checks if max is 0, that way you know if no values have been entered:
if(max == 0)
printf("No values have been entered.");
else printf("This is the largest integer: %d", max);
Notice that you can assign the elements of num and update max in the same for loop, therefore the second for becomes completely useless and you can remove it:
#include <stdio.h>
int main()
{
int num[10];
int max = 0, a;
for (a = 0; a < 10; a++)
{
printf("Enter the integer: ");
scanf("%d", &num[a]);
if (num[a] == 0)
break;
if (num[a] > max)
max = num[a];
}
if(max == 0)
printf("No values have been entered.");
else printf("This is the largest integer: %d", max);
return 0;
}
I suggest you to turn on your compilers warning, especially -Wall and -Wextra, so you would notice problems like these:
<source>: In function 'main':
<source>:17:16: warning: 'max' may be used uninitialized [-Wmaybe-uninitialized]
17 | num[0] = max;
| ~~~~~~~^~~~~
<source>:6:9: note: 'max' was declared here
6 | int max, a;
| ^~~
For starters this for loop
for (a = 0; a < 10; a++)
{
printf("Enter the integer: ");
scanf("%d", &num[a]);
if (num[a] == 0)
break;
}
can enter less than 10 elements in the array num due to the condition
if (num[a] == 0)
break;
So the next loop has to traverse exactly a elements of the array not 10. So in the next loop you have to use another variable for the index as for example
for( int i = 0; i < a; i++)
The variable max was not initialized
int max, a;
So this for loop invokes undefined behavior where the variable max is assigned to elements of the array or where it is compared with elements of the array.
for(a = 0; a < 10; a++)
{
num[0] = max;
if(max < num[a])
{
num[a] = max;
}
}
Moreover the variable max is not changed within the for loop. So the loop in whole does not make sense.
Pay attention to that the user can enter 0 at once. So the array will not contain any valid values. In this case the array does not have a maximum value.
Your program can look for example the following way
#include <stdio.h>
int main( void )
{
enum { N = 10 };
int num[N];
int i = 0;
do
{
printf( "Enter the integer (0 - stop): " );
scanf( "%d", &num[i] );
} while ( num[i] != 0 && ++i < N );
int max_i = 0;
for ( int j = 1; j < i; j++ )
{
if ( num[max_i] < num[j] )
{
max_i = j;
}
}
if ( i == 0 )
{
puts( "You have not entered numbers unequal to zero." );
}
else
{
printf("This is the largest integer: %d", num[max_i] );
}
return 0;
}
You neither initialise nor ever write any value at all to the variable max. Using uninitialised variables is undefined behaviour.
You seem to know how to write 0 into a. But for max you seem to have it reversed. Remember that with = the value on the right of it goes into the variable on the left of it.
To fix the problem, turn any something = max; which occurs in your code into max = something;.

My program immediately exits after it asks for a character [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 1 year ago.
I hope you are doing well everyone. I was given this homework by my teacher.
Which is the problem below:
Write a program that will ask for n positive whole numbers. Your program will only stop asking for a number if the input number is 0 or < 0. From these inputs, determine all the prime numbers. After determining the prime numbers, write a menu option shown below:
[A] Display One’s
[B] Display Ten’s
[C] Display Hundred’s
[D] Display Thousand’s
If the user presses on of these options, then it will display what is being asked. To further understand and shorten the instructions, an illustration is provided below.
Input numbers: 123, 112, 1377, 2, 13, 0
Prime numbers: 123 1377 2 13
If the user presses ‘A’, then the output is
123 = 3
1377 = 7
2 = 2
13 = 3
If the user presses ‘B’, then the output is
123 = 23
1377 = 77
2 = 0
13 = 13
If the user presses ‘C’, then the output is
123 = 123
1377 = 377
2 = 0
13 = 0
If the user presses ‘D’, then the output is
123 = 0
1377 = 1377
2 = 0
13 = 0
I've written a program that I thought would solve the problem, but somehow after I input a character (A,B,C,D) the program immediately terminates?
If someone could point any other mistakes or have any suggestions in mind. I'll be open to them and I'll be grateful. Thanks so much in advance. :))
#include<stdio.h>
int isPrime(int num);
void Sort(char sort, int psize, int* prime);
int main ()
{
int psize=0;
int i, num=1;
int arr[1000], prime[1000];
char sort;
do
{
printf("Enter array element:");
scanf("%d", &num);
if(num<=0) break;
if(isPrime(num))
{
prime[psize]= num; //assign to prime array if it is a prime
psize++;
}
} while(num>0);
printf("\nEnter [A] to Display One's\nEnter[B] Display Ten's\nEnter[C]Display Hundred's\nEnter[D]Display Thousand's");
scanf("%c", &sort);
Sort(sort, psize, prime);
}
int isPrime (int num)
{
int i, flag=1;
for(i=2;i<num;i++)
{
if(num%i==0)
{
flag=0;
break;
}
}
return flag;
}
void Sort(char sort, int psize, int* prime)
{
int i, ans;
if(sort == 'A'){
printf("Ones\n");
for(i=0;i<psize;i++)
{
ans = prime[i] % 10;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'B'){
printf("Tens\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 10)
ans = prime[i] % 100;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'C'){
printf("Hundreds\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 100)
ans = prime[i] % 1000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'D'){
printf("Thousands\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 1000)
ans = prime[i] % 10000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
}
I think that will help you out.
put a fflush() after your scanf function like:
scanf("%d", &num);
fflush(stdin);
Or you use a easier way
int getNumber()
{
char userinput = '1';
int number = 0;
/*
Ascii-table
0 = 48
1 = 49
...
9 = 57
*/
while(1)
{
userinput = getchar();
if (userinput == '\n') break;
if (userinput >= 48 && userinput <= 57)
number = (number * 10) + (userinput - 48);
}
return number;
}
Replace your scanf("%d", &num); with num = getNumber(); - that works!
So, here another code with A-D letters
I hope this will be enough now - And all useres forgive me for my uncomplete code review ^^" :
int getNumber( int opt )
{
char userinput = '1';
int number = 0;
/*
Ascii-table
0 = 48
1 = 49
...
9 = 57
*/
while(1)
{
userinput = getchar();
if (userinput == '\n') break;
/*
opt (Options)
1: Numbers
2: Letters A-D
Other numbers undefined!
*/
switch(opt)
{
case 1:
/* Only 0-9 allowed */
if (userinput >= 48 && userinput <= 57)
number = (number * 10) + (userinput - 48);
break;
case 2:
/* Only A-D allowed */
if (userinput >= 'A' && userinput <= 'D')
number = userinput;
break;
default:
/* Nothing to do - wrong input */
number = 0;
break;
}
}
return number;
}
Replace your scanf("%d", &num); with num = getNumber(1);
Replace your scanf("%d", &sort); with sort = getNumber(2);

C Program - Finding the highest odd integer, stops when input a number less than 1.(Beginner)

I am currently taking programming classes this semester and at the moment we are using C language to program.
For this program it has to find the highest even integer among the values entered by the user. It stops asking values when a value less than 1 has been entered. If there is no even integer it should display "NO ODD INTEGER
at the moment this is what I have
#include<stdio.h>
#include<stdlib.h>
#define MAXNUMBERS 5
int find_maximum(int[], int);
int main()
{
int c, array[MAXNUMBERS], location, maximum, amount_numbers;
clrscr();
amount_numbers = getNumbers(array);
printf("Highest odd integer: ");
for (c = 0 ; c < MAXNUMBERS ; c++)
{
location = find_maximum(array, MAXNUMBERS);
maximum = array[location];
}
printf("%d", maximum);
getch();
}
int find_maximum(int a[], int n) {
int c, max, index;
max = a[0];
index = 0;
for(c = 1 ; c < n ; c++) {
if(a[c] > max && a[c] %1==1) {
index = c;
max = a[c];
}
}
return index;
}
int getNumbers(int arr[])
{
int c;
int n = 0;
printf("You may enter a max. %d numbers, enter a number less than 1 to end.\n", MAXNUMBERS);
for(c = 0 ; c < MAXNUMBERS ; c++)
{
scanf("%d", &arr[c]);
fflush(stdin);
n++;
if(arr[c] < 1)
{
break;
}
}
return n;
}
*Problem has been fixed question can be closed or deleted because of unecessary question
I suggest this approach :
int main()
{
int c, array[MAXNUMBERS], maximum, amount_numbers;
clrscr();
getNumbers(array);
location = find_maximum(array, MAXNUMBERS);
if (location == -1 )
printf("No Even integer");
else {
maximum = array[location];
printf("Highest even integer :%d", maximum);
}
getch();
}
int find_maximum(int a[], int n) {
int c, max, index;
max = -10000; // A very low number
index = -1; // shows that no even integer is found yet.
for(c = 1 ; c < n ; c++) {
if(a[c] > max && a[c] %2 == 0) {
index = c;
max = a[c];
}
}
return index;
}
int getNumbers(int arr[])
{
int c;
printf("You may enter a max. %d numbers, enter a number less than 1 to end.\n", MAXNUMBERS);
for(c = 0 ; c < MAXNUMBERS ; c++)
{
scanf("%d", &arr[c]);
fflush(stdin);
if(arr[c] < 1)
{
break;
}
}
}
You should first scan the array from the user which is what getNumbers function does.
Next you need to find the highest even integer which is what find_maximum funciton does.
this function returns index of the highest event integer in your array. the default value is -1 which indicates that no even value is found ! if it's given any other value means that found the highest even integer.
so now that you have the index you check if it's -1(not found) or it's found (returned index).
There is no sense to define an array for a sequence of numbers with undefined size that to determine the maximum value. When a next number is entered you can compare it with the current maximum value provided that the entered number is even.
The program can look the following way
#include <stdio.h>
int main( void )
{
int max = 0;
int value;
printf("Enter a sequence of integer numbers.\n"
"Enter a number less than 1 to end: ");
while (scanf("%d", &value) == 1 && !(value < 1))
{
if (value % 2 == 0 && max < value) max = value;
}
if (max != 0)
{
printf("Highest even integer: %d\n", max);
}
else
{
puts("No even integer");
}
}
As for your program then this loop is wrong.
for (c = 0 ; c < MAXNUMBERS ; c++)
{
location = find_maximum(array, MAXNUMBERS);
maximum = array[location];
}
For starters the number of entered values can be less than MAXNUMBERS. You have to use at least the variable amount_numbers in the condition.
Moreover the loop is not needed Because it does the same that is it calls several times the function find_maximum and nothing is changed with the function result between iterations of the loop. Moreover you have to check whether the variable location gets value 0 and whether the element with this index is less or greater than 1. Otherwise you can show invalid result.
As commented, you are only required to output the answer so there is no need to store the input in an array. This shows how to do it with a simple loop. The program also ends at non-numeric input (effectively a 0 value).
#include <stdio.h>
int main(void) {
int innum = 0;
int maximum = 0;
while(scanf("%d", &innum) == 1 && innum > 0) {
if(innum % 2 == 0 && maximum < innum) {
maximum = innum;
}
}
if(maximum < 2) {
puts("NO EVEN INTEGER");
}
else {
printf("Highest even integer: %d\n", maximum);
}
return 0;
}
Program session:
3 8 1 5 3 4 -5
Highest even integer: 8

How to read 2 lines of integer input in C?

I'm doing a project for my algorithms class and I'm having a lot of trouble with inputs. I'm trying to read an input like this:
6 0 2 3 1 3
5 9 2 1 3
The integers will need to go to
int num1; // num1 = 6
int num2; // num2 = 5
int array1[100]; // array1 = {0, 2, 3, 1, 3, 0, 0, ...}
int array2[100]; // array2 = {9, 2, 1, 3, 0, 0, ...}
The input will come from standard input, in the form of a file. So in terminal running the program would look like this:
cat input.txt | ./a.out
Where input.txt contains the two lines of integers.
Here is my flawed attempt so far:
while(scanf("%d%c", &temp, &ch) > 1){
if (ch != '\n'){
one[count] = temp;
}
else if (ch == '\n'){
count = 0;
two[count] = temp;
}
one[count] = temp;
count++;
if (ch != ' ')
{
printf("Invalid input. Please do int + space.\n");
return -1;
}
if ((temp >= 100) || (temp <= -100))
{
printf("Input is too big, must be between -100, 100.\n");
return -1;
}
if (one[0] < 1){
printf("Input for n cannot be smaller than one!");
return -1;
}
}
I think the main issue is that I'm just not sure how to deal with multiple lines of input. One line of input is fine by me but multiple lines is what trips me over.
You could fetch an entire line of input using the getline function and then iterate over that line, scanning one number at a time using the strtol function.
From the example in your question I assume that you want all remaining entries in the two arrays to be zero so don't forget to zero them out (either manually or using the memset function.).
And also don't forget to free() the buffer getline gave you.
Actually I ended up using scanf, here is the working code below. It really helped to read some of these comments and also refer to K&R
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 100
void shiftArrayBackByOne(int a[]){
for(int i = 1; i <= ARRAY_SIZE; i++){
a[i - 1] = a[i];
}
}
void printArray(int a[], int n){
for(int i = 0; i < n; i++){
printf("%d ", a[i]);
}
putchar('\n');
}
int main(){
int isLineTwo = 0;
int countOne = 0;
int countTwo = 0;
int inputNum;
int num1;
int num2;
int array1[ARRAY_SIZE];
int array2[ARRAY_SIZE];
char ch;
while(scanf("%d%c", &inputNum, &ch) > 0){
//Puts the input into different arrays depeding
//on value of isLineTwo
if (isLineTwo){
array2[countOne] = inputNum;
countOne++;
} else {
array1[countTwo] = inputNum;
countTwo++;
}
//Increment isLineTwo if ch is a 'newline'
if (ch == '\n')
{
isLineTwo++;
}
//Check if user inputs more than 2 lines
if (isLineTwo > 1){
printf("Hey, no more than 2 input lines!\n");
}
}
printArray(array1, countOne);
printArray(array2, countTwo);
num1 = array1[0];
num2 = array2[0];
shiftArrayBackByOne(array1);
shiftArrayBackByOne(array2);
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
printArray(array1, countOne);
printArray(array2, countTwo);
}
Look at my code below. Maybe it helps you.
Generally, if you know how many numbers will be inputted, you can read numbers one by one using scanf("%d", ...) and use fflush() when the expected amount is met to clear any other numbers in the buffer. This example assumes that the first two numbers are the respective lengths of each line. The input could look like:
// example input:
// 4
// 3
// 1 2 3 4
// 5 6 7
int main()
{
int it;
int it1 = 0;
int it2 = 0;
int line1[100];
int line2[100];
scanf("%d", &it1); // amount of line 1 numbers
scanf("%d", &it2); // amount of line 2 numbers
it = 0;
do
{
scanf("%d", &line1[it]);
} while (++it < it1);
fflush(stdin); // clear input buffer
it = 0;
do
{
scanf("%d", &line2[it]);
} while (++it < it2);
return 0;
}

Resources