The code will not produce a compiler error, but i am trying to update the memory allocation after every loop if the user types Y, and increase the size of the memory. But after the first while loop, when i try to print the list of numbers using the first for loop, it will just show one number which will be 0.00000. I can't get it to update (which is what I am trying to do in the second if loop). Any help is appreciated.
#include<stdio.h>
#include<stdlib.h>
int main()
{
double *userNum = (double*)malloc(sizeof(double));
double sum = 0;
char userChar = 'Y';
int i = 0;
int j = 0;
if (userNum == NULL) {
printf("Error with memory");
return 1;
}
while (userChar == 'Y' || userChar == 'y') {
printf("Enter a number\n");
scanf("%lf", userNum);
printf("List of numbers:\n");
for (j; j < (i + 1); j++) {
printf( "%lf\n", userNum[j]);
}
printf("More numbers (Y/N)? \n");
getchar();
scanf("%c", &userChar);
if (userChar == 'Y' || userChar == 'y') {
userNum = realloc(userNum, (i + 2) * sizeof(double));
i++;
}
}
return 0;
)
You need to reinitialize your loop counter to 0 when printing out the numbers :
for (j = 0; j < (i + 1); j++) {
printf("%lf\n", userNum[j]);
}
And you need to increment the position in userNum that you scan the numbers into :
scanf("%lf", &userNum[i]);
Related
so i'm a beginner and trying to solve a small project about making fibonacci number.
The code essentially is about typing n (the sequence) and it will show you what value of fibonacci number in that n-sequence.
but of course the code went wrong, the code just stop until i type the n-sequence, and nothing being printed after that. Can anybody check my code pls?
#include <stdio.h>
int main(){
int n;
int seq[n];
int i;
printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
scanf("%d", &n);
for(i = 0; i <= n; i++){
if(i == 0){
seq[i] = 0;
}
else if(i == 1){
seq[i] = 1;
}
else if(i > 1){
seq[i] = seq[i-1] + seq[i-2];
}
}
if(i == n){
printf("the value in sequence %d is %d", n, seq[n]);
}
return 0;
}
You need to declare the variable length array seq after you entered its size
For example
int n;
int i;
printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
scanf("%d", &n);
int seq[n + 1];
The size of the array is specified as n + 1 because the user is asked to enter the fibonacci number starting from 0.
Also this for loop will be correct provided that the array has n + 1 elements.
for(i = 0; i <= n; i++){
It is better to write it like
for(i = 0; i < n + 1; i++){
And this if statement
if(i == n){
does not make a sense. Just output the value of the array element seq[n].
apparently, in the loop, you set the boarder as i<=n while the array seq[n] is with the size of n. So i must be less than n.
n is uninitialized. It contains a garbage value.
Don't use scanf() for reading user input. It is very error-prone. Just try typing some string and see what happens. Better use fgets() in combination with sscanf().
int n;
char input[255];
printf("Number of sequence: ");
fgets(input, sizeof input, stdin);
input[strcspn(input, "\n")] = '\0';
if (sscanf(input, "%d", &n) != 1) {
// Handle input error
}
int seq[n+1]; // Edited: n+1 because fib starts from 0
int i;
for (i = 0; i < n+1; i++) {
if (i == 0 || i == 1)
seq[i] = i;
else
seq[i] = seq[i-1] + seq[i-2];
}
I'm trying to make a C program to insert elements into an array until user inputs a 0 or less number, as the title says. But when I print the array out, it doesn't show the numbers I inputted. I have tried using a while as well as do-while loops but without success.
#include <stdio.h>
int main() {
int data[100];
int i;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
int n = sizeof(data[i]);
for (int i = 0; i < n; i++) {
printf("%d ", &data[i]);
}
}
Try this:
#include <stdio.h>
int main() {
int data[100];
int i;
int counter = 0;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
counter++;
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
for (int j = 0; j < counter - 1; j++) {
printf("%d ", data[j]);
}
}
The problem was that you had printf("%d ", &data[i]); instead of printf("%d ", data[i]);.
And also you've trying to get the sizeof() of an element data[i], not the size of the whole array. That's why there's counter in my code.
int n = sizeof(data[i]);
this is wrong, you want
int n = i;
sizeof(data[i]) gives you the size of an int (4 on my machine)
On the other hand, you need to check the result of scanf, if a bad input is entered do not increment the counter, something like:
int i = 0;
while (i < 100)
{
int res = scanf("%d", &data[i]);
if (res == EOF)
{
break;
}
if (res == 1)
{
if (data[i] <= 0)
{
break;
}
i++;
}
else
{
// Sanitize stdin
int c;
while ((c = getchar()) != '\n');
}
}
Finally, scanf wants a pointer to the object, but this is not the case of printf:
printf("%d ", &data[i])
should be
printf("%d ", data[i])
int main()
{
int r, c, i=0, size_e, size_j;// First list of ints to be used in the program
printf("Input numbers of elements in the array: ");//Initializing user to ask for elements to the array
while(scanf("%d", &size_e) != 1)
{
printf("Invalid entry, please input a valid entry: \n");
while(getchar() != '\n' ){}
}
printf("How many columns do you have: ");//Number of columns
while(scanf("%d", &size_j) !=1 )
{
printf("Invalid entry, please input a valid entry: \n");
while(getchar() != '\n' ){}
}
while ((size_e % size_j) != 0)
{
printf("Number of elements must be divisible by the number of columns. Try again! \n ");
while(getchar() != '\n' ){}
exit (0);
}
int array[size_e];
printf("The error is after this: ");
for (r = 0; r < size_e ; r++)
{
printf("Input the value for %d: ", r + 1);
while(scanf("%d", &array [r]) != 1)
{
printf("Please input a correct value: ");
while(getchar() != '\n' ){}
}
}
printf("The error is after this: ");
int **matrix[size_e / size_j][size_j];
for (r = 0; r < (size_e / size_j) ; r++)
{
for (c = 0; c < size_j; c++)
{
**matrix[r][c] = array[i];
++i;
}
}
printf("This is your matrix: \n");
printf("The error is after this: ");
for (r=0; r< (size_e / size_j) ; r++)
{
for (c = 0; c < size_j; c++)
{
printf("%d ", **matrix[r][c]);
if (c == size_j - 1)
printf("\n");
}
}
int row, col, val;
printf("Type in what value you wish to change indicated <row> <column> <value>\n or enter any letter to quit to quit \n ");
while((scanf("%d %d %d", &row, &col, &val ) == 3))
{
**matrix[row][col] = val;
printf("Type in what value you wish to change indicated <row> <column> <value>\n or enter any letter to quit \n ");
while(getchar() != '\n' ){}
for (r=0; r< (size_e / size_j) ; r++)
{
for (c = 0; c < size_j; c++)
{
printf("%d ", **matrix[r][c]);
if (c == size_j - 1)
printf("\n");
}
}
}
return 0;
I am a greenhorn to coding and I've been tripped up on this for quite some time. My code was working previously deferencing the address through ((blah + blah) + blah) but I'm required to use an array of pointers to convert the 1d user defined array to the 2d user defined "matrix". Only issue is after the user puts in their inputs, it kicks me out following int array[size_e];
printf("The error is after this: ");
All the operations after don't work but the compiler doesn't give me any flags
matrix is a 2-dimensional array of pointers to pointers. But you never initialized any of the pointers.
If you want the elements of matrix to refer to the corresponding elements of array, they should just be pointers, not pointers to pointers. And then you need to set them to the addresses of the array elements.
int *matrix[size_e / size_j][size_j];
for (r = 0; r < (size_e / size_j) ; r++)
{
for (c = 0; c < size_j; c++)
{
matrix[r][c] = &array[i];
++i;
}
}
After this, accessing *matrix[r][c] is equivalent to accessing array[r * size_j + c].
I have written a Guess the Movie game in the C programming language. My logic seems to be correct but whenever I run the program, it doesn't work as expected.
Here is my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ran = 1;
int l, j = 0, i = 0, total = 0, d = 0;
char b;
char a[20];
char s[1000];
int z;
FILE *my;
printf("Enter your name:\n ");
scanf("%s", s);
ran = rand() % 6;
if (ran == 1)
{
my = fopen("my1.txt", "r");
}
else if (ran == 2)
{
my = fopen("my.txt", "r");
}
else if (ran == 3)
{
my = fopen("my2.txt", "r");
}
else if (ran == 4)
{
my = fopen("my3.txt", "r");
}
else if (ran == 5)
{
my = fopen("my4.txt", "r");
}
for (d = 0; d < 20; d++)
fscanf(my, "%c", &a[d]);
fclose(my);
printf("GUESS THE MOVIE GAME\n");
for (j = 0; j < 7; j++)
{
if (a[j] == 'm')
{
printf("M ");
}
else
{
printf("_ ");
}
}
printf("\n");
printf("Let's begin the game\n");
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
printf("enter character number %d\n",i+1);
scanf("%c", &b);
if (b == a[i])
{
printf("its a right guess\n");
total = total + 4;
i++;
}
else if (b != a[i])
{
printf("Wrong choice\n");
if (total == 1 || total == 0)
{
total=0;
}
else
{
total = total - 2;
}
}
}
}
printf("You have guessd the movie\n");
printf("The movie name is: ");
for (i = 0; i < 7; i++)
{
printf("%c",a[i]);
}
printf("Your score is %d\n",total);
}
This is the program output that I get each time I run the above code:
Enter your name:
raj
GUESS THE MOVIE GAME
_ _ _ _ M _ _
Let's begin the game
Enter character number 1
Wrong choice
Enter character number 1
I
Wrong choice
Enter character number 1
Wrong choice
Enter character number 1
Besides the deficiencies pointed out in comments, there's this major logic error:
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
…
}
}
If the loop encounters an m, it repeats endlessly. Eliminate the if (a[i] != 'm') or add an else ++i.
I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.