Jump to content

1-2-3's

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
8 replies to this topic

#1
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
Helping people get this ****ty idea out of their heads. C is not a hard language.
So C is just like batch you can input stuff, output stuff, to use that we include:
STDIO.H // Standard input/output
to output something we put printf("Hello world")
To ask the user for something we use scanf();
now to start a program.
To declare a variable.. there's :
Char, int, float that are mostly used.
a 1 in float is 1.000000
So lets make a simple program that asks for two numbers then does the sum and prints it shall we :) ?
first of all
%d = decimal ( integer )
%s = string
%c = char
%f = float
%.2f = displays two numbers after the comma
%.3f = Displays three numbers after the comma. like 1.123
\n = new line
\t = gives a little space.

#include<stdio.h>

main()

{

int a,b,c; // you can see we use a ; at the end of every line, except some statements

printf("Enter two numbers\n");

scanf("%d%d", &a,&b);  The & is used to assign the value entered in %d for the variable.

c=a+b;

printf("%d", c);

}

So that's easy right ?
To conceive less memory we can use instead of
int c;
unsigned c;
now to move to other statements.

IF statements :
There are logical operators :
== ( equal )
!= ( NOT equal )
< ( smaller than )
!< ( NOT smaller than )


If(condition)

    action

else if(condition

    action

else 

   action

Now if the action is only 1 line of code we won't need { }
if the first statement is wrong, it checks if the second is true. If none are true it goes to the ELSE.

There's the modulo in C wich is %

fprintf("%d", 10%2);

Will display 0, Why ? well you should know what a modulo is. I'm not that good in english :P
So lets make a statement that checks if a number is dividable by two

if((number%2)==0)

 printf("%d is dividable by two", number);

else

 printf("%d is not dividable by two", number);


Now we go to loops.
There are 3 kinds of loops, for, while, DO.. while.
using for is like this:

for(i=0; i<10; i++)

{

  printf("Hi\n");

}

same thing in while it would be like

while(i<10)

{

printf("HI\n");

i++;

}

You can see a while loop does not add anything automatically. you need to add the variable or else it would get stuck in the loop.
now do while is the following:

do{

printf("Hi\n");

i++;

while(i<10);

now what it does is that it doesn't check for the condition untill it does the action

Now to move on to Switch Statement:

A switch statement is just like an easier " IF else if else if else if... "

This

#include<stdio.h>

int main()

{

int c;

scanf("%d", &c);

if(c==0)

{

printf("You entered 0");

}

else if(c==1)

{

printf("You entered 1");

}

else if(c==2)

{

printf("You entered 2");

}

}

Can be replaced by

#include<stdio.h>

int main()

{

int c;

scanf("%d", &c);

switch(c)

{

case 0:

printf("You entered 0");

break;

case 1:

printf("You entered 1");

break;

case 2:

printf("You entered 2");

break;

}

}

you can see we used switch(variable)
You can consider the variable as something the switch holds and checks the cases.
lets take a virtual example,
lets say if switch case 1 is true, the value is now 1(true)
So now it won't check for others. it will just keep going writing all the other cases.
Thats why we use "Break" statement, it will break the loop,if,switch statement and move on.

If case 1: is false, it won't check whats inside knowing that it won't be needing it!

So now that we know what switch is.. Lets do some examples on all those statements;

A calculator using if statement

#include <stdio.h>


int main()

{

float num1, num2;

char operation;

while (1) {

scanf("%f%c%f", &num1, &operation, &num2);

if (operation == '+')

printf("%f\n", num1+num2);

if (operation == '-')

printf("%f\n", num1-num2);

if (operation == '*')

printf("%f\n", num1*num2);

if (operation == '/')

printf("%f\n", num1/num2);

}

getchar();

return 0;

}

GUEST MADE IT NOT ME.

Thats for the if, now that you know how to use switch, you should know how to change all of those if's to switch cases...

Now for using strings..
A string is like uhh a sentence !
How do we call it a string ? Easy !
char str[lengh];

keep in mind that the string will hold a '\0' so if you call the lengh 90, it will only hold 89 letters.

So how to ask the user to input a string ? there are many ways ! But the safest one is
fgets(buffer, buffer_size, stdin);

Why we use this ? because simply this limits the amount of characters to take from the user to prevent buffer overflows ( Zekedragon told me that :P )

To print a string you can either use printf("%s", str);
or puts(str);

keep in mind while using fgets when you press enter it will also grab the enter and put it in the string.
So if we put " hello man [enter] "
The string will say " Hello man \n" taking the crusor to a new line..
To clear it up we use a " LOOP "

for ( i = 0; i < stringsize; i++ )

{

    if ( input[i] == '\n' )

    {

        input[i] = '\0';

        break;

    }

}

This will eliminate the new line for us :)
Now of course our beloved C has made things easier for us by making a library called " string.h "Wich holds some usefull statements like

strcpy

strcat

strlen

strcat is short for "string concatenate"; concatenate is a fancy word that means to add to the end, or append. It adds the second string to the first string. It returns a pointer to the concatenated string. Beware this function; it assumes that dest is large enough to hold the entire contents of src as well as its own contents.

strcpy is short for string copy, which means it copies the entire contents of src into dest. The contents of dest after strcpy will be exactly the same as src such that strcmp ( dest, src ) will return 0.

strlen will return the length of a string, minus the termating character ('\0'). The size_t is nothing to worry about. Just treat it as an integer that cannot be negative, which is what it actually is. (The type size_t is just a way to indicate that the value is intended for use as a size of something.)


Now a small program to make things easier:

#include <stdio.h>    /* stdin, printf, and fgets */

#include <string.h>   /* for all the new-fangled string functions */


/* this function is designed to remove the newline from the end of a string

entered using fgets.  Note that since we make this into its own function, we

could easily choose a better technique for removing the newline.  Aren't

functions great? */

void strip_newline( char *str, int size )

{

    int i;


    /* remove the null terminator */

    for (  i = 0; i < size; ++i )

    {

        if ( str[i] == '\n' )

        {

            str[i] = '\0';


            /* we're done, so just exit the function by returning */

            return;   

        }

    }

    /* if we get all the way to here, there must not have been a newline! */

}


int main()

{

    char name[50];

    char lastname[50];

    char fullname[100]; /* Big enough to hold both name and lastname */


    printf( "Please enter your name: " );

    fgets( name, 50, stdin );


    /* see definition above */

    strip_newline( name, 50 );


    /* strcmp returns zero when the two strings are equal */

    if ( strcmp ( name, "Alex" ) == 0 ) 

    {

        printf( "That's my name too.\n" );

    }

    else                                     

    {

        printf( "That's not my name.\n" );

    }

    // Find the length of your name

    printf( "Your name is %d letters long", strlen ( name ) );

    printf( "Enter your last name: " );

    fgets( lastname, 50, stdin );

    strip_newline( lastname, 50 );

    fullname[0] = '\0';            

    /* strcat will look for the \0 and add the second string starting at

       that location */

    strcat( fullname, name );     /* Copy name into full name */

    strcat( fullname, " " );      /* Separate the names by a space */

    strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */

    printf( "Your full name is %s\n",fullname );


    getchar();


    return 0;

}

Credits for C programming.com - Your Resource for C and C++ Programming for the last source and string definitions :)

