Advertising (This ad goes away for registered users. You can Login or Register)

[Tutorial] Introduction to programming using C (VIII)

Discuss about your favorite (gaming...or not) devices here. The most popular ones will end up getting their own categories
Programming discussions for your favorite Device
Forum rules
Forum rule Nº 15 is strictly enforced in this subforum.
User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

[Tutorial] Introduction to programming using C (VIII)

Post by m0skit0 » Mon Jul 09, 2012 11:43 am

Back to index
<< Prev Next >>

Code flow

Until now, our code executed from first line to last line passing through all lines. Sometimes we don't want this, as we want to perform some operations only if certain conditions are met. For this, we have control flow instructions, which will allow us to execute or not blocks of code based on certain conditions.

The most simple control flow instruction is if

Code: Select all

if (expression1)
{
	// Code executed if expression1 is true
}
else if (expression2)
{
	// Code executed if expression1 is false and expression2 is true
}
else
{
	// Code executed if all previous expressions are false
}
The switch control flow instruction allows more readable ifs. It's usually used when comparing a variable value with a set of predefined values:

Code: Select all

switch(variable)
{
	case value1:
		// Code executed if variable == value1
		break;
	case value2:
		// Code executed if variable == value2
		break;
	default:
		// Code executed if none of the previous cases was executed
}
The use of break reserved word is to exit the switch() statement. If break is omitted, the execution will enter next case and execute its code as well. This can be interesting to use in very few cases, but breaks code readability so bad I don't recommend it.

The while loop is a loop control flow statement. This means the block of code enclosed between the while braces could execute more than once. This is very useful when we want to do an operation several times until a condition is fulfilled.

Code: Select all

while(expression)
{
	// This code will be executed as long as expression is true
}
In this case, the code inside the while has to modify somehow the evaluation of the expression (I'm not considering multi-threading or process inter-communication here). Otherwise you will get what's known as an infinite loop. This is when the loop is badly written and the loop never ends (the expression is always true). Also please note that if expression is false before entering the loop, the code inside the while will not be executed. Also keep this in mind if a program you wrote hangs: it could probably be because of an infinite loop!

Another way of writing a while loop is

Code: Select all

do
{
	// This code will be execute at least once
} while(expression);
This will execute the code inside the do-while loop at least once. This is because the expression is evaluated after the execution of the code inside and not before like in the normal while.

Another very used loop construct is the for loop. You can think of this as a special while loop where you do some stuff automatized, so you don't have to include extra code inside the loop

Code: Select all

for(expression1; expression2; expression3)
{
	// This code will execute as long as expression2 is true
}
expression1 is executed only once before the loop begins. expression2 is evaluated after each loop (think of it as the equivalent of while(expression)). expression3 is executed after each loop as well. Usually expression1 is used as an initialization. expression2 controls the end of the loop. expression3 is usually used as an increment operation.

The for loop suits better when we know we're going to loop a code a fixed number of times. For example, to calculate the average of an array of numbers, we can use a for loop:

Code: Select all

#include <stdio.h>

// Pre-processor directive: defines 
#define ARRAY_SIZE 8

int main()
{
	int array[ARRAY_SIZE] = {2, 5, 9, 10, 45, 5, 1, 3};
	int total = 0;
	
	// We sum all the numbers on the array
	int i;
	for (i = 0; i < ARRAY_SIZE; i++)
	{
		total += array[i];
	}
	
	// We calculate the average value of the array and print it
	float average = (float) total / (float) ARRAY_SIZE;	
	printf("The average of the array is %f\n", average);
	
	return 0;
}
This is a typical usage of for loop. Note the usage of i as a counter. This is somehow standard: you use i, j, k, h... for indexes and/or counters.

The #define preprocessor directive allows us to use symbols instead of literals. This is NOT processed by the compiler, this is not real code. What the preprocessor actually does is replace all instances of the ARRAY_SIZE symbol by its value (8) before the file is passed to the compiler. This allows us fast modification of this value if needed, since we only have to modify the #define and not all occurences of the number 8.

So now some exercises to practice this new stuff ;)

For all exercises:
  • It's not allowed to use any external library to do the main task of the exercise (string.h is forbidden! :mrgreen: ).
  • Use the #define directive instead of using literals.
  • Write a program that given an array of 10 numbers, prints only the even numbers.
  • Write a program that given an array of 10 numbers, prints only the odd positions.
  • Write a program that given an array of 10 numbers, prints only the 2 first multiple of 3 numbers.
  • Write a program that given one string, prints its length.
  • Write a program that given 2 ASCII stings as an input, checks if they are exactly equal.
  • Write a program that checks if one string is part of another (if it's a substring).
  • Write a program that given an array of 10 numbers, it orders it ascendantly.
  • Write a program that given 2 ASCII stings as an input, checks if they are exactly equal, but case-insensitive (that is, given "hello" and "HeLLo", it should say they are equal) This one could be a bit tricky ;)
  • Write a program that given two matrices float a[3][3] and float b[3][3], adds them.
Have fun and good luck! :geek:

<< Prev Next >>
Advertising
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

snailface
Posts: 95
Joined: Tue May 24, 2011 8:02 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by snailface » Mon Jul 09, 2012 10:16 pm

Write a program that given 2 ASCII stings as an input, checks if they are exactly equal, but case-insensitive (that is, given "hello" and "HeLLo", it should say they are equal) This one could be a bit tricky ;)
Alright, I gave the tricky one a shot since it sounds the most interesting. Didn't turn out as simple as I hoped, but it works :)

[spoiler]

Code: Select all

#include <stdio.h>

