For clarification purposes I need the program to print the numbers that are input for a and b, not the actual letters a and b.
Okay here's the revised program per yall's suggestions:
int main (int argc, char *argv[])
{
int a; /*first number input*/
int b; /*second number input*/
a = atoi(argv[1]); /*assign to a*/
b = atoi(argv[2]); /*assign to b*/
if (a < b)
printf("%s\n", a < b); /* a is less than b*/
else {
printf("%s\n", a >= b); /* a is greater than or equal to b*/
}
if (a == b)
printf("%s\n", a == b); /* a is equal to b*/
else {
printf("%s\n", a != b); /* a is not equal to b*/
}
return 0;
} /* end function main*/
lol, now when I run the program I get told
8 [main] a 2336 _cygtls::handle_exceptions: Error while dumping state
Segmentation fault
What the heck does that mean? (If you haven't noticed by now I am pretty hopeless at this stuff lol).
You're asking printf() to print the values of the boolean expressions (which always resolve to 1 or 0 for true and false respectively).
You probably want your code to look more like:
if (a < b)
printf("%s\n", "a < b"); /* a is less than b*/
else {
printf("%s\n", "a >= b"); /* a is greater than or equal to b*/
}
To display the results as strings.
This line:
if (a = b)
shouldn't it be
if (a == b)
Same here:
printf("%d\n", a = b); /* a is equal to b*/
should be
printf("%d\n", a == b); /* a is equal to b*/
Based on your edit, I think you're looking for this:
#include <stdio.h>
int main (int argc, char *argv[]) {
int a; /*first number input*/
int b; /*second number input*/
a = atoi(argv[1]); /*assign to a*/
b = atoi(argv[2]); /*assign to b*/
if (a < b)
printf("%d < %d\n", a, b); /* a is less than b*/
else
printf("%d >= %d\n", a, b); /* a is greater than or equal to b*/
if (a == b)
printf("%d == %d\n", a, b); /* a is equal to b*/
else
printf("%d != %d\n", a, b); /* a is not equal to b*/
return 0;
}
This code:
wfarr#turing:~$ ./foo 1 2
1 < 2
1 != 2
printf("%s\n", a == b);
"%s" prints a string. a == b isn't a string, it's a boolean expression, resulting in 1 (true) or 0 (false).
So, your printf() attempts to print characters until it finds a null byte, starting at the position of the boolean expression... desaster.
Your problem is, you are trying to substitute logical expressions instead of integers. All of the above (a > b) ... evaluate to true or false (except a = b which assigns the value of b to a). What you should be doing, if you are trying to return the larger value, is the following:
printf("%d\n", a > b ? a : b)
This says if a is greater than b, print a, otherwise b.
Edit: I think what you are actually looking for is to print out the words "a > b" etc. In which case, put them in the printf. When you place %d in the printf, it subs a specified integer value into that spot in the string.
I believe you want the following:
if(a > b)
printf("a > b\n");
else
printf("b >= a\n");
Is that correct?
I'm assuming you want something like this...
Input:
a = 5, b = 7
Output:
5 < 7
5 != 7
If so, you need to print the integers a and b, as well as a string in between to show the relationship.
if( a < b ) {
printf( "%d < %d\n", a, b );
}
else {
printf( "%d >= %d\n", a, b );
}
// follow similar pattern for the next if/else block..
Related
#include <stdio.h>
int main() {
// Write C code here
int a, b = 1, c, d;
printf("Value of a:");
scanf("%d", &a);
while (b < a) {
c = b * a;
printf("%d", c);
b++;
}
return 0;
}
I was trying to find the factorial of a number but I don't know how to add the values.
It's written in C.
There are some problems in your code:
the expression c = b * a; computes an intermediary result, but not a useful one. You should compute c = c * b; multiplying the current factorial by the next integer to get the next factorial.
for the expression c = c * b; you must initialize c to 1 before the beginning of the loop.
printf("%d", c); outputs just the digits. You should output a space or a newline to separate the numbers.
scanf("%d", &a) may fail to convert a number from user input, for example if the user typed A. a will stay uninitialized, causing undefined behavior when you use it in further expressions. You should test that scanf() succeeded and returned 1, the number of successful conversions.
Here is a modified version:
#include <stdio.h>
int main() {
int a, b = 1, c = 1;
printf("Value of a:");
if (scanf("%d", &a) == 1) {
while (b < a) {
c = c * b;
printf("%d\n", c);
b++;
}
}
return 0;
}
It is recommended to use the for loop to group the initialization, increment and test of the loop variable in a single place:
#include <stdio.h>
int main() {
int a;
printf("Value of a:");
if (scanf("%d", &a) == 1) {
int c = 1;
for (int b = 1; b < a; b++) {
c = c * b; // one can also write c *= b;
printf("%d\n", c);
}
}
return 0;
}
following are the strings provided by the user to me -
"1 20";
"1 203";
"1 2030";
in above examples 1 is query and 20,203,2030 are the numbers to be extracted,how can I extract them in C language?
There are many ways to parse a string containing numbers. If you expect the string to have a fixed format with 2 integers, the simplest solution is to use sscanf():
#include <stdio.h>
int parse2numbers(const char *str) {
int a, b;
// sscanf returns the number of successful conversions
int n = sscanf(str, "%d%d", &a, &b);
if (n == 2) {
printf("success: a=%d, b=%d\n", a, b);
return 1;
}
if (n == 1) {
printf("failure: only one number provided: a=%d, str=%s\n", a, str);
return 0;
}
if (n == 0) {
printf("failure: invalid format: %s\n", str);
return 1;
}
printf("failure: encoding error: n=%d, str=%s\n", n, str);
return 0;
}
If the string can contain a variable number of integers, you could use strtol() to parse one integer at a time:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void parse_numbers(const char *str) {
long a;
char *p;
for (;; str = p) {
errno = 0;
// strtol returns a long int
// updates `p` to point after the number in the source string
// sets errno in case of overflow and returns the closest long int
a = strtol(str, &p, 10);
if (p == str)
break;
if (errno != 0) {
printf("overflow detected: ");
}
printf("got %ld\n", a);
}
if (*str) {
printf("extra characters: |%s|\n", str);
}
}
I have not tested it but I think theoratically this should work
int rows=2, columns=4 // defining length of array
char ch[rows] [columns] = {"1 90"}, {"2 90"}; // creating two dimentional array for sample data
for (int i = 0; i < rows; i++) { // looping throw first dimention
// this only works if data is sorted and there is no missing indes in between like [1 200] [3 200] will not work but [1 200] [2 200] should
char* index;
if ( ch[i] [0] != itoa(i+1, index, 10) ) // checking if index donot match the row then skip this itteration and move to next one.
continue;
for ( int j = i+2; j<columns; j++) { // looping through second dimention
printf("%c\n", ch[i][j]); // printing that second dimention
}
}
I have a question in c programming(may in other languages too)
consider this program:
(I want to write the last input number that is dividable by 3 without using arrays and ... just with recursion)
int func( int n )
{
int a;
if (n==0)
return 0;
scanf("%d",&a);
function(n-1);
if(a%3==0)
{
printf("%d\n",a);
return 1;
}
}
but unfortunately, it prints numbers dividable by 3 in reverse order(I want just the last number dividable by 3)
You have to return the value to print, if it is valid and no other valid value has been returned previously (using -1 as invalid marker, for example)
int func (int n) {
int a;
if (n == 0)
return -1;
scanf("%d", &a);
int ret = func(n-1);
if ((ret == -1) && (a%3 == 0))
ret = a;
return ret;
}
Now you can print the return value of func().
printf("%d\n", func(100)); // For 100 values
I'm practicing programming in c, but I've come across an issue that I can't seem to figure out. I have a printf statement with two markers for two different int values. No matter what the first int is, it prints 0, but the second int prints normally. Here's the code:
#include <stdio.h>
#include <stdlib.h>
int a, temp;
int toBinary();
int toDecimal();
int main()
{
char c;
for(;;)
{
scanf("%d",&a);
scanf(" %c",&c);
switch(c)
{
case 'a' :
printf("%d converted to binary: %d\n",a,toBinary());
break;
case 'b' :
printf("%d converted to decimal: %d\n",a,toDecimal());
break;
case 'c' :
printf("EXIT\n");
return 0;
break;
default :
printf("ERROR c value: %c\n",c);
return 0;
}
}
}
int toBinary()
{
if (a == 0)
return 0;
else
{
temp = a;
a /= 2;
return (temp % 2 + 10 * toBinary());
}
}
int toDecimal()
{
int res=0, base = 1, rem;
while (a > 0)
{
rem = a % 10;
res = res + rem * base;
a /= 10;
base *= 2;
}
return res;
}
The problem is that the printf statements in the first two cases ignore the actual value of int a, but it works normally for the value of the two functions. I'm not sure what's wrong, as a is given a value before, in the scanf statement, and I am using the proper marker in the text.
Since the order of argument evaluation is unspecified, this is undefined behavior.
The simplest fix would be to save a copy of a in a different variable, and print that.
int a_copy = a;
printf("%d converted to binary: %d\n",a_copy,toBinary());
But it would be better if the function didn't use a global variable in the first place.
int toBinary(int a)
{
if (a == 0)
return 0;
else
{
return (a % 2 + 10 * toBinary(a / 2));
}
}
Then you would do:
printf("%d converted to binary %d"\n, a, toBinary(a));
If a is modified in either toBinary() or toDecimal(), it's an UB.
The order of argument evaluation in one function call is unspecified. Some compilers evaluate them L->R (like GCC), some others do it R->L (like VC).
Try this and you'll find it out:
printf("%d %d %d\n", a, toBinary(), a);
printf("%d %d %d\n", a, toDecimal(), a);
The value of a in the function toBinary() gets reduced to 0 due to presence of the statement a /= 2; and it is getting recursively executed.
Hence your printf statement prints 0 for the value of a.
As #Barmar suggested, it's a good coding practice to use local variables rather than global variables inside a function.
My instructor has asked us to follow the variables through this code and determine when the variables change. He says the inputs should be
8, 4, 2, 1
I have compiled and run the code to he me understand it but it doesn't stop. It just ouputs "Feed me two numbers please:" over and over. Any help is greatly appreciated.
#include <stdio.h>
main ()
{
int a;
int b;
int c=0;
int d=0;
int e=0;
int f=0;
while (c == 0 || a + b !=0){
printf("Feed me two numbers please: \n");
scanf ("%d %d", &a, &b);
if (c == c + 1){
printf("Welcome to my world!\n\n");
}
if (c = 0){
d = a + b;
e = d;
}
else if (a + b > d){
d = a + b;
}
else if (a + b < e){
e = a + b;
}
if (a < f){
f=a;
}
c = c + 1;
}
printf("Now hear this:%d %d\n\n", d, e, f);
}
In
if (c = 0)
you're assigning 0 to c, the expression of the assignment returns the assigned value, so the expression will be always evaluated to false as it's equivalent to if(0), it should be if(c == 0).
Also
if (c == c + 1)
doesn't make any sense, what exactly do you mean? I think it should be c > 0.
In all cases, you should use the debugger, it can save you a lot of time, and will help you to really understand your code.