Author Topic: understand c programming logic but can't write a tough program  (Read 5707 times)

0 Members and 1 Guest are viewing this topic.

Offline khatusTopic starter

  • Regular Contributor
  • *
  • Posts: 146
  • Country: gl
understand c programming logic but can't write a tough program
« on: February 22, 2020, 06:19:44 pm »

Hello guys I am a beginner in c programming.I understand the logic behind a solved problem in c programming, but I can't write a tough program(like Pascal's triangle,pyramid) without any algorithm or flowchart by myself.When the program gets a little tough, I can't solve it. What should I do now?Which book should i follow.I  need some useful advice.
 

Offline Byonnem

  • Newbie
  • Posts: 9
  • Country: nl
  • Bachelor Student EE
Re: understand c programming logic but can't write a tough program
« Reply #1 on: February 22, 2020, 06:30:48 pm »
To be honest, practice makes perfect... It took me 140 Hours to understand pointers and structs, so don't demotivate yourself but instead keep trying.

I found that the best way to motivate myself was by doing "realistic" challenges.

Some practical tips:

First step should always be on paper. Think, how to approach a challenge: divide it in sub-parts, flow charts and so on..
I like to layout my functions, before i start to fill them with code. Make clear with comments what you expect each function, object or what ever should do, or to what it corresponds to on the paper you made in the step before.
Comments, i cannot stress enough how important documentation is. If you can't explain what you're doing, there is something wrong.

And my final tip would be, buy a rubber duck and explain your code to him ;)

Good Luck!

M.D.S
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9893
  • Country: us
Re: understand c programming logic but can't write a tough program
« Reply #2 on: February 22, 2020, 07:17:52 pm »
I find it useful to write some kind of pseudo-code that explains, in sequence, what needs to be done to solve the problem.  Make this fairly fine grained and then you can write C functions for each of the steps.

Many years ago, one of the premier computer scientists suggested that programmers not have access to a computer or keyboard.  In those days we were doing flow charts and a lot more paper modeling than is typical today.

But you must be able to solve the problem on paper before you even begin to write code.  Comments explaining each step are helpful.

The C code for Pascal's Triangle is near the bottom of this page:
https://www.programiz.com/c-programming/examples/pyramid-pattern

On paper, walk through the for loops and make certain you truly understand how the code works:

Code: [Select]
// just the important stuff...

    for (i=0; i<rows; i++) {  // do as many rows as the user requested  I would rename 'i' to 'row' everywhere!

        for (space=1; space <= rows-i; space++)  // rows near the  start require more spaces to center - walk through it on paper

        for (j=0; j<=i; j++) {  // walk across the row
            if (j==0 || i==0) // the left and right edge are always '1'
                coef = 1;
            else
                coef=coef*(i-j+1)/j; // ok, this is awkward, STUDY it
            printf("%4d", coef);
        }
[/font]

The linked code works in Microsoft Visual Studio by substituting scanf_s() for scanf().  Otherwise, the compiler whines and snivels about scanf being unsafe.

The working code:
Code: [Select]
#include<stdio.h>

int main() {
    int rows, coef = 1, space, i, j;
    printf("Enter number of rows: ");
    scanf_s("%d", &rows);
    for (i = 0; i < rows; i++) {
        for (space = 1; space <= rows - i; space++)
            printf("  ");
        for (j = 0; j <= i; j++) {
            if (j == 0 || i == 0)
                coef = 1;
            else
                coef = coef * (i - j + 1) / j;
            printf("%4d", coef);
        }
        printf("\n");
    }
    return 0;
}
[/font]

ETA:  Walk through the code for rows = 1, rows = 2 and rows = 3.  That will do for a start.  Include more rows if you are so inclined.

« Last Edit: February 22, 2020, 07:33:55 pm by rstofer »
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 4047
  • Country: nz
Re: understand c programming logic but can't write a tough program
« Reply #3 on: February 22, 2020, 09:53:23 pm »
Strange code. What is the " || i == 0" for? The program is fine without it. I could understand if it was " || i == j" but that is also unnesessary.

And it seems just overly "clever", especially in the "coef = coef * (i - j + 1) / j". Ugh!

I'd split the calculation of coef out into a very simple function:

Code: [Select]
#include <stdio.h>

int coef(int i, int j) {
  if (j == 0 || j == i)
    return 1;
  else
    return coef(i-1, j) + coef(i-1, j-1);
}

int main() {
  int rows, space, i, j;
  printf("Enter number of rows: ");
  if (EOF == scanf("%d", &rows)) return 1;
  for (i = 0; i < rows; i++) {
    for (space = 1; space <= rows - i; space++) printf("  ");
    for (j = 0; j <= i; j++) printf("%4d", coef(i, j));
    printf("\n");
  }
  return 0;
}

You can think that coef() will be inefficient. You're unlikely to be using a big enough value of rows that this will matter, but if you are then you can memoize the results:

Code: [Select]
#define MAXROWS 1024
int coefs[MAXROWS][MAXROWS]; // initialized to 0s

int coef(int i, int j) {
  if (coefs[i][j] != 0) return coefs[i][j];
  return coefs[i][j] = (j == 0 || j == i) ? 1 : coef(i-1, j) + coef(i-1, j-1);
}

This will about as fast as the original code -- or even faster as there is no multiply or divide. Of course it will use more RAM. Tradeoffs :-)
« Last Edit: February 22, 2020, 11:18:30 pm by brucehoult »
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9893
  • Country: us
