Lecture 6

Functions was the theme of today, and you can find the slides here: lecture 6
While all the stuff we did before dealt with variables or commands, this lecture was about questions regarding “how to organize your code”. A function is a piece of code that is reusable, and can be called from everywhere in your program. A such it is a way for you to define your own commands. It allows you to hand arguments to your functions and get a result in return. There is a proof that everything regarding code can be done without actually using functions, it just becomes extraordinary hard to write in certain cases. This means that you have to learn when it is useful to use a function and when it is useless. Later in life you will face the following problem when it comes to writing code: Should it run fast, should it look elegant, or do I want to write the code as fast as possible. And to make life even harder: Sometimes the shortest most elegant code is the one you can write fastest, and sometime the fastest code is the ugliest, and sometimes throwing together a couple of copy pasted lines gets you an answer and that was what you needed, and nobody cares for the code looking ugly and not being reusable.

However for now lets look at a simple example of a function that returns the higher of two values:

#include <stdio.h>

int higher(int A, int B);

int main(){
    int a=5,b=7;  
    printf("%i %i the higher is: %i\n",a,b,higher(a,b));
    return 0;
}

int higher(int A, int B){
    if(A>B)
        return A;
    else
        return B;
}

This example might look fairly useless, but keep in mind that we use printf and scanf quite often, and that they are functions too, and as you can imagine printf does a lot of stuff.

The other topic we touched is our midterm in two weeks. I am going to do another blog which will contain several possible examples of programs you might be asked to write. I recommend that you sit down in a group and give each other programming problems you have to code. Remember coding can’t be learned it has to be mastered, and that takes practice!

Cheers Arend

Posted in Uncategorized | Leave a comment

Lecture 5

More Loops and the switch statement!
I know, loops can be tiresome. But quite frankly loops is what programming is about! Well, that is not true, but it is sometimes true. The big advantage of computers is that they can do things repetitively over and over agent, and loops let you do that. Which is the reason why we dedicated todays lecture to exercising loops. From now on this lecture assumes that you know how to do loops and that you are able to make all the “shapes” we made in our exercise, because they capture most looping problems in one form or the other.
The other thing we talked about is the switch statement. Instead of explaining it here again, I will write it to the recap post from before.
In the meantime you can find the lecture here:lecture 5
Cheers Arend

Posted in Uncategorized | Leave a comment

Results Homework Lecture 3

ah 10
an 8
ar 8
cr 10
dk 5
dm 8
ds 10
dz 8
fl 5
gj 8
gw 10
hk 10
jg 9
jl 5
jm 5
js 10
jw 10
kw 8
mj 8
mr 10
ms 10
nh 10
rb 10
rl 8
rs 10
sg 8
tp 8
ts 10
xz 5
yj 10

I am going to discuss the homework in class. The two main errors that I saw were about the abort condition or the srand command.
Cheers Arend

Posted in Uncategorized | Leave a comment

Recap

I was asked to give a little recap in more detail and longer than I usually blog about the lectures. The problem with that is, that longer is actually more confusing than helpful. After all the C language is super straight forward and almost primitive … as long as you don’t need to think about pointers, functions, or structures – and that is where we are. The problem most of you struggle with is not the language but “how to program”. But programming is like solving a puzzle, you have to know the commands, and you have to piece them together in the right order. Finding out how is what makes you become a better programmer, telling you how makes you rely on outside help. However a simple recap of our known C commands can’t hurt. So here we go:
1) Basic program
Each program requires at least this structure:

int main(void){
//code to be added here
    return 0;
}

2a) printing to the screen
If you want to print something to the screen you should use printf, but that requires you to include the stdio library. In the simplest form printf can printf STRINGS, that are “sentences” started by a ” and ended by a ?

#include <stdio.h>;
int main(void){
    printf("something you want to print");
    return 0;
}

2b) printing something elegant to the screen
Printing everything after the other is lame, you want to print new lines, tabs, “, and \ and you do that by using special “characters” as there are
\n to new line
\t for a tab
\\ for the
\% for a %
and \” for a ” … how else should C know if your string is ending or you want to have a ” in your string, right?

2c) printing variables
You might want to print variables to see the result of a calculation? For that you have to “mark” the position in the string with a special character which will have a % in front. Here is the example:

#include <stdio.h>
int main(void){
    int i=1;
    float f=3.141;
    char c='A';
    printf("printing a constant number %i\n",5);
    printf("printing a computation %i\n",2+3);
    printf("printing an integer variable %i\n",i);
    printf("printing an floating point variable %f\n",f);
    printf("printing an ascii character%c\n",c);
    return 0;
}

2d) formating variables
check out this link for more formatting: http://www.cplusplus.com/reference/clibrary/cstdio/printf/

