This program uses an array and three functions to read inputs, sum up the ones and tens place of inputted integers, and compute the average of input integers. Why can't I get more than one input that is a positive integer? The program runs after one input that is within the limits of integers that are valid.
#include <stdio.h>
int read_data(int Ar[]);
void comp_sums(int Ar[], int size); // prototypes
double comp_avg(int Ar[], int size);
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar);
comp_sums(Ar, size);
avg = comp_avg(Ar, size);
printf("The average of the integers in the array: %lf\n", avg);
}
int read_data(int Ar[]) // reads inputted integers, stores in array
{
int flag;
char ch;
int i,j, num;
flag = 1;
i = 0;
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
return i;
}
}
void comp_sums(int Ar[], int size) /* computes sum of ones and tens place of the inputted integers into the array*/
{
int i, j;
int sum_ones, sum_tens;
sum_ones = 0;
sum_tens = 0;
for (i = 0; i < size; i++) {
sum_ones += Ar[i] % 10;
j = Ar[i] / 10;
sum_tens += j % 10;
}
printf("The sum of the ones is: %d\n", sum_ones);
printf("The sum of the tens is: %d\n", sum_tens);
}
double comp_avg(int Ar[], int size) // computes average of integers
{
int i, sum;
double avg;
sum = 0;
for (i = 0; i < size; i++) {
sum += Ar[i];
}
avg = (double)size / sum;
return avg;
}
When you take an array as an argument, you have to take the length as well,
because you have to check if you are reading/writing out of bounds. Forget for a
second that the return is at that incorrect position, the user can input more
values than the array can hold and you are doing nothing to prevent the buffer overflow.
So to fix your read_data function:
int read_data(int Ar[], size_t len)
{
if(Ar == NULL || len == 0)
return 0;
int i = 0, j, num;
// imortant to check the bounds
while (i < len) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
break;
} else {
Ar[i] = num;
i++;
}
}
return i;
}
I removed the flag bit because if num >=100, you would be ending the loop
anyway, so it's much simpler to do a break. Also the intention is more clearer.
Now you can call it:
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar, sizeof Ar / sizeof *Ar);
...
}
The problem is that you call return inside the whileloop. So as soon as you get a valid number, you'll return from the function.
Move it outside the loop. Like:
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
// return i; Incorrect
}
return i; // Correct
Related
So I need to do C program that asks 20 integers from user (number between 10-100) and print only the numbers that occurs only once.
#include <stdio.h>
int main() {
int n;
int i=20;
while(i-- && n <100 && n>10)
{
scanf("%d", &n);
}
printf("Number is not between 10-100. Try again");
return 0;
}
You need to remember the numbers in the array and check for repetitions.
Here you have a naive implementation (you can improve many things). Instead of user input I fill the array with random (pseudo random) numbers
void printDistinct(int *arr, size_t size)
{
for(size_t cnum = 0; cnum < size; cnum++)
{
int isDistinct = 1;
for(size_t index = 0; index < size; index++)
{
if(index != cnum)
if(arr[cnum] == arr[index])
{
isDistinct = 0;
break;
}
}
if(isDistinct)
printf("arr[%zu] = %d\n", cnum, arr[cnum]);
}
}
#define NNUM 50
int main(void)
{
int arr[NNUM];
srand(time(NULL));
for(size_t i = 0; i < NNUM; i++)
{
arr[i] = rand() % 50;
}
printDistinct(arr, NNUM);
}
https://godbolt.org/z/7a9ejfrav
I have make this program that calculates number factorization such as 60 = 2^2 * 5 * 3.
How can i modify my code in order to print POWERFUL NUMBERS such as 9000 = 2^3 * 3^2 * 5^3 without using math.h library and without using arrays?
Thank you very much!!
#include<stdio.h>
#define MAX 1000
int main(){
int num;
int counter;
int number;
char factorizationOutput;
int isAchiles = 0;
int factor=2;
for(counter=2;counter<=MAX;counter++){
isAchiles = 1;
number=counter;
int factor=2;
while(factor<number){
int power=0;
if(number%factor==0){
while(number%factor==0){
number=number/factor;
power++;
}
if(power == 1){
isAchiles = 0;
}
printf("%d^%d",factor,power);
if(number!=1)
printf(" X ");
}
factor++;
}
if(number!=1)
printf("%d^1.\n",factor);
if(isAchiles == 1){
printf("factorazation of number %d is: ",counter);
}
}
}
#include<stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
printf("%d = ", n);
for(int i = 1; i <= n; i++)
{
int count = 0;
for(int j = 1; j <= i; j++)
{
if(i % j == 0)
{
count++;
}
}
int l = 0;
if(count == 2)
{
while(n % i == 0)
{
l++;
n = n/i;
}
printf("%d^%d*", i, l);
}
}
}
When I ran this code why is it giving me incorrect output? In my system I'm getting the correct output. My output is the same as the one given in the link but still they wont accept it.
int main()
{
int t, n, b, i;
scanf("%d", &t);
while (t--) {
scanf("%d %d", &n, &b);
int area[n];
int max = 0;
area[0] = 0;
int p[n], w[n], h[n];
int count = 0;
for (i = 1; i <= n; i++) {
scanf("%d %d %d", &w[i], &h[i], &p[i]);
}
for (i = 1; i <= n; i++) {
if (p[i] <= b) {
area[i] = w[i] * h[i];
if (area[i] > max) {
max = area[i];
printf("%d\n", max);
count++;
}
}
}
if (count == 0) {
printf("no tablet\n");
}
}
return 0;
}
You are indexing out of the array bounds with
for(i = 1; i<=n; i++)
You can index an array length n with index 0 to n-1. So change both the loops to
for(i = 0; i < n; i++)
and remove the useless line
area[0] = 0;
Also, you should not output the result inside the loop, since if the data entry sequence is different from the example it prints a result more than once. Put that afterwards.
if(count == 0)
{
printf("no tablet\n");
}
else
{
printf("%d\n",max);
}
My sort function won't print the sorted array?
I'm trying to write a program that gathers array elements, sorts the array, then prints the factorial of each element. I don't want to get ahead of myself and write the recursive function if the array isn't being sorted correctly. The sort seems fine to me; people have criticized me using while loop but I don't know another way yet. Any input is appreciated.
#include <stdio.h>
int sorter(int numbList[]);
int getData(int numList[]);
//int recursive(int numList[]);
int main(void) {
int x;
int numberList[x];
getData(&numberList[x]);
sorter(&numberList[x]);
//recursive(&numberList[x]);
return 0;
}
//gets user input-data
int getData(int numbList[]) {
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d", &x);
printf("Enter the values for each element starting from first
element:\n");
for (i = 0; i < x; i++) {
scanf("%d", &numbList[i]);
}
printf("\nYou have filled the array list with\n");
for (i = 0; i < x; i++) {
printf("%d\n", numbList[i]);
}
return numbList[x];
}
//sorter function
int sorter(int numbList[]) {
int x;
int temp;
int swapped;
while (1) {
swapped = 0;
for (int i = 0; i < x; i++) {
if (i > numbList[i + 1]) {
temp = numbList[x];
numbList[x] = numbList[x + 1];
numbList[x + 1] = numbList[x];
swapped = 1;
}
if (swapped == 0) {
break;
}
}
printf("Array as sorted:\n");
for (int i = 0; i < x; i++) {
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}
//recursive factorial function
/* int recursive(int numbList[]) {
int b = 0;
numbList[b] *= numbList[b - 1];
return 0;
} */
Some hints as comments in your code:
It still won't do the job, but get you in better shape...
int main(void)
{
//uninitialized x!
int x;
//Even if you get a value for x, VLAs are depreciated
int numberList[x];
//Both calls get the adress of last value + 1 in numberList.
//So you a) go out of the array bounds, and b) why would you want
//the last element's address??
//Just use it like getData(numberList);
getData(&numberList[x]);
sorter(&numberList[x]);
return 0;
}
//gets user input-data
//What is the return value for?
int getData(int numbList[])
{
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d",&x);
printf("Enter the values for each element starting from first element:\n");
for(i=0;i<x;i++){
scanf("%d",&numbList[i]);
}
printf("\nYou have filled the array list with\n");
for(i=0;i<x;i++){
printf("%d\n",numbList[i]);
}
//see above
return numbList[x];
}
//sorter function
//Again, what and why return?
int sorter(int numbList[])
{
//uninitialized x!
int x;
int temp;
int swapped;
while(1)
{
swapped=0;
for(int i=0;i<x;i++)
{
//What do you compare here? Think.
if(i>numbList[i+1])
{
temp=numbList[x];
numbList[x]=numbList[x+1];
//What do you have temp for??
numbList[x+1]=numbList[x];
swapped=1;
}
//Pretty sure you want an else clause here
if(swapped==0)
{
break;
}
}
printf("Array as sorted:\n");
for(int i=0;i<x;i++)
{
printf("%d\t",numbList[x]);
}
return(numbList[x]);
}
}
There are multiple problems in your code:
the number of elements x is uninitialized when you define the array numbList[x]. This has undefined behavior. You should pass a pointer to the count to getData and this function should update this value, allocate the array, read the values and return a pointer to the array.
You should not break strings on multiple lines without a \
The swap code is broken: the test if (i > numbList[i + 1]) is incorrect, it should be
if (numbList[i] > numbList[i + 1])
the swap code should use i instead of x as an index and the last assignment in the swap code should store temp into numbList[i + 1].
the inner loop should stop at x - 1 to avoid reading past the end of the array.
you should let the inner loop run to the end and break from the outer loop if swapped == 0.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int *getData(int *count);
void sorter(int numList[], int count);
int main(void) {
int x;
int *numberList;
numberList = getData(&x);
if (numberList != NULL) {
printf("Elements entered:");
for (int i = 0; i < x; i++) {
printf(" %d", numberList[i]);
}
printf("\n");
sorter(numberList, x);
printf("Sorted array:");
for (int i = 0; i < x; i++) {
printf(" %d", numberList[i]);
}
printf("\n");
free(numberList);
}
return 0;
}
//gets user input-data
int *getData(int *countp) {
int i, x;
int *numbList;
printf("Enter the number of elements: ");
if (scanf("%d", &x) != 1 || x <= 0) {
printf("Invalid size:");
return NULL;
}
numbList = calloc(sizeof *numbList, x);
if (numbList == NULL) {
printf("Memory allocation error:");
return NULL;
}
printf("Enter the element values: ");
for (i = 0; i < x; i++) {
if (scanf("%d", &numbList[i]) != 1) {
free(numbList);
return NULL;
}
}
*countp = x;
return numbList;
}
//sorter function
void sorter(int numbList[], int x) {
for (;;) {
int swapped = 0;
for (int i = 0; i < x - 1; i++) {
if (numbList[i] > numbList[i + 1]) {
int temp = numbList[i];
numbList[i] = numbList[i + 1];
numbList[i + 1] = temp;
swapped = 1;
}
}
if (swapped == 0) {
break;
}
}
}
You can use bubble sort algorithm technique which is fast sorting algorithm and it uses for loop instead of while loop
int bubbleSorter(int numbList[])
{
int temp;
int i, x;
bool swapped = false;
for (i = 0; i < x - 1; i++)
{
swapped = false;
for (j = 0; j < x - 1 - i; j++)
{
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
else {
swapped = false;
}
}
// if no number was swapped that means
// array is sorted now, break the loop.
if (!swapped) {
break;
}
printf("Array as sorted:\n");
for (int i = 0; i<x; i++)
{
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}
I was wondering, how can I add up the divisors displayed once I run my code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
scanf("%d", &n);
for(i = 1; i < n; i++)
{
if(n % i == 0)
{
printf("%d\n", i);
}
}
return 0;
}
If I were to enter, say, 25, it would print out 1, 5. I was wondering how to add up the two numbers 1 and 5?
Could it be as simple as this? You will want to use a simple increment operator (+=), to increment the variable sum.
int main(void)
{
int n, i, sum = 0;
if( scanf("%d", &n)!= 1){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
for(i = 1; i < n; i++)
{
if(n % i == 0)
{
printf("%d\n", i);
sum += i;
}
}
printf("Sum of divisors: %d\n", sum);
return 0;
}
How to add up divisors of an integer n?
Iterating n times as with for(i = 1; i < n; i++) can take a long time when n is some high value, especially if code used 64-bit integers. Instead only iterate sqrt(n) times - much faster
int factor_count(int number) {
if (number <= 1) {
return TBD_Code(number); // OP needs to define functionality for these cases.
}
int sum = 1;
int quotient;
int divisor = 1;
do {
divisor++;
quotient = number/divisor;
int remainder = number%divisor;
if (remainder == 0) {
sum += divisor;
if (quotient > divisor) sum += quotient;
}
} while (divisor < quotient);
return sum;
}
Additional improvements noted here.