Re: understand c programming logic but can't write a tough program
« Reply #4 on: February 22, 2020, 10:34:54 pm »
Agreed!  The code, as given, may be short but it is ugly too!

I would break out the user interaction to a function called get_rows() just to make it clear in main() what was going on so rows = getrows().  I like the idea of aborting if there is no entry.

I would also break out the spaces bit to a function print_leading_spaces(int rows), again to make it clear in the  main() function exactly what was happening.

Functions will kind of spill out of the block diagram and pseudo code.  Find something that is more or less isolated logic and make it a function.  It just makes things easier to read.

There's nothing ambiguous about a function named 'print_leading_spaces(rows).  I would also substitute 'row' for 'i' and maybe 'col' for 'j'.

We could get a lot more specific with something like 'print_leading_spaces(number_of_rows)' and change the variable 'rows' to 'number_of_rows'.  Or, leave well enough alone.  But the more descriptive the name, the better.  Until it looks stupid....
 

Offline nigelwright7557

  • Frequent Contributor
  • **
  • Posts: 693
  • Country: gb
    • Electronic controls
Re: understand c programming logic but can't write a tough program
« Reply #5 on: February 23, 2020, 12:33:33 am »
Start off with small programs and build up to the complicated stuff slowly.

For simple stuff I just bang the code in.
For more complicated stuff  I take a step back and write out a flowchart of what I want the software to do.
Its easier to change it on paper than having to rewrite all the code again.


 

Offline SilverSolder

  • Super Contributor
  • ***
  • Posts: 6126
  • Country: 00
Re: understand c programming logic but can't write a tough program
« Reply #6 on: February 23, 2020, 12:55:47 am »
I find it useful to write some kind of pseudo-code that explains, in sequence, what needs to be done to solve the problem.  Make this fairly fine grained and then you can write C functions for each of the steps.  [...]

This is a very powerful approach.  Basically,  write your program in (structured) English first.   When you have done that, you will have defined the algorithm that you want to use.

Designing the algorithm is a very different thought process from coding that algorithm in a specific programming language.
 

Offline admiralk

  • Regular Contributor
  • *
  • Posts: 178
  • Country: us
Re: understand c programming logic but can't write a tough program
« Reply #7 on: February 23, 2020, 01:06:11 am »
When the program gets a little tough, I can't solve it.

