I am writing a calculator in C, but it will take input like 1+2*9/5.
I am not an expert in C, so I thought I can ask the user how many numbers he has (for example let's say 4), then asking 3 times "enter the number, enter operator" and 1-time "enter number". Then putting all inputs to an empty array respectively then doing the operations by looping through the array. But of course, I've got problems.
#include <stdio.h>
int main(void) {
int how_many;
printf("How many numbers do you have to calculate?");
scanf("%d", &how_many);
int number_entry = how_many; // for example 1+2*9/5 has 4 numbers
int operator_entry = how_many - 1; // and 3 operators
int number_in;
char operator_in;
int all_inputs[(number_entry + operator_entry)];
for (int j = 0; j < operator_entry; j++) {
printf("Enter the number : ");
scanf("%d", &number_in);
all_inputs[j] = number_in;
printf("\n");
printf("Enter the operation as + for add, - for substract, * for "
"multiply and / for division");
scanf(" %c", &operator_in);
all_inputs[j + 1] = operator_in;
}
printf("Enter the number : ");
scanf("%d", &number_in);
all_inputs[operator_entry + 1] = number_in;
for (int k = 0; k < (2 * how_many) - 1; k++)
printf("%s\n", all_inputs[k]);
return 0;
}
As you can see from the code, looping through the code to append inputs into the array is not working because I am doing
j=0
append a number to all_inputs[0]
append operator to all_inputs[0+1]
j=1
Now, the operator will be replaced with a number.
And another problem is, it shows "enter a number" just once and then loops the "enter the operator".
ss for problem
If you know any other way to do this, please let me know. Again, I am not a pro in C.
Related
I am trying to code a program that asks the user for the # of rows and columns and generates a 2d array (a matrix) corresponding to their input. I then ask for a second matrix (same dimensions), then I do some math on the 2 matrices. I'm stuck on how to use the scanf function to get the user-inputted matrix. According to the guidelines, the user input will be in the shape of the matrix itself, ex if it is a 2x2 matrix the user enters:
12 10 (then on the next line)
10 10
How do I use the scanf function appropriately to copy this matrix into the 2d array that I've created? I know that you can do scanf("%d %d %d", &int1, &int2, &int3), but I don't know if this will work for a user-determined matrix, since the length could be 2, 10, even a 100 (which is max length for this problem).
#include <stdio.h>
int main(void) {
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
/*User enters matrix in the form:
12 10
10 10
*/
printf("Enter Matrix A\n");
for(int i=0; i<sizeof(matrixA); i++){
for(int j=0; j<sizeof(matrixA[i]);i++){
scanf("%d ",&matrixA[i][j]);
}
}
//to see if scanf worked
for (int i = 0; i<sizeof(matrixA); i++) {
for(int j=0; j<sizeof(matrixA[i]);i++) {
matrixA[i][j] = '.';
printf("%c ",matrixA[i][j]);
}
printf("\n");
}
int matrixB[r][c];
printf("Enter Matrix B\n");
return 0;
}
You are right that
scanf( "%d %d %d", &int1, &int2, &int3 );
will only work if the number of parameters is fixed at compile-time. It cannot be changed at run-time.
Your idea of calling
scanf("%d ",&matrixA[i][j]);
in a loop instead is correct, in principle. However, you should not have a space character in the format string, as this will cause scanf to continue to read input from the input stream, and it will only return after it has encountered a non-whitespace character. This is usually not what you want.
Also, the line
for(int i=0; i<sizeof(matrixA); i++){
is wrong, because sizeof(matrixA) is the size of the array in bytes. Since you instead want to get the number of elements in the outer array, you could write sizeof matrixA / sizeof *matrixA instead. (The parentheses are only necessary when referring to types, not variables.) However, in this case, it would be easier to simply use r instead.
The line
for(int j=0; j<sizeof(matrixA[i]);i++){
is wrong. You probably intended to write j++ instead of i++.
Also, when printing variables of type int with printf, you should usually use %d instead of %c, because otherwise the value may be truncated if the value is higher than 127.
It is unclear what the line
matrixA[i][j] = '.';
is supposed to accomplish, as this will overwrite the previous input of scanf (assuming that you fix your loop as described above).
After fixing all of the issues mentioned above, your code should look like this:
#include <stdio.h>
int main(void)
{
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
printf("Enter Matrix A:\n");
for ( int i=0; i < r; i++ )
for( int j=0; j < c; j++ )
scanf( "%d", &matrixA[i][j] );
//to see if scanf worked
printf( "Input complete, the array contents are:\n" );
for ( int i=0; i < r; i++ )
{
for( int j=0; j < c; j++ )
printf( "%d ",matrixA[i][j] );
printf( "\n" );
}
return 0;
}
This program has the following behavior:
Please enter the number of rows : 4
Please enter the number of columns : 4
Enter Matrix A:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input complete, the array contents are:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
POSIX-specific answer
Well, you don't.
There are two ways to get that done:
Slice stdin into rows by the '\n' character n times; later slice every row in n columns by ' ' the whitespace. getline and strtok come in handy here.
The other approach is more efficient and as usual more complicated: rather than slicing into rows first, you iterative cut-off cols, counting them, and when count == n comes true, you expect '\n' to be there thus ending another line. I wouldn't suggest this approach.
So roughly your codes looks something like:
ssize_t nread;
for (sizet_t i = 0; i < n; i++) {
char *line = NULL;
if ((nread = getline(&line, &len, stream)) != -1) {
fprintf(stderr, "Bad format: %il-th line expected.", i + );
exit(EXIT_FAILURE);
}
char* token = strtok(line, " ");
for (size_t ii = 1 /* because you've already cut-off the first token */; i < n; ii++) {
token = strtok(NULL, " ");
}
}
Of course, you have to parse your char * tokens, but that is something I leave to you as an exercise. It also quite sloppy and does not do any sort of validation a production code is expected to do.
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++);
Can't get the if statements/while loop to work. If I make raceChosen an int it will never allow me to enter choose another race. When I use a char the if statements don't work. I have absolutely no idea who to fix this. Any assistance that could be provided would be appreciated.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
struct player { /*a struct to hold the player information.*/
int type[7];
int name[12];
int Smartness[7];
int Strength[7];
int MagicSkills[7];
int Luck[7];
int Dexterity[7];
int lifePoints[3];
}player;
int main(void)
{
struct player* ptr;
srand(time(NULL));
int numberPlayers,i,j,Smartness,Luck,Strength,Dexterity;
int MagicSkills,name,slots,x,Hill,City,LevelGround,m,lifePoints;
lifePoints = 100;
char raceChosen[1];
printf("Please enter the number of players you would like");
scanf("%d",&numberPlayers); /*take in the number of players*/
struct player plyr[numberPlayers];
i = 0;
while( i<numberPlayers )
{
printf("Please enter the race you would like to play as \n"
"Press elf for Elf \n"
"Press 1 for Human \n" /*taking in the race from the user*/
"Press 2 for Ogre \n"
"Press 3 for Wizard \n");
scanf(" %c",&raceChosen);
if(raceChosen == "0"){
printf("Please enter your name \n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength); /* generating the character */
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
if(raceChosen == "1"){
printf("Please enter your name \n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength);
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
}
i++;
}
}
First of all, I would recommend you try to compile your code before asking questions.
Anyways, let's go through your compile errors step by step:
Line 43: Passing the wrong variable type to scanf
You only need one character from standard input, so no need for a string array (char *), just use a character variable (char)
So char raceChosen[1] becomes char raceChosen
Lines 46 and 69: Comparing two strings with == operator
This is a good reason to start learning the basics of C programming. To compare two strings in C, you use strcmp(first_string, second_string).
Since raceChosen is not a character array anymore, we don't need strcmp, we can still use == but the quotes around 0 and 1 have to be single quotes.
So your if statements become if(raceChosen == '0') and if(raceChosen == '1'). This is how you compare two characters.
Lines 23, 24 and 32, Lots of unused variables
I hope you're gonna use those later because this is bad practice.
Line 48: Using an uninitialized variable
Just initialize ptr to NULL (ptr = NULL) right after you declare it.
Just a notice tho, you don't need to use a pointer to struct here, unless you were asked to. A simple struct would do the work.
Line 98: Extraneous closing brace
Yup, just as it says, too many closing braces.
Change like this, i hope it work for you.
int main(void)
{
struct player* ptr;
srand(time(NULL));
int i,j,Smartness,Luck,Strength,Dexterity;
int MagicSkills,name,slots,x,Hill,City,LevelGround,m,lifePoints;
lifePoints = 100;
char raceChosen[1];
static int numberPlayers=0; //Changed
printf("Please enter the number of players you would like");
scanf("%d",&numberPlayers); /*take in the number of players*/
struct player plyr[numberPlayers];
i = 0;
while( i<numberPlayers )
{
printf("Please enter the race you would like to play as \n"
"Press elf for Elf \n"
"Press 1 for Human \n" /*taking in the race from the user*/
"Press 2 for Ogre \n"
"Press 3 for Wizard \n");
scanf("%c",&raceChosen);
if(*raceChosen == '0'){ //Changed
printf("Please enter your name \n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength); /* generating the character */
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
if(*raceChosen == '1'){ //Changed
printf("Please enter your name 1\n:");
scanf("%d", &ptr->name[i]);
Smartness = rand()%31 + 70;
printf("%d\n",Smartness);
scanf("%d", &ptr->Smartness[i]);
Luck = rand()%41 + 60;
printf("%d \n",Luck);
scanf("%d", &ptr->Luck[i]);
Strength = rand()%50 + 1;
printf("%d \n",Strength);
scanf("%d", &ptr->Strength[i]);
Dexterity = rand()%100 + 1;
printf("%d\n",Dexterity);
scanf("%d", &ptr->Dexterity[i]);
MagicSkills = rand()%31 + 50;
printf("%d \n",MagicSkills);
scanf("%d", &ptr->MagicSkills[i]);
printf("\n********\n");
}
}
i++;
}
There are 2 major things to be considered within your code, lets correct them one by one:
char raceChosen[1]; <=> Here you have declared a charecter array of size 1
Please note : Array is collection of data of same type, so when you want to store at least 2 or more data, you could had used array, but here you are using a single charecter variable so you should avoid using array.
correct way: char raceChosen;
Secondly,
scanf(" %c",&raceChosen);
if (raceChosen == "0")
Here you are taking input racechosen as a charecter : "%c" is for charecter input, and while comapring you are comapring it with string : " "double quote is for string. ie; You are comapring
if (raceChosen == "0")
(char) (string)
This condition is not going to be true, hence you are not entering these if blocks.
correct way:
if (raceChosen == '0')
char char
When the first number is 1 and second number is 2, and the length is 5, it should be 1 2 3 5 8. But then my output is always 1 2 1 3 4. I can't seem to find the problem.
Another input is 2 and 5. Output is 2 5 1 6 7. The 3rd number which is 1 shouldn't be there. What should I change or add?
*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.
int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}
printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}
printf("%d\t", fib);
}
}
The first time you print fib (before the for loop), you haven't assigned it anything yet.
Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.
Putting it all together, we get something like:
#include <stdio.h>
int main() {
int length = 0, a, b;
while (length < 2 || length > 100 || a > b ) {
printf("\nFirst number: ");
(void) scanf("%d", &a);
printf("\nSecond number: ");
(void) scanf("%d", &b);
printf("\nHow long?: ");
(void) scanf("%d", &length);
}
printf("%d\t%d\t", a, b);
for (int i = 2; i < length; i++) {
int fib = a + b;
printf("%d\t", fib);
a = b;
b = fib;
}
printf("\n");
return 0;
}
Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.
just add fib=a+b; before printing fib value.
Its a good coding habit to initialize all variable before using it(especially in C).
Your code seems strange to me. I tried to simplify your code a bit. See this once:
int main()
{
int a,b,next,last,i;
printf("Enter the first Value:");
scanf("%d",&a);
printf("Enter the second Value:");
scanf("%d",&b);
printf("Enter the length of Fab. series:");
scanf("%d",&last);
printf("%d,%d,",a,b);
for (i=3; i<= last; i++)
{
next = a + b;
if(i<last)
printf("%d,",next);
else
printf("%d",next);
a = b;
b = next;
}
return 0;
}
Hope it's Helpful!!
I have written a code in c for long number multiplication but output is not being displayed on the IDE. Please can you point out the error in the given code. Also which language is more efficient for solving these type of problems?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10000
void main()
{
char ac[MAX];
char bc[MAX];
int a[MAX],b[MAX];
int mul[MAX];
int c[MAX];
int temp[MAX];
int la,lb;
int i,j,k=0,x=0,y;
long int r=0;
long int sum = 0;
la=strlen(ac)-1;
lb=strlen(bc)-1;
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
for(i=0;i<=la;i++){
a[i] = ac[i] - 48;
}
for(i=0;i<=lb;i++){
b[i] = bc[i] - 48;
}
for(i=lb;i>=0;i--){
r=0;
for(j=la;j>=0;j--){
temp[k++] = (b[i]*a[j] + r)%10;
r = (b[i]*a[j]+r)/10;
}
temp[k++] = r;
x++;
for(y = 0;y<x;y++){
temp[k++] = 0;
}
}
k=0;
r=0;
for(i=0;i<la+lb+2;i++)
{
sum =0;
y=0;
for(j=1;j<=lb+1;j++){
if(i <= la+j){
sum = sum + temp[y+i];
}
y += j + la + 1 ;
}
c[k++] = (sum+r) %10;
r = (sum+r)/10;
}
if (r==1)
{
c[k]=r;
}
j=0;
for(i=k-1;i>=0;i--){
mul[j++]=c[i];
}
for(i=0;i<j;j++)
{
printf("%d",mul[i]);
}
}
You calculate the length of the input strings before assigning the strings:
la=strlen(ac)-1;
lb=strlen(bc)-1;
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
If you instead do it the other way around the program actually does something:
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
la=strlen(ac)-1;
lb=strlen(bc)-1;
Your second problem is in the last part of your code:
for(i=0;i<j;j++)
{
printf("%d",mul[i]);
}
You're incrementing j instead of i, it should be:
for(i=0;i<j;i++)
{
printf("%d",mul[i]);
}
Another little thing, this isn't really clear what it does to the uninitiated:
a[i] = ac[i] - 48;
if you write it like this it's easier to understand:
a[i] = ac[i] - '0';
Use remove those la and l assignment and put it after scanning the strings like below.
printf("Enter the first number : ");
scanf("%s",ac);
printf("Enter the second number : ");
scanf("%s",bc);
la=strlen(ac)-1;
lb=strlen(bc)-1;
for(i=0;i<=la;i++){
a[i] = ac[i] - 48;
}
for(i=0;i<=lb;i++){
b[i] = bc[i] - 48;
}
Even in the last part of your code there is an error.Inside the loop you have used for(i=0;i<j;j++) replace it with for(i=0;i<j;i++).
I would also suggest you to change the size of temp array to 2*MAX+2.Because suppose somebody enters a number of 8000 digits then temp wont be able to store these many digits if the size is restricted to MAX only.
you can use java and python languages for doing same. In Java there is separate class known as BigInteger.
Scanner sc=new Scanner(System.in);
BigInteger b1,b2,b3;
String num1,num2;
System.out.println("Enter the first integer");
num1=sc.next();
System.out.println("Enter the second integer");
num2=sc.next();
b1=new BigInteger(num1);
b2=new BigInteger(num2);
b3=b1.multiply(b2);
System.out.println("The product of "+b1+" and "+b2+" is "+b3);