3) reading some input from the command line
Sometimes you want an user input, so what the user writes needs to end up in a variable. Use scant, which is similar in usage to printf, except that you can’t write anything specific, example:

#include <stdio.h>;
int main(void){
    int i;
    float f;
    char c;
    scanf("%i",&i);
    scanf("%f",&f);
    scanf("%c",&c);
    printf("you entered: %i %f %c\n",i,f,c);
    return 0;
}

You see the & in front of the variable in the scant statement? It says: Address of i, because C doesn’t need to know the current value of i but where the address of i in memory is to fill it with new content.

4a) if (conditional)
The if statement evaluates a condition and if the condition is true it executes the next following command (or scope {}). Once that is done it continues with the usual program flow. That is the reason why if helps you control the flow of your code. if has a helper called else which allows you to not only execute something or not, it allows you to execute something or something ELSE… example:

    int a=5;
    if(a==4){
        //this will not be executed because a isn't 4
    } else {
        //this will be executed because a is 4
    }

In order to be able to make comparisons in the condition you have a couple of comparators == is an equal and checks if the left and right side are identical, and to check which side is bigger you can use < > <= >= and the last one checks for inequality !=.

4b) AND and OR
If you have multiple or complex statements to be evaluated you can use the logical AND && or the logical OR || operator. If you want to know if a number is in the range from 5 to 10 you can write:

    int a=6;
    if((a>=5)&&(a<=10))
        printf("the number is bigger or equal to 5 and smaller or equal to 10");

5) while (condition)
While works almost exactly like if, as it evaluates a condition, but instead of executing the next command or scope if the condition is true, it executes the next command of scope over and over again until conditions becomes false. This is used to make loops or repeats like counting from 0 to 100:

    int a=0;
    while(a<100){
        printf("%i\n",a);
        a++;
    }

6) for(initialization;condition;manipulation)
Most of your while loops follow a certain scheme: you initialize a variable a=0 and you use a condition like a a<100 and manipulate a++ within the scope, otherwise you would loop forever anyways. So here is how you replace the above example with a for:

int a;
for(a=0;a<100;a++)
    printf("%i\n",a);

7) switch
A switch statement allows you to simplify your code. Imagine you have multiple choices to do that would fit in a list. For example you what a user choose from 5 different options. You could write:

int a;
printf("Choose option 1-5:");
scanf("%i",&a);
if(a==1) printf("you chose option one!\n");
if(a==2) printf("you chose option two!\n");
if(a==3) printf("you chose option three!\n");
if(a==4) printf("you chose option four!\n");
if(a==5) printf("you chose option five!\n");

This not only looks tedious it is also very hard to read. A switch statement for the same problem would look like this:

int a;
printf("Choose option 1-5:");
scanf("%i",&a);
switch(a){
    case 1:printf("you chose option one!\n"); break;
    case 2:printf("you chose option two!\n"); break;
    case 3:printf("you chose option three!\n"); break;
    case 4:printf("you chose option four!\n"); break;
    case 5:printf("you chose option five!\n"); break;
    default:printf("not an option!\n"); break;
}

You can see that the switch statement consist of a

switch(condition)

and several different cases:

case 0:
    //some code to execute
break;

You can list arbitrary many cases as long as each case is followed by a constant. You can unfortunately NOT do something like this:

switch(a){
case a>0: /* do something */ break;
case a==0: /* do something */ break;
case a<0: /* do something */ break;
}

If you forget the break; code will continue to be executed until the switch is left or until the next break can be found. This code:

switch(0){
    case 0:printf("zero");
    case 1:printf("one");
    case 2:printf("two");
}

Will result in this output:

zeroonetwo

Cheers Arend

Posted in Uncategorized | Leave a comment

Homework for Lecture 4

Well, this homework lets you experience more nested loops. To give you a little hunch, there are two ways to count from 0 to 99. The first looks like this:

#include <stdio.h>
int main(){
    int a;
    for(a=0;a<100;a++)
        printf("%02i\n",a);
    return 0;
}

The second one is:

#include <stdio.h>
int main(){
    int a,b;
    for(a=0;a<10;a++)
        for(b=0;b<10;b++)
            printf("%i%i\n",a,b);
    return 0;
}

Now your mission is to count how many numbers in the range from 0000 to 9999 have a digit sum of 13. The digit sum of a number is the sum of all digits. So the digit sum of 99 is 9+9=18, the digit sum of 45 is 4+5=9 the digit sum 888 is 8+8+8=24. You don’t need to sum the digits of a digit sum again!
Cheers Arend

Posted in Uncategorized | Leave a comment

Lecture 4

I admit, we didn’t get as far as I hoped for, but I think you progressed. Coding involves a lot of thinking on the programmers part. Particularly with C because everything is so basic that you really have to take care of every little detail. The examples we worked on today were selected to get you from one experience level to the other while not being obvious at the same time. Some of you experienced this:

How I look when challenged with a code problem…

The problem is that I can’t spare you this face. The more often you deal with code and programming problems the less bad this face will become, but I also promise that it will never go away entirely. I spent weeks on programming problems without the project moving an inch.

I fixed the bug in the quiz in case you want to revisit that, and you can get find the course material here:lecture 4

However let us revisit some essential steps. The core concept of this lecture dealt with the idea of nested loops. We already used single loops to count from 0 to 100 or your homework let you loop until a certain criterion was reached. Now we go beyond this and have one loop within the other. Check out the following program:

#include
int main(){
  int a,b;
  for(a=0;a<5;a++){
    for(b=0;b<5;b++)
      printf("X");
    printf("\n");
}
return 0;

And the corresponding output:

xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

What we did is:
count to 5 using variable a
—-every time we increment a we count to 5 using variable b
——–every time we increment b we print an X
—-after we counter to 5 in b we add a \n
done

If you have problems with the above example, I am almost unable to help you because that is not programming that is common sense. Visit me during my office hour on Thursday if the above example is incompatible with you.

The next example is somewhat trickier, becaue instead of making a square, we make a triangle. In the example above we had two loops, and each loop was independent of the other while they still contained each other. In this example we make the inner loop dependent on the other. Check out the code:

#include <stdio.h>
int main(){
    int a,b;
    for(a=0;a<5;a++){
        for(b=0;b<(a+1);b++)
            printf("X");
        printf("\n");
    }
    return 0;
}

and the output:

X
XX
XXX
XXXX
XXXXX

The only thing we changed was the inner loops abort criterion from b<5 to b<(a+1). As you can see this little change made the inner loop dependent on the outer one so that instead of looping to 5 we loop to a+1, and get a triangle as a result.
Cheers Arend

Posted in Uncategorized | Leave a comment

Lecture 4 Quiz

Running the following code will show what? int a=0; int b=5; a=b; b=a+b; b=b+a+b; printf("%i\n",b);

 
 
 
 
What will the following code print? int a=0; int b=1; int c=0; int d; while(c<5){ d=a+b; printf("%i \n",d); a=b; b=d; c++; }

 
 
 
 
will the following code compile? #include  <stdio.h> int main(void){ int a; scanf("%i",&a); return 0; }

 
 
 
 
 
Which line of code will print the following output: Hello World!

 
 
 
 
 
what is wrong with the following code? #include int main(void){ int a,b; while(a<100){ a++; b=0; printf("%i",a++); while(b<a) printf("!"); return 0; }

 
 
 
 


Posted in Uncategorized | Leave a comment

Homework L2 results

Here is a list of your scores on the homework for Lecture 2:
ah 8
an 8
ar 8
cr 10
dk 10
dm 10
ds 10
dz 10
fl 8
gj 8
gw 10
hk 8
jg 10
jl 9
jm 10
js 10
jw 10
kw 10
mj 10
mr 10
ms 8
nh 8
rb 8
rl 10
rs 10
sg 10
tp 10
ts 10
xz 8
yj 10

The main mistakes where:

A) that you forgot to label the inputs, you had three scanf statements followed by three printf, the user has no idea what is going on, so please add a printf in front of every scanf describing what the input is supposed to be

B) you forgot the permutations and returned the variables six times in the order ABC

C) float instead of int in front or main … while that compiles, it for sure gives a warning, and the OS expects a sane return value and these return codes are int and not float, I don’t think it matters in a current modern OS, but who knows for sure, so use int main, and return a 0

Cheers Arend

Posted in Uncategorized | Leave a comment

errata to Lecture 3

I said that if(0) would be evaluated as true, but that is wrong, if(1) would be evaluated as true, sorry for the confusion. Next lecture I will show you stdbool.h which allows us to use the word true and false, which is so much easier than to use 0 or 1 as false and true. Example

#include <stdio.h>
#include <stdbool.h>

int main(){
    if(true)
        printf("true\n");
    if(false)
        printf("false\n");
    return 0;
}

Cheers Arend

Posted in Uncategorized | Leave a comment

Homework for lecture 3

Please keep generating three random numbers, where each random number is in the range of 0 to 100. Stop generating triplets of random numbers when one of the two following criteria is met:

A) Random number one is equal to random number two and random number one plus random number two is equal to the third random number. Example: 10 10 20, or 30 30 60

B) The three random numbers count upward, so that random number two is random number one plus 1, and random number three is one bigger than random number two. example  1 2 3 or 10 11 12

Make it pretty: Show all the triplets and if you want count them. Name the file CSE251_L3_AH.c (where AH should be replaced by YOUR initials…) mail the homework to me hintze@msu.edu until Monday morning 8am.

Cheers Arend

Posted in Uncategorized | Leave a comment