Can you solve the problem without it being a program? If so, just imagine explaining the solution to a 5 year old. Then use that solution to base your program on, instead of the one you are trying to use. Write the simple steps out in comments and then replace the comments with code. That way, instead of looking at the big picture, you will only focus on one step at a time which is all you need to do. Do not even think about functions, until you find yourself writing the same thing over and over again. Once you get it working, then worry about cleaning it up.
 

Offline Simon_RL

  • Regular Contributor
  • *
  • Posts: 53
  • Country: au
Re: understand c programming logic but can't write a tough program
« Reply #8 on: February 23, 2020, 10:15:58 am »
The C Programming Language by Brian Kernighan is by for the best book on C. It is what I used at Uni instead of the recommended book and it was the best decision I made.
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9893
  • Country: us
Re: understand c programming logic but can't write a tough program
« Reply #9 on: February 23, 2020, 04:09:37 pm »
The C Programming Language by Brian Kernighan is by for the best book on C. It is what I used at Uni instead of the recommended book and it was the best decision I made.

There is the original (pre-ANSI) version that works with classical C and a newer ANSI version that is more aligned with modern C.  I have both!

I actually use the string and numeric conversion functions in my own projects.  This is useful when I want to avoid using a heap for the library string functions.  And that is just about always!
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4206
  • Country: us
Re: understand c programming logic but can't write a tough program
« Reply #10 on: February 24, 2020, 01:46:37 am »
I have a special dislike for "programing challenges" that are actually "figure out the mathematical algorithm" problems.
But for program in general (using Pascal's Triangle as an example):
  • Understand the problem.  Do you know how to make a Pascal Triangle by hand?
  • Document the problem.
  • Research prior art and algorithms.  Is there an existing library that you're allowed to use (consider honor codes, licensing issues, etc)?  There's a well known formula for the Kth element of the Nth row of PT, for instance.  You CAN decide to echo the "by hand" method, though.
  • Document how you intend to solve the problem.
  • Implement.  Use whatever language you want (but keep in mind your final target.)  Get the correct output.
  • Optimize.  Convert to the desired language, if necessary.  Don't over-optimize for the problem.
  • Make it pretty.  Make the output pretty, make the code pretty, fix all your formatting and documentation.  Remove obscure language constructs (why did you use them in the first place?)
  • Document how to use it.
  • Goto (1) if your understanding changes along the way.
Writing code before you understand the problem is probably the biggest cause of bad software in the world.  It is, alas, frequently necessary, because problems in real world programming situations are frequently not very well defined.
And also: "premature optimization is the root of all evil." (and many bugs)  :-)
 

Offline aeberbach

  • Regular Contributor
  • *
  • Posts: 198
  • Country: au
Re: understand c programming logic but can't write a tough program
« Reply #11 on: February 24, 2020, 09:08:52 am »
In 20+ years as a software engineer when I look back at the times I failed badly I have realised it was almost always* because I tried to do too much at once. If you are feeling overwhelmed or stuck or there's a bug you can't solve the solution is almost always to break down the steps further and understand each smaller step - they add up to success in the broader problem. Eat the elephant one bite at a time, as they say.

*OK, once or twice it was Nethack.
Software guy studying B.Eng.
 

Offline SilverSolder

  • Super Contributor
  • ***
  • Posts: 6126
  • Country: 00
Re: understand c programming logic but can't write a tough program
« Reply #12 on: February 24, 2020, 12:26:50 pm »

[...]Writing code before you understand the problem is probably the biggest cause of bad software in the world.  It is, alas, frequently necessary, because problems in real world programming situations are frequently not very well defined.[...]


My favourite tactic against "not very well defined requirements" is to write as little code as possible,  having as few features as possible.  This way, the real requirements tend to get flushed out in the open faster.
 

Offline nigelwright7557

  • Frequent Contributor
  • **
  • Posts: 693
  • Country: gb
    • Electronic controls
Re: understand c programming logic but can't write a tough program
« Reply #13 on: February 28, 2020, 04:45:03 pm »
In 20+ years as a software engineer when I look back at the times I failed badly I have realised it was almost always* because I tried to do too much at once. If you are feeling overwhelmed or stuck or there's a bug you can't solve the solution is almost always to break down the steps further and understand each smaller step - they add up to success in the broader problem. Eat the elephant one bite at a time, as they say.