#define one "THis IS a STRinG wITH CaPs sTicKing."
#define two "This is a string with caps sticking."
int main()
{
    //our two example strings, defined above.
    char str1[]=one;
    char str2[]=two;

    int notSame=0; //flag that stores our comparison status
    int x=0;       //string array position

    do
    {
        //if either string is at a capital letter,
        //add 32 to char value to make it lower-case.
        //-this eliminates case difference as a comparison
        //condition
        if(str1[x]>64 && str1[x]<91) str1[x]+=32;
        if(str2[x]>64 && str2[x]<91) str2[x]+=32;

        //compare letters. trip notSame flag if they
        //are different
        if(str1[x] != str2[x])notSame=1;

        x++;//advance to next letter
    }
    //if either string ends in NULL, break loop
    while(str1[x]!=0 && str2[x]!=0);

    //if both strings are not 0 at loop break, they must
    //be different lengths -- trip flag if true.
    if(str1[x]!=0 || str2[x]!=0)notSame=1;

    if(notSame==0)printf("These two strings are identical, save possibily for case-sensitivity!");
    else
        printf("These two strings are not identical!");

    return 0;
}
[/spoiler]
Advertising
Image

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by m0skit0 » Tue Jul 10, 2012 7:15 am

Yeah very nice, you found the best way to do it (ASCII-wise of course :mrgreen: ) ;) And a few comments if you don't mind:

[spoiler]

Code: Select all

#define one "THis IS a STRinG wITH CaPs sTicKing."
Usually constants (#define) are written in all-caps to differentiate them from variables. So this should be called ONE. Also one is a very horrible name that tells nothing about its value.

Code: Select all

int x=0;       //string array position
As I said in the OP, for counters and/or indexes, use i, j, k... not x, y. This is kind of a mathematical notation where i, j, k are usually used for indexes, while x,y are unknown arbitrary values.

Code: Select all

if(str1[x] != str2[x])notSame=1;
Please don't do this. You'll regret it later, trust me. Better write it like

Code: Select all

if(str1[x] != str2[x])
{
	notSame=1;
}
Much more readable an maintainable. You can also simply do this:

Code: Select all

notSame = (str1[x] != str2[x]);
Same goes for all your ifs: use the dang braces! Always! ;)

Code: Select all

while(str1[x]!=0 && str2[x]!=0);
Why you keep going comparing the strings when you already know they are different? Makes no sense, right? ;)

Code: Select all

if(str1[x]!=0 || str2[x]!=0)notSame=1;
This is strange to compare it again when you already did it per each character in the loop. Get rid of this and fix the loop to take this into account.[/spoiler]
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by Wdingdong » Wed Jul 11, 2012 9:01 am

Code: Select all

#define ARRAY_SIZE 8linked list
What is this 'linked list' for?
// Big thanks to people who share information !!!

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by m0skit0 » Wed Jul 11, 2012 9:07 am

It's... a typo :lol: This is due to a Linux feature: to copy-paste text, you just select the text and then paste it using middle-click button. That happened with "linked list" ;)
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by Wdingdong » Wed Jul 11, 2012 5:30 pm

And THIS is my first Ubuntu post :D What a coincidence :D
PS: Sorry for off topic

Edit: What are literals? You said to use #define for literals.
Edit2: Do you mean by array size or array contents also?
// Big thanks to people who share information !!!

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by m0skit0 » Mon Jul 16, 2012 8:50 am

Wdingdong wrote:What are literals? You said to use #define for literals.
Literals are expressions defined at compiled time. For example: 2. 2 is a literal since it doesn't need anything else to know that this expression evaluates to 2.
Wdingdong wrote:Do you mean by array size or array contents also?
I don't understand this question.
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by Wdingdong » Tue Jul 17, 2012 2:46 pm

So, literals are similar to constants right?
And I meant whether I should use #define for array contents also? They are also literals right?
// Big thanks to people who share information !!!

User avatar
m0skit0
Guru
Posts: 3817
Joined: Mon Sep 27, 2010 6:01 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by m0skit0 » Tue Jul 17, 2012 3:13 pm

Constants in C have a different meaning, but yes, you can consider literals as constant expressions (this is not always true, but it's OK... for now).
Wdingdong wrote:And I meant whether I should use #define for array contents also? They are also literals right?
Well #defines are really for literals you're going to use repeatedly through the program, so to modify the value you only have to do it once in the #define and not search the literal through all the program (and guess if that literal actually must be changed). Usually array initialization is only used once, so it makes no sense to use a constant for it.
I wanna lots of mov al,0xb
Image
"just not into this RA stuffz"

Wdingdong
Posts: 92
Joined: Tue Aug 02, 2011 5:34 pm

Re: [Tutorial] Introduction to programming using C (VIII)

Post by Wdingdong » Thu Jul 19, 2012 3:05 pm

Even Numbers

Code: Select all

#include<stdio.h>
#define size 10

int main()
{
	int a[size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	int i;
	for(i = 0; i < size; i++)
	{
		if(a[i] % 2 == 0)
			printf("%d\n",a[i]);
	}
	return 0;
}
Odd Positions

Code: Select all

#include<stdio.h>
#define size 10

int main()
{
	int a[size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	int i;
	for(i = 0; i < size; i++)
	{
		if(i % 2 == 1)
			printf("%d\n",a[i]);
	}
	return 0;
}
Length of String

Code: Select all

#include<stdio.h>
#define size 10

int main()
{
	char a[size] = "Freedom";
	int c = 0;
	int i = 0;
	while(a[i] != '\0')
	{
		c += 1;
		i++;
	}
	printf("Length of the string is %d", c);
	return 0;
}
I'm still working on the rest :oops:
BTW,
2 first multiple of 3 numbers.
I didn't understand this.
// Big thanks to people who share information !!!

Post Reply

Return to “Programming and Security”