ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Whoa there! Order of precedence in programming language is unrelated to commutative properties. Order of precedence simply means that operations of different precedence are performed in the specified order, and operations of the same precedence are performed from left to right.
Addition and multiplication are commutative:
2+4 == 4+2
2*4 == 4*2
Subtraction and division are not commutative:
2-4 != 4-2
2/4 != 4/2
Just don't always believe that left-to-right rule. In Python we see things like this:
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
It's ok RT, don't worry about it - I've probably made every mistake you could think of. I'll try and read up on precedence in general.
Quote:
Originally Posted by rtmistler
...Perhaps get programming, but worry less about the equation of a triangle, or how to calculate the area of a circle. If you're poor at Math, then writing code to compute equations is a bad idea. You can certainly write code to control an I2C device, or GUI code, or database code. No reason to complicate things. And if you understand the math, then writing the code is fine. For instance if you understand how to calculate simple interest, like for a car loan, so you can get the annual interest on some loan, and write a program that calculates your payment for a 5-year car loan, or something like that. If that's too much for you, then it is. Concentrate on some stuff you can do for now.
Quote:
Originally Posted by igadoter
Don't listen to them. There are people who are programming and those who are teaching programming. So just start to program. Instead of you will be stuck on 'learning programming'. Maybe for months, even year. Just waste of time.
I've been thinking about the above comments, and I can't help but think both RT and igadoter have some good points there. And it made me ask myself: "Well, how did I learn what I know about anything IT related? Did I read a book cover to cover? No. Did I sit there reading the documentation cover to cover? No. Do I know all there is to know about Linux (or most other things, maybe even anything else IT related)? No. Did I have a clue what I was doing in the mid to late 2000's when I started with Linux? No. Is learning anything else all that different (if any different) in this regard? No. Did it take a while before the various concepts really started sinking in? Yes. Did I learn it by doing it, and where I got stuck on something, read about whatever it was I was stuck on? Yes. Can I do the same thing to learn C? I don't see why not. Can I learn the math concepts along the way, bit by bit? I don't see why not."
The moral of the story is that; I'm going to try a different plan of attack, and learn what C concepts I can and try and use that to learn more about the math concepts that are important for programming. I'll just make up my own exercises as I go, because then I can discover the answers along the way, and find out at the same time why they are the answers. I know it sounds counter-intuitive, but it's the only way I can think of that will both give me a chance to learn what I need before I'm dead and there's no point in learning anything, and that is my best chance to have any hope in hell of being able to do it at all.
Quote:
Originally Posted by rtmistler
I recommend starting a new thread in General where you explain that you're trying to learn Mathematics for programming and describe the problems which you are having.
Until you can intuitively grasp some of the Math concepts, I fear you'll still end up blocked with the exercises you persist with trying in the C course you are following.
I can understand why you say that, but I think I'll hold off on doing that for the time being, for the same reasons as above. But thanks again for all of your help.
I've been trying a few concepts out for inputting characters, using if statements, and for loops. So I wrote a little program that just accepts a letter (char), and if it's the letter "t", it will run the for loop ten times, outputting the letter "t" on the screen, otherwise displays a message saying it's not the letter "t", and quits. But I want to use a string instead, but everything I've tried results in gcc complaining and thinking I'm trying to use a pointer instead. Excuse the pun, but could someone give me some pointers about that?
Here's my code below, and believe it or not, I managed to type most of it out without looking at the C book or examples;
Code:
#include <stdio.h>
int main(void)
{
int loopi;
char input;
printf("\nEnter a single letter: \n");
scanf("%c", &input);
if (input == 't')
for ( loopi = 1; loopi <= 10; ++loopi )
printf("%c\n", input);
else
printf("\nNot t, you entered: %c\n", input);
return 0;
}
@jsbjsb001: You are missing (messing?) almost everything. This is program in Rexx
Code:
the_number = random(1,10)
say "I'm thinking about number between 1 and 10. What is it?"
pull the_guess
if the_number = the_guess
say 'You guessed it!'
else
say 'Sorry, my number was: ' the_number
say 'Bye!'
it was taken from book 'Rexx Programmer's Reference' by Howard Fosdick. Book is freely available. As Regina - Rexx interpreter. So maybe give it a chance. Before trying to learn C.
Have you read chapter 9 "Character Strings" in the Kochan book? In it, one of the things he teaches you is how to input a string and how to compare a string. I believe it's in this chapter where he uses a dictionary program to illustrate these concepts.
I'm not trying to be preachy but you should read the chapters in the order they're intended, otherwise you'll just be shooting yourself in the foot
You would do scanf() with a %s and give it the pointer to a character array.
Code:
char myArray[32];
// The address of it can be expressed as either
myArray
// Or
&myArray[0]
// Both of these are acceptable
scanf("Enter a string: %s", myArray);
scanf("Enter a string: %s", &myArray[0]);
It gets more complicated, such as avoiding reading in too long of a string, but this can get you started.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Quote:
Originally Posted by Mechanikx
...
I'm not trying to be preachy but you should read the chapters in the order they're intended, otherwise you'll just be shooting yourself in the foot
Thanks Mechanikx. I didn't mean that I was going to skip any chapters. I'll still follow the chapters in the order they appear in the book, I just want to get a better understanding of the chapters I've read so far. Sorry I wasn't clear about that before.
I did do some if statements and used scanf before I started with the Kochan book, so I've already got at least some understanding of if statements, and scanf has been covered in the chapters I'm up to as well. But I do agree with what you've said though, and understand why you say that.
Thanks RT. I want to practice using if statements, like if else, if then, etc using more than just numbers. Because this will help me write some programs that can help with the math side of things. I know it seems like a backwards approach, but like I said before, I'll still be reading the chapters in-between. Then I can fill in the gaps.
igadoter, I'm not entirely sure what you are saying. What is it do you think I'm missing?
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Chapter 5: Program Looping
I've been practising for loops, and I decided to have another crack at the exercises in the C book.
Exercise 7
Quote:
A decimal point before the field width specification in a printf statement has a special purpose.Try to determine its purpose by typing in and running the following program. Experiment by typing in different values each time you are prompted.
From the experiments I done by removing it, and then compiling it without the decimal point, it looks like it adds the decimal point, and tells printf that there is no space between the numbers in the output?
Code:
printf ("$%i%.2i\n\n", dollars, cents);
output:
Code:
Enter dollars: 6
Enter cents: 6
$606
Code:
printf ("$%i.%2i\n\n", dollars, cents);
output:
Code:
Enter dollars: 6
Enter cents: 6
$6. 6
Code:
printf ("$%i.%.2i\n\n", dollars, cents);
output:
Code:
Enter dollars: 6
Enter cents: 6
$6.06
Exercise 8
Quote:
8.Program 5.5 allows the user to type in only five different numbers. Modify that program so that the user can type in the number of triangular numbers to be calculated.
I added the first printf and scanf statements, and added the "numberOfTriangularNumbers" variable, and then changed the first for loop condition from "5" to the variable "numberOfTriangularNumbers". I tested it, and it does seem to work as expected.
Code:
#include <stdio.h>
int main(void)
{
int n, number, triangularNumber, counter, numberOfTriangularNumbers;
printf ("How many triangular numbers do you want? ");
scanf ("%i", &numberOfTriangularNumbers);
for ( counter = 1; counter <= numberOfTriangularNumbers; ++counter ) {
printf ("What triangular number do you want? ");
scanf ("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
triangularNumber += n;
printf ("Triangular number %i is %i\n\n", number,triangularNumber);
}
return 0;
}
I suggest you use indentation to make it easier to read:
Code:
#include <stdio.h>
int main(void)
{
int n, number, triangularNumber, counter, numberOfTriangularNumbers;
printf ("How many triangular numbers do you want? ");
scanf ("%i", &numberOfTriangularNumbers);
for ( counter = 1; counter <= numberOfTriangularNumbers; ++counter ) {
printf ("What triangular number do you want? ");
scanf ("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
triangularNumber += n;
printf ("Triangular number %i is %i\n\n", number,triangularNumber);
}
return 0;
}
This makes it easier to skip reading and jump to a section you may be working on. It can also help spot typeographic errors (like a missing "}") and get the fix in the right place...
From the experiments I done by removing it, and then compiling it without the decimal point, it looks like it adds the decimal point, and tells printf that there is no space between the numbers in the output?
In the case of '%i' it tells printf how many leading zeros to display for the number (note: number not field, there's a subtle difference). Kochan describes it as putting "a decimal point before the field width" but that is misleading. What you're actually doing is specifying a precision on a field of unspecified width.
The syntax is [width][.precision] and both are optional components, so you can have
%2i
%.2i
%4.2i
Hint: try displaying -5 with each of those and you'll see the subtle difference between width and precision.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Thanks again guys.
jpollard, I've tried to start practising indenting my code, thanks again for your help.
GazL, thanks for explaining that about the decimal point in the printf statement.
Quote:
Originally Posted by GazL
BTW, without wishing to derail this thread, a quick aside to our pro-programmers:
I notice that this revision of the Kochan book favors %i over %d in printf() while
my dead-tree first edition of the book uses %d.
Is %i usage common?
While I'm far from a pro-programmer, I'd be interested to hear the answer to that too. So no, I wouldn't consider that derailing the thread.
Anyhow, I've been practising the while loop, as well as including an if statement in it, so it will only run if you enter 10 or above, and less than 50. I couldn't figure out why it would only run a certain amount of times depending on the number you enter, but I noticed when I only enter say "48", it runs twice, and if I enter "47", it runs three times. So from that I discovered that because in the if statement I set the condition to equal to or more than "50", it counts back from "50", and therefore that explains it.
Here's my code;
Code:
#include <stdio.h>
int main(void)
{
int enteredNumber;
printf("Enter a number: \n");
scanf("%i", &enteredNumber);
while ( enteredNumber >= 10 ){
if ( enteredNumber >= 50 )
break;
else
printf("%i\n", enteredNumber);
++enteredNumber;
}
return 0;
}
Last edited by jsbjsb001; 02-04-2019 at 04:02 AM.
Reason: correction
I've been practising the while loop, as well as including an if statement in it, so it will only run if you enter 10 or above, and less than 50. I couldn't figure out why it would only run a certain amount of times depending on the number you enter, but I noticed when I only enter say "48", it runs twice, and if I enter "47", it runs three times. So from that I discovered that because in the if statement I set the condition to equal to or more than "50", it counts back from "50", and therefore that explains it.
Here's my code;
Code:
#include <stdio.h>
int main(void)
{
int enteredNumber;
printf("Enter a number: \n");
scanf("%i", &enteredNumber);
while ( enteredNumber >= 10 ){
if ( enteredNumber >= 50 )
break;
else
printf("%i\n", enteredNumber);
++enteredNumber;
}
return 0;
}
You should really read the code which you wrote and fully understand what it is doing.
Furthermore, you should learn how to use the debugger. I have two blogs about debugging code in C and one of them describes using GDB. Because using a debugger, single stepping, and examining the variable values, you'll see very clearly why the program does, what it does.
For instance you would see that the line, "++enteredNumber" is executed every iteration of your loop, what value it started with, and how may times the loop runs, as well as what the outcome of the if-else test is.
Note also that the definition of your loop is:
Code:
while ( enteredNumber >= 10 ){
If you wish the actual loop to define the upper boundary, then your test for >= 50 should be part of the "while" statement.
My viewpoint here is that you should have one point in the code which tests your exit condition, not several. Yes, you only have two, but as you progress writing lengthier code, using a "convenient" point to exit your loop means in my humble opinion, that you did not design it properly.
I also agree that proper indenting is helpful. Mandatory if you were to work for me. Using different indentations all the time for the same levels of code are difficult to view and read.
BTW, without wishing to derail this thread, a quick aside to our pro-programmers:
I notice that this revision of the Kochan book favors %i over %d in printf() while
my dead-tree first edition of the book uses %d.
Is %i usage common?
I don't think it is common yet, but it is a good addition.
It indentifies that the field is for conversion of integer values (32 bits) - which don't necessarly work with %d, as a "long long" integer (64 bits) would not be properly converted. I think it was added along with %lld and %lli to handle 64 bit ints; and %p is there for pointers (previously it was either %x or %d; and %d had the problem of assuming 32 bits, and pointers are now 16/32/64 bits).
Other than "i" being more associated with "int" there is no difference between %i and %d.
I'm cognizant of the %i, but haven't seen much in the way of explanation. Good stuff to know. I appreciate the expansion of the discussion.
This made it occur to me that literally every system I work within; we, or providers, or example code, typically has type defines for sized variables.
uint8_t
int8_t
uint16_t
And so forth
And we may also do test stuff like:
Code:
printf("Size of an short is: %d\n", sizeof(short));
This is to ensure that when we call something 16 bits, it really is.
An additional comment with jsbjsb001's code is that eventually for a real design you also do not hard-code array sizes, limits, etc, you #define those or enumerate those.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.