*OK, once or twice it was Nethack.

Just break down big problems into lots of smaller easier problems.
Old saying,"You can move mountains, if you do it by the barrow load."
 

Offline Elestaten_Harold

  • Newbie
  • Posts: 4
  • Country: de
Re: understand c programming logic but can't write a tough program
« Reply #14 on: March 01, 2020, 04:13:28 pm »
I'm really not good at it yet, maybe someone can recommend good udemy c++ course?
 

Online brucehoult

  • Super Contributor
  • ***
  • Posts: 4047
  • Country: nz
Re: understand c programming logic but can't write a tough program
« Reply #15 on: March 02, 2020, 12:01:46 am »
I'm really not good at it yet, maybe someone can recommend good udemy c++ course?

Modern C++ is horrendously complex. And the standard library is worse. I doubt that anyone really knows it. Every company I ever worked at that said "We use C++" also had a long list of C++ features that were forbidden. Mostly they might as well have used Java.

When C++ came out it had a lot of features that were just "Better C". For example being able to declare and initialize a variable at the point of first use instead of only before the first statement in a block. Modern C has adopted those, making it much more pleasant than C89 was (let alone K&R).

I suggest people learning to program start with a very simple language that they can easily learn all of, and then concentrate on how to use that to build real programs. C is on the border of that. Pascal and Python do everything C can (except speed in the case of Python) but with easier syntax. Scheme had much simpler syntax but some annoying quirks that Dylan fixed -- similar to the "Better C" things C++ did.

Personally, I think it's not stupid for beginners to start with a simple assembly language, and use stdio and malloc/free from the C library. Original MIPS or ARMv2 or RISC-V RV32I -- something with just a handful of instruction formats so it's easy to understand what instructions and variations are possible. AVR is ok too. 6502 is very simple to learn, but runs into the problem that it's so simple it's hard to get anything done.

A great thing these days is it's so very easy to start programming in any of these instruction sets. One simple command will install a compiler and assembler and linker and libraries and debugger and all that stuff, and another will install an emulator (usually qemu).

My biggest problem when I started learning programming -- and in fact any time I learn a new programming language -- is not in understanding the examples that are shown to me, but in understanding where the limits are: what I CAN'T say in the language. C is just awful for this. Just look at some of the things a smart guy like Simon tries to force into C that it actually can't do. Python and Pascal and Go aren't a lot better for this. Unless you understand the underlying machine model or registers and ram and instructions it's very hard to make sense of them.
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19614
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: understand c programming logic but can't write a tough program
« Reply #16 on: March 02, 2020, 08:54:42 am »
I'm really not good at it yet, maybe someone can recommend good udemy c++ course?

Modern C++ is horrendously complex. And the standard library is worse. I doubt that anyone really knows it. Every company I ever worked at that said "We use C++" also had a long list of C++ features that were forbidden. Mostly they might as well have used Java.

When C++ came out it had a lot of features that were just "Better C". For example being able to declare and initialize a variable at the point of first use instead of only before the first statement in a block. Modern C has adopted those, making it much more pleasant than C89 was (let alone K&R).

I suggest people learning to program start with a very simple language that they can easily learn all of, and then concentrate on how to use that to build real programs.

Very very true :) For an amusing demonstration of why very few people understand C++, see the FQA http://yosefk.com/c++fqa/

But back to the OP. They need to understand the difference between an algorithm and a language and a library.

If you cannot outline the algorithm that you will use, then
  • the language is irrelevant; if an author doesn't have a story then they can't write it in English, German, Malayalam, ...
  • find a library that encapsulates the necessary algorithm

Occasionally the algorithm suggests that one language would be more appropriate than others.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4206
  • Country: us
Re: understand c programming logic but can't write a tough program
« Reply #17 on: March 02, 2020, 09:59:35 am »
A problem is that when you take an "Algorithms" class, you don't learn about how to turn a big problem into a program, you just learn about a set of relatively small tools that can (maybe) help solve part of the problem.
"We spent 5 weeks learning about graph algorithms, but I can't figure out how to make my email program use any of that!"
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19614
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: understand c programming logic but can't write a tough program
« Reply #18 on: March 02, 2020, 10:41:28 am »
A problem is that when you take an "Algorithms" class, you don't learn about how to turn a big problem into a program, you just learn about a set of relatively small tools that can (maybe) help solve part of the problem.
"We spent 5 weeks learning about graph algorithms, but I can't figure out how to make my email program use any of that!"

... in which case letting such a person near a keyboard with a compiler/IDE would be a disaster in the making.

Practice without theory is blind fumbling.
Theory without practice is mental masturbation.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline hwj-d

  • Frequent Contributor
  • **
  • Posts: 676
  • Country: de
  • save the children - chase the cabal
Re: understand c programming logic but can't write a tough program
« Reply #19 on: March 02, 2020, 11:10:02 am »
Ok, don't read the complete thread now, only the first post.
The biggest failure is when you try to achieve too much at once. Programming is a time-consuming activity for a beginner with a very large overhead to climb the practical learning curve. Here only learning by doing helps. If an algorithm doesn't work, or the compiler doesn't want to compile for syntactic reasons, it helps to take the problem out, break it down into its rudimentary components, and test and debug those separately until you get the error or difficulty. This is time consuming, but necessary. So even now you are only just learning the necessary techniques, and you get more realistic ideas about the time needed to get larger program blocks working. You have to go this way yourself, you cannot study it theoretically. The literature supports only this way, i.e. it follows it, not the other way around.
 

Offline SilverSolder

  • Super Contributor
  • ***
  • Posts: 6126
  • Country: 00
Re: understand c programming logic but can't write a tough program
« Reply #20 on: March 02, 2020, 12:02:49 pm »
Ok, don't read the complete thread now, only the first post.
The biggest failure is when you try to achieve too much at once. Programming is a time-consuming activity for a beginner with a very large overhead to climb the practical learning curve. Here only learning by doing helps. If an algorithm doesn't work, or the compiler doesn't want to compile for syntactic reasons, it helps to take the problem out, break it down into its rudimentary components, and test and debug those separately until you get the error or difficulty. This is time consuming, but necessary. So even now you are only just learning the necessary techniques, and you get more realistic ideas about the time needed to get larger program blocks working. You have to go this way yourself, you cannot study it theoretically. The literature supports only this way, i.e. it follows it, not the other way around.

After about 30 or 40 years of this, you get to the point where you can write quite long programs that compile the first time  (notice, I didn't say "work" the first time!)   :-DD
 
The following users thanked this post: Brumby

Offline grizewald

  • Frequent Contributor
  • **
  • Posts: 612
  • Country: ua
Re: understand c programming logic but can't write a tough program
« Reply #21 on: March 02, 2020, 12:21:42 pm »
I have a special dislike for "programing challenges" that are actually "figure out the mathematical algorithm" problems.
But for program in general (using Pascal's Triangle as an example):
  • Understand the problem.  Do you know how to make a Pascal Triangle by hand?
  • Document the problem.
  • Research prior art and algorithms.  Is there an existing library that you're allowed to use (consider honor codes, licensing issues, etc)?  There's a well known formula for the Kth element of the Nth row of PT, for instance.  You CAN decide to echo the "by hand" method, though.
  • Document how you intend to solve the problem.
  • Implement.  Use whatever language you want (but keep in mind your final target.)  Get the correct output.
  • Optimize.  Convert to the desired language, if necessary.  Don't over-optimize for the problem.
  • Make it pretty.  Make the output pretty, make the code pretty, fix all your formatting and documentation.  Remove obscure language constructs (why did you use them in the first place?)
  • Document how to use it.
  • Goto (1) if your understanding changes along the way.
Writing code before you understand the problem is probably the biggest cause of bad software in the world.  It is, alas, frequently necessary, because problems in real world programming situations are frequently not very well defined.
And also: "premature optimization is the root of all evil." (and many bugs)  :-)

Not a bad list, but I'd object to step 7 on principle because if you have that step at all, it never ends up being done in the real world because it's not perceived as adding value if the program already works.

Good formatting and commenting is something that should be done as you write the code, not relegated to a "nice to have" afterwards.

I've dealt with far too much code which looks like it was written by a dyslexic in a hurry. You should always spare a thought for the guy who has to maintain what you've written, maybe decades later. Oh, and comments should tell me WHY you are doing something, never WHAT you are doing.

 
  Lord of Sealand
 
The following users thanked this post: nfmax

Offline nfmax

  • Super Contributor
  • ***
  • Posts: 1562
  • Country: gb
Re: understand c programming logic but can't write a tough program
« Reply #22 on: March 02, 2020, 12:49:36 pm »
Good formatting and commenting is something that should be done as you write the code, not relegated to a "nice to have" afterwards.

I've dealt with far too much code which looks like it was written by a dyslexic in a hurry. You should always spare a thought for the guy who has to maintain what you've written, maybe decades later. Oh, and comments should tell me WHY you are doing something, never WHAT you are doing.
If you use a special algorithm you found somewhere, you should place a reference to the original in a comment, perhaps with an explanation why you used it. (I mean a bibliographic reference, not a gentrified pointer)
 

Offline hwj-d

  • Frequent Contributor
  • **
  • Posts: 676
  • Country: de
  • save the children - chase the cabal
Re: understand c programming logic but can't write a tough program
« Reply #23 on: March 02, 2020, 12:53:24 pm »
After about 30 or 40 years of this, you get to the point where you can write quite long programs that compile the first time  (notice, I didn't say "work" the first time!)   :-DD
Something to laugh about there?
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 19614
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: understand c programming logic but can't write a tough program
« Reply #24 on: March 02, 2020, 04:05:27 pm »
I have a special dislike for "programing challenges" that are actually "figure out the mathematical algorithm" problems.
But for program in general (using Pascal's Triangle as an example):
  • Understand the problem.  Do you know how to make a Pascal Triangle by hand?
  • Document the problem.
  • Research prior art and algorithms.  Is there an existing library that you're allowed to use (consider honor codes, licensing issues, etc)?  There's a well known formula for the Kth element of the Nth row of PT, for instance.  You CAN decide to echo the "by hand" method, though.
  • Document how you intend to solve the problem.
  • Implement.  Use whatever language you want (but keep in mind your final target.)  Get the correct output.
  • Optimize.  Convert to the desired language, if necessary.  Don't over-optimize for the problem.
  • Make it pretty.  Make the output pretty, make the code pretty, fix all your formatting and documentation.  Remove obscure language constructs (why did you use them in the first place?)
  • Document how to use it.
  • Goto (1) if your understanding changes along the way.
Writing code before you understand the problem is probably the biggest cause of bad software in the world.  It is, alas, frequently necessary, because problems in real world programming situations are frequently not very well defined.
And also: "premature optimization is the root of all evil." (and many bugs)  :-)

Not a bad list, but I'd object to step 7 on principle because if you have that step at all, it never ends up being done in the real world because it's not perceived as adding value if the program already works.

Good formatting and commenting is something that should be done as you write the code, not relegated to a "nice to have" afterwards.

I've dealt with far too much code which looks like it was written by a dyslexic in a hurry. You should always spare a thought for the guy who has to maintain what you've written, maybe decades later. Oh, and comments should tell me WHY you are doing something, never WHAT you are doing.

Good formatting should take 1 keystroke in a decent language (i.e. not C/C++). Good commenting is more of a rarity, especially with the XP/Agile "no comments because they are out-of-sync with the self-explanatory code" religious dogma.

As for "why" rather than "what", yes indeed - but add in "why not" where beneficial!
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf