In my program, I want to input some numbers until I input 0. When I input 0, the program must stop and show the numbers in order. It's almost finish but I have one problem. I must not use an array, it's forbidden .
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int number;
int *ptr;
int i = 0, j = 0;
ptr = &number;
number = (int*)malloc(2000);
do{
printf("Enter a number : ");
scanf("%d",ptr);
printf("\n######\n");
printf("%d. number = %d \t%p\n",i+1,*(ptr),(ptr+i));
printf("\n######\n");
i++;
} while(((number)) != 0);
printf("\n!!!!############!!!!\n");
for(j = 0 ; j < i; j++){
number=number+j;
printf("%d. number = %d \t%p\n",j+1,(number),&(number));
}
return 0;
}
You code has a number of problems. I think you tried something too challenging for your level of understanding right now.
You should learn about pointers from the beginning and make sure you understand the * and & operators. Try writing some small simple programs so you have a good grasp on them.
From there you can move on to scanf and malloc, since they rely on heavily pointers.
Here is a working version of your code:
int main()
{
int* number; // this is should be a pointer
//int *ptr;
int i = 0, j = 0;
//ptr = &number;
number = (int*)malloc(2000);
do{
printf("Enter a number : ");
// scan an integer into the ith place in memory
// after the address pointed to by "number"
scanf("%d",number+i); //number+i is already an address, don't use &
printf("\n######\n");
printf("%d. number = %d \t%p\n",i+1,*(number+i),number+i);
printf("\n######\n");
i++;
// need to use a -1 since we incremented i
}while(*(number+i-1) != 0);
printf("\n!!!!############!!!!\n");
for(j = 0 ; j < i; j++){
//=number+j;
printf("%d. number = %d \t%p\n",j+1,*(number+j),number+j);
}
return 0;
}
Related
So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
// takes string input
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//turns the string to int
int x = atoi(s);
int temp = x, len = 0;
//calculates string length
while (x != 0) {
x = x / 10;
len++;
}
x = temp;
//parses through the string and matches digits with each number
for (int j = 0; j < 10; j++){
int count = 0;
for(int i = 0; i < len; i++){
if(x % 10 == j){
count++;
}
x = x / 10;
}
x = temp;
printf("%d ", count);
}
return 0;
}
To write a correct and reasonable digit-counting program:
Do not allocate any buffer for this.
Create an array to count the number of times each digit occurs. The array should have ten elements, one for each digit.
Initialize the array to zero in each element.
In a loop, read one character at a time.
Leave the loop when the read routine (such as getchar) indicates end-of-file or a problem, or, if desired, returns a new-line or other character you wish to use as an end-of-input indication.
Inside the loop, check whether the character read is a digit. If the character read is a digit, increment the corresponding element of the array.
After the loop, execute a new loop to iterate through the digits.
Inside that loop, for each digit, print the count from the array element for that digit.
Your approach is way to complicated for a very easy task. This will do:
void numberOfDigits(const char *s, int hist[10]) {
while(*s) {
if(isdigit(*s))
hist[*s - '0']++;
s++;
}
}
It can be used like this:
int main(void) {
char buf[1024];
int hist[10];
fgets(buf, sizeof buf, stdin);
numberOfDigits(s, hist);
for(int i=0; i<10; i++)
printf("Digit %d occurs %d times\n", i, hist[i]);
}
This can also be quite easily achieved without a buffer if desired:
int ch;
int hist[10];
while((ch = getchar()) != EOF) {
if(isdigit(ch))
hist[ch - '0']++;
}
#include <stdio.h>
int main(void) {
int input = 1223330;
int freq[10] = {0};
input = abs(input);
while(input)
{
freq[input%10]++;
input /= 10;
}
for(int i=0; i<10; ++i)
{
printf("%d: %.*s\n", i, freq[i], "*************************************************");
}
return 0;
}
Output:
Success #stdin #stdout 0s 5668KB
0: *
1: *
2: **
3: ***
4:
5:
6:
7:
8:
9:
This app is currently limited by the size of an int (approximately 9 or 10 digits).
You can update it to use a long long easily, which will get you to about 19 digits.
I was trying to make a program where if I enter an integer, the program would find out the bigger number and subtract it by the smaller number. This part, I got it.
The problem is, the infinite loop part.
I tried to get type in two integers keep on printing with the while loop, and break when at least one character is typed in.
For example, if I type in 2 #, it would break.
But I couldn't find the write place to get the break; within the code and therefore whenever I enter a character it would keep on creating an infinite loop.
Is there any way to create a break in this code? I humbly ask for advice...
The following is the code which I couldn't put the break
(By the way, the reason I did the condition in while as sizeof(i)==4 || sizeof(j)==4 was to make it so it would only enter an integer, since the size of an integer is 4)
int main()
{
int i, j;
int result;
while (sizeof(i)==4 || sizeof(j)==4){
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i){
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
The bottom code is the one I tried to put break but failed (it kept creating an infinite loop)...
int main()
{
int i, j;
int result;
while (sizeof(i)==4 || sizeof(j)==4){
if (sizeof(i) == 4 || sizeof(j) == 4) {
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
else
break;
}
return 0;
}
and here's a code where I got rid of the sizeof and used while(1), though there wasn't much change in the fact that the break didn't work...
int main()
{
int i, j;
int result;
while (1){
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
You can't use sizeof(i) to do run-time checks! This is a compile-time constant that, in your case (32-bit integers) will always evaluate to 4.
In order to check that two valid integers have been given, you can check the return value of the scanf function (it gives the number of fields successfully scanned):
#include <stdio.h>
int main()
{
int i, j;
int result;
while (1) {
printf("type in two integers : ");
if (scanf("%d %d", &i, &j) != 2) break; // Break here if we didn't get two integers
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
Feel free to ask fir further clarification and/or explanation.
Drop the whole concept of endless loop with break inside if.
Make a condition for the loop based on the return value of scanf(), that is practically what it is designed for.
#include <stdio.h>
int main()
{
/* always init everything */
int i=0, j=0;
int result=0;
printf("type in two integers : ");
while (2==scanf("%d %d", &i, &j))
{
if (i < j) {
result = j - i;
}
else /* removed second if, to have a meaningful result for i==j */
{
result = i - j;
}
printf("%d\n", result);
printf("type in two integers : ");
}
return 0;
}
I'd probably actually use do {...} while (...) with a variable storing the return value of scanf()for being used in the loop condition. I'd consider it more elegant for not having to copy the print, but I kept it closer to your code structure.
More comments on your code:
as explained in comments, sizeof() works differently than you seem to think; it is static and does not change at runtime and hence cannot be used in a loop condition
with while (sizeof(i)==4 || sizeof(j)==4){if (sizeof(i) == 4 || sizeof(j) == 4){/* a */} else {/* b */}, b cannot ever be reached, because the conditions of while and if are identical
check the possible outcomes of the if conditions inside the loop, you are leaving the one with i==j undefined and return an uninitialised value
always init all variables as a habit
for a good MRE include the include lines
On your request, here is a proposal for the do-while alternative:
#include <stdio.h>
int main()
{
/* always init everything */
int i=0, j=0;
int result=0;
int iScanned=0;
do
{
printf("type in two integers : ");
iScanned=scanf("%d %d", &i, &j); /* keep the return value for loop */
if (i < j) {
result = j - i;
}
else /* removed second if, to have a meaningful result for i==j */
{
result = i - j;
}
if(2==iScanned) printf("%d\n", result); /* if to avoid awkward last output */
} while (2==iScanned);
return 0;
}
I have this simple code that inserts the number entered in the terminal at the position of the vector at each loop.
int main()
{
int vector[5];
int i;
for (i = 0; i < 5; i++)
{
printf("Number: ");
scanf_s("%d", &vector[i]);
}
system("pause");
return 0;
}
My question is how I break the loop as soon as I type the number 0.
For example, imagine that my vector have 50 positions and I type 10 positions with positive integers numbers and now I want the loop ends when I enter zero and the rest of the 40 positions remain blank.
I imagine it's with the while loop, but I could not even get close to the result I want.
#define MAX_SIZE (5)
int main()
{
int vector[MAX_SIZE] = {0};
int i;
memset(vector, 0xFF, sizeof(vector)); //sets all vector[i] to -1 on init;
for (i = 0; (i < MAX_SIZE) && (i?vector[i-1]:1) ; i++) //you can add the condition to break from the for loop here. This is more complicated but its just for demonstration.
{
printf("Number: ");
scanf_s("%d", &vector[i]);
}
system("pause");
return 0;
}
The above sample code demonstrates the using the for loops conditional expression as a means to break the loop. The ternary in there prevents the i=0 case resulting in an out of bounds index, due to the way you structured your loop. The better/more readable way is below:
#define MAX_SIZE (5)
int main()
{
int vector[MAX_SIZE] = {0};
int i;
memset(vector, 0xFF, sizeof(vector)); //sets all vector[i] to -1 on init;
for (i = 0; i < MAX_SIZE; i++)
{
printf("Number: %d\n", i);
scanf_s("%d", &vector[i]);
if(vector[i] == 0)
{
break;
}
}
//system("pause");
printf("Broke the loop when i was %d\n", i);
return 0;
}
The difference between the two besides readability is that i will be incremented one extra time in the first one. Also, make sure to initialize all the variables you declare (all your vector elements are stack garbage, the 0xFF memset assigns them all to -1).
I have a program that I would like to dynamically allocate an array that gets filled by the user through the terminal argument line in Linux. After the user enters the numbers, the array of numbers should be sorted.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
int array[100];
int count = 0;
while(1){
printf("please enter a number: \n");
scanf("%d", &i);
if(i == 0){
for (int k = 0; k < count -1; k++) {
if(array[k] <= array[k + 1]){
int temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
for (int j = 0; j < count; ++j)
{
printf("%d ", array[j]);
}
printf("\n");
break;
} else {
array[count] = i;
count++;
}
}
}
This only sorts the array if I type the numbers in low to high, but if I enter the numbers from high to low eg. 4, 3, 2 and then 1, it prints 2, 3, 1 and then 4, instead of the 1,2,3,4 that it does if I type it that way.
I don't want to initialize the array with 100, I just can't get it to work if I don't initialize it. I want it to be increased if necessary.
Thank you :)
Errors/Deviations from the proposed program:
As mentioned, you want to use command line arguments - You need main(argc,*argv[]) instead of main().
For dynamic allocation you need malloc/calloc but instead of that you have used static array.
Your code shows you are not clear about concept of sorting, leave the program aside and use a pen and paper first to clear that.
This question already has answers here:
how to scanf unknown amount of integer numbers into array in C?
(3 answers)
Closed 6 years ago.
I am doing a assignment which requires the input of a list of numbers and get the output when I press Enter on the keyboard. This is the code I am trying the use to get the list of numbers when I enter, but it doesn't work:
#include <stdio.h>
int main(){
int arra[100];
int i ;
int j = -1;
while (scanf("%d",&i) != 1){
arra[++j] = i;
}
printf("\n");
int k;
for(k = 0; k < j; k++){
printf("%d",arra[k]);
}
return 0;
}
I want to print the elements of arra.
First off, massive kudos for testing the return value from scanf, most people just blindly assume it works. It's just a shame you're using it in the wrong way :-)
You want the loop to continue as long as the return value is 1, meaning that you managed to scan an integer. That means it should be:
while (scanf ("%d", &i) == 1) {
That also means that any non-numeric input will cause scan failure and hence the while loop will exit. So, if you enter:
3 1 4 1 5 9 stop
you should successfully see the numeric values from the array.
The only other thing is to clean up your j handling since the k loop will stop early. This can be done with:
for (k = 0; k <= j; k++) {
Alternatively, leave that loop alone and just change how you initialise and modify j:
int j = 0;
:
arra[j++] = i;
I tend to find the second choice more C-like since j is then a count of the elements in the array rather than the maximum index.
And, of course, you're open to a buffer overflow attack at the moment since you assume nobody will enter more than a hundred numbers. So, don't use this as a homework solution (what you have is good enough with the slight bug fixes) but I'd tend to write it as something like:
#include<stdio.h>
#define SZ 100
int main (void){
int arra[SZ], i, nxt = 0;
while ((nxt < SZ) && (scanf ("%d", &(arra[nxt])) == 1))
nxt++;
printf ("\n");
for (i = 0; i < nxt; i++)
printf ("%d ", arra[i]);
return 0;
}
Check the below code:
#include<stdio.h>
int main(){
int arra [100];
int i ;
int k;
int j = 0; /* index from 0 */
printf("Keep entering numbers and press q once done \n");
while (scanf("%d",&i) == 1){ /* scan for integers */
arra[j++] = i;
}
printf("\n");
for(k = 0; k < j; k++){
printf("%d",arra[k]);
}
return 0;
}