#2
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts
Overall, this seems like a random hodge-podge of bits that does a lesser job than most of introducing the C language.

[quote name='Moudi']To ask the user for something we use scanf();[/QUOTE]I generally advise avoiding scanf -- unless you are willing to venture into all of the caveats and issues that arise when you attempt to use it safely and correctly (which can be non-trivial).

[quote name='Moudi'][/quote]
Implicit int declaration of main has really been out of date since 1989. With scanf, which I mentioned earlier has many issues, you should at least be checking the return value to see if you actually obtained the input before using them. I might also add that main returns an int, and generally 0 is what is returned for success.

[quote name='Moudi']So that's easy right ?[/quote]
Meh.

[quote name='Moudi']To conceive less memory we can use instead of
int c;
unsigned c;
now to move to other statements.[/quote]
I have no idea why or what you are trying to say here. Both likely use the exact same amount of memory, and this bit just appears out of nowhere for no reason (as well as not really being correct).

[quote name='Moudi']!< ( NOT smaller than )[/quote]
Are you kidding me?

[quote name='Moudi'][/quote]
Match parens.

[quote name='Moudi']Now if the action is only 1 line of code we won't need { } [/quote]
True. And like the source of future bugs. I always use braces. I recommend it.

[quote name='Moudi']Now we go to loops.
There are 3 kinds of loops, for, while, DO.. while.
using for is like this:

same thing in while it would be like
[/quote]
You might as well try to write equivalent loops -- which would require you to initialize i for the while loop. Especially since...

[quote name='Moudi']You can see a while loop does not add anything automatically. you need to add the variable or else it would get stuck in the loop.[/quote]...you bring up the attempt for equivalence here. And the for loop doesn't add anything automatically for you either -- the code to do so is in a different location.

[quote name='Moudi']now do while is the following:

now what it does is that it doesn't check for the condition untill it does the action [/quote]Which means (an important thing to bring up) that a do...while will always execute at least once. Again, though, i needs to be initialized.

[quote name='Moudi']A switch statement is just like an easier " IF else if else if else if... "[/quote]Except that a switch only works with integer constants for cases. So you can't use if for string comparisons. You can't use it for ranges.

[quote name='Moudi']Thats why we use "Break" statement, it will break the loop,if,switch statement and move on.[/quote]
When a switch is in a loop, the break statement in a case will not break the loop, it will break out of the switch. I'm not sure what you're trying to say.

---

Overall, this is quite a mixed bag of various things you mention. But I don't think it's a good substitute for other introductions such as:
[url=http://c-faq.com/~scs/cclass/notes/top.html]C Programming Notes[/url]

Keep at it, though. I try to offer constructive criticism. I hope my comments are received as such, even though the words I choose at times may seem unduly harsh.

#3
Moudi

Moudi

    Programmer

  • Members
  • PipPipPipPip
  • 167 posts
Okay uhh , thanks ?

#4
se7en

se7en

    Learning Programmer

  • Members
  • PipPipPip
  • 30 posts
Nice tut Moudi

#5
TriggerHappy

TriggerHappy

    Learning Programmer

  • Members
  • PipPipPip
  • 30 posts

Moudi said:

Okay uhh , thanks ?

That's all you have to say after he took is time to review your (not-so-good) tutorial?

#6
n00py

n00py

    Newbie

  • Members
  • Pip
  • 4 posts

Quote

#include <stdio.h>

int main()
{
float num1, num2;
char operation;
while (1) {
scanf("%f%c%f", &num1, &operation, &num2);
if (operation == '+')
printf("%f\n", num1+num2);
if (operation == '-')
printf("%f\n", num1-num2);
if (operation == '*')
printf("%f\n", num1*num2);
if (operation == '/')
printf("%f\n", num1/num2);
}
Get rid of this code. scanf isn't used correctly. Have a peak at this post for more information.

#7
XJamesX

XJamesX

    Newbie

  • Members
  • PipPip
  • 17 posts
Helping people get this ****ty idea out of their heads. C is not a hard language.

Any language can be hard to learn for most people when they first start out. I recommend just getting your hands on a good book. No one short post could ever cover all the basics and if you believe so you may want to also go and get a nice book. scanf is fine to start off learning with and it's flaws shouldn't even be mentioned till the student has a fine enough grasp on simple programming concepts. They are plenty of standard C functions that can totally screw up an otherwise great program.

And btw signed and unsigned ints are the same size. You may of been thinking of short int, int, long int, long long int. Which have no gaurentees of having different sizes either. The only guarentee is that long long int >= long int >= int >= short int. The sizes are machine specific and the knowledge can really be skipped until some better foundation in programming has been established.

They are other flaws in your post that dcs didn't pick up on. On a 5 star rating for useful tutorials I have to give this just 1 star. Sorry. Keep practicing and learning you are getting there. I think a "newb" would be better off skipping this tut.

I guess I'll just leave off saying learning to program isn't hard. It's the programming concepts that can be hard (and the jargon).
C is basicly a few reserved keywords and operators.

Edited by XJamesX, 23 March 2010 - 09:09 AM.
typo iaks

while(1) { if(if_girl_is_pretty(girl)) ask_her_out();
else drink_another_beer(); }

#8
ToMegaTherion

ToMegaTherion

    Newbie

  • Members
  • PipPip
  • 29 posts
Another useful thread i've been doing some study on C programming in the last few months and the lecturer over complicates the language. I hope you don't mind but I've made copy of this tutorial for my own reading. I find it is always useful to have multiple materials when learning a programming language.

I agree that C is quite easy, the problem is when people are first starting out and they find it difficult to understand some of the concepts of programming theory in general.

Thanks for writing this tut.

#9
wiwbiz

wiwbiz

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
That's a good tutorial and good reviews. No doubt it's helpful for beginners to start. A revealing criticism will be much appreciated although , i.e. not just " why did you use scanf() " ,insteed " you should use (something) because it help you to overcome problem like (something) "