View Feed
group-icon
Coffee Room
Discuss anything here - everything that you wish to discuss with fellow engineers.
12838 Members
Join this group to post and comment.
simplycoder
simplycoder • Aug 19, 2011

Beginners Tutorial : The C-language.

Hello this is simplycoder, and welcome to the series of C programing tutorials.

I request not to post questions or anything in this thread, as it will only disrupt the flow and co-ordination of the tutorials.


OK everyone, this tutorial is basically designed for programmers, basically new to computing or new to "The C-Language".
So now let us get started with the C.


History of C


  • C language was developed by Dennis Ritchie in early 70s at the Bell Laboratories for Unix operating system.
  • C is a procedural language.
  • C was influenced by B, ALGOL, FORTRAN and Assembly.
  • C influenced most of the modern world programing languages which include the mighty C++ and Java as well.
Above points are enough to answer the most common questions asked in vivas (oral-examinations) or objectives.

As of now, this much is enough for more, google for C.
Tutorial-1 will be posted in another dedicated post.
Until then take care
Ciao.

PS: These tutorials will be based on DevC++ IDE and on Windows platform
you can download DevC++ from here Bloodshed Software - Providing Free Software to the internet community
-------------------------------------------------------------------------------------------------------------------------------------
INDEX
Tutorial 1
Tutorial 2
Tutorial 3
Tutorial 4
Tutorial 5
Tutorial 6
Tutorial 7
Tutorial 8
Tutorial 9
Tutorial 10
Tutorial 11
Tutorial 12
Tutorial 13
Tutorial 14
Tutorial 15
Tutorial 16
Tutorial 17
Tutorial 18

-------------------------------------------------------------------------------------------------------------------------------------

simplycoder
simplycoder • Aug 19, 2011
Re: Beginners Tutorial : The C-language :: Tutorial-1

Tutorial-1
Hello this is simplycoder and welcome to the first tutorial on C.

In this tutorial, we are going to learn the basic structure of a C-program.

Any C program will contain a function called as: int main(int argc,char*argv[])
Now let us break this in parts and analyze one by one.

1)What is a function?
Function is a small part of entire program,containing some set of instructions that is generally dedicated to perform a specific task.
Advantages: Easy to debug,code resuability.
Disadvantage: Lengthy code.

2) int: it is a built in data type stands for Integer, we are going to understand the data-types in more detail in comming tutorials, as of now just understand that a data-type is something that signifies the type of data,which helps the compiler to allocate the memory. We are also going to learn about memory allocation and other stuffs in later tutorials,however as of now we can describe memory allocation similar to reserving space for something. Typing 'int' in front of the function,tells the compiler to return an Integer value once you finish the execution from the function.

3)main: This is the name of the function. Every program,like in real life, needs a starting point. main exactly does that. Generally, any name followed by '()' signifies that it is a function. This is basically syntax. Whatever is typed inside the '()' are called as parameters.

4) As of now, we can skip what is the meaning of (int argc,char*argv[]). We will require this when we read some file from the command line, but as of now its ok even if we skip it.

Now that we know meaning of individual parts in the main function, there are few more things that are required to understand before we can start writing our first program.

Let me explain the next concept with an example.

Consider a large thermo-flask of coffee , similarly one that of milk and so on and these flask are never empty.
In order to make one cup of coffee, I just have to pour some coffee and milk in my cup. That is it.
Similarly in order to make 10 cups of coffee,I just have to pour some coffee and milk in 10 cups according to their needs,they can have black coffee aswell.
The point is that I will never make coffee again by myself, all I will do is to use the coffee which is already available,use some milk which is already available,without bothering about it or how that coffee was brewed or any details on milk.

In C, there are various inbuilt functions which can be used by programers. Say for example, there is a function which helps to print some thing on screen,then there is another which helps to read the input from the user, without even bothering about it. This is called as code reusability.
In C, there are two such important files

1)stdio.h
2)stdlib.h

stdio.h stands for 'standard input-output header file'
stdlib.h stands for 'standard library functions header file'

What is a header file?
Header files allow programmers to separate certain elements of a code into reusable files. Header files commonly contain declarations and in this way, it helps to standardized a program.Header files donot contain implementations.

Now the question arises: how do we use the material from the above two header files? How can we convey the compiler to include these two files in our program?There is our next syntax,

5)#include:
This is basically called as preprocessor directive, as from the name, we can easily guess that it is going to be accessed before the process starts.

In C-style syntax, we tell compiler as follows:
#include
#include

In simple terms, compiler includes the files in the angle bracket along with your source code.Now we are in a position to write our first program based on our basic structure using some more things along with what we have already learnt.
#include 
#include 
/*Author : simplycoder*/
int main(int argc, char *argv[])
{
  printf("Hello World!");//Print something.
  system("PAUSE");    
  return 0;
}
6)printf(): It is a built in function which is used to print the data on the screen.It stands for print formatted as it accepts a string,another data-type along with other format specifier, things will be cleared once we start to program regularly.

7)system("PAUSE"): This is pretty much self explanatory, try running your code without this and check for the results.

8)return 0: This is called as fullfilling the promise. We made a promise to the compiler that main function will return an integer once it about to exit.

Minor details before I conclude with:

9)'{..}' or use of curly brackets: This tells the compiler- "No matter what it appears, treat this block of code as a single statement"
We shall see much more use of curly braces in control-structures.

10) ';' or use of semi-colon: this conveys the compiler that it is the end of the statement syntactically, its similar to period in english.

11)The comments: There are 2 types of comments in C.

11.a) // or Single line comment : This tells the compiler,"Donot consider the data beyond the '//' on that particular line"

11.b)/* ... Some comment ...*/ or multiline comment: This tells the compiler" Donot consider the block of data included between '/*' and '*/'

Comments are really very useful in lengthy programs, they help to make other users quickly understand the block of code or nature of variables or in general anything that the author of the program wants to convey.

Exercises:
Modify the above program,check what errors you get if you remove ';'
Modify the above program,check what errors you get if you remove '{' or '}'
Modify the above program,check what errors you get if you remove 'system("PAUSE")'
Play with it until you get bored of it.😉

I know this has been a long tutorial hopefully it wasnt boring either, please send me a PM if you found some bug or something that I may have skipped or if you disliked the tutorial or if you liked it what ever it is, please give a feed-back so that I would know where to improve in my next tutorial.
In next tutorial, we shall discuss concepts related to variables,data-types and more..
Keep playing with C
Until then take care
Ciao.
SagaRocks
SagaRocks • Aug 19, 2011
tutorial is nice but add some colors to it so that it will looks better and more peoples will read it..!!! 😀
simplycoder
simplycoder • Aug 20, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-2

Tutorial-2

Hello everyone again this is simplycoder and welcome to the 2[SUP]nd[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn about variables,different data-types and other related stuff.

What are data-types?
In C-programing, a data can be represented in different formats.
an example might be as follows, in mathematics, 12 and 12.0 are same, however in computer science, the memory required by 12 and 12.0 is different.
The number of bits required to store an integer is not the same as the number of bits stored by a floating point value(decimal point value).
So the question arises how to tell the compiler to allocate the memory for different types of data?
The answer to this is by telling the complier the data-type of the value or data which is the type of the data.
C language data types can be classified as


  • Primary data type
  • Derived data type
  • User-defined data type
Concept of : signed,unsigned,short and long.
This is pretty simple as signed data-type means that it will cover the positive and the negative values as well.
Unsigned data-type will cover only the positive values starting from 0.
short datatype will allocate either same or less than the main type of the data and definitely lesser memory as compared to long-datatype of the same.
short int <= int <= long int
float <= double <= long double


[TABLE="class: grid"]
[TR]
[TD]Type[/TD]
[TD]Size (Bits)[/TD]
[TD]Range [/TD]
[/TR]
[TR]
[TD]Char or Signed Char[/TD]
[TD]8[/TD]
[TD]-128 to 127[/TD]
[/TR]
[TR]
[TD]Unsigned Char[/TD]
[TD]8[/TD]
[TD]0 to 255[/TD]
[/TR]
[TR]
[TD]Int or Signed int[/TD]
[TD]16[/TD]
[TD]-32768 to 32767[/TD]
[/TR]
[TR]
[TD]Unsigned int[/TD]
[TD]16[/TD]
[TD]0 to 65535[/TD]
[/TR]
[TR]
[TD]Short int or Signed short int[/TD]
[TD]8[/TD]
[TD]-128 to 127 [/TD]
[/TR]
[TR]
[TD]Unsigned short int[/TD]
[TD]8[/TD]
[TD]0 to 255[/TD]
[/TR]
[TR]
[TD]Long int or signed long int[/TD]
[TD]32[/TD]
[TD]-2147483648 to 2147483647[/TD]
[/TR]
[TR]
[TD]Unsigned long int[/TD]
[TD]32[/TD]
[TD]0 to 4294967295[/TD]
[/TR]
[TR]
[TD]Float[/TD]
[TD]32[/TD]
[TD]3.4 e-38 to 3.4 e+38[/TD]
[/TR]
[TR]
[TD]Double[/TD]
[TD]64[/TD]
[TD]1.7e-308 to 1.7e+308[/TD]
[/TR]
[TR]
[TD]Long Double[/TD]
[TD]80[/TD]
[TD]3.4 e-4932 to 3.4 e+4932[/TD]
[/TR]
[/TABLE]





The above values are for a 16-bit machine.

We shall discuss derived data-types and user-defined data-types in their dedicated tutorials.
As of know, knowing just the simple data types is more than enough.

What are variables?
Variables in computer science is something that symbolizes the known or unknown data.
Variable names are independent of the data-type of the variable.
Variables can be changed in the course of execution under proper conditions.
Variable names are nothing but temperory names given to some part of memory.

Now we are in a position to write our first program which involves usage of variables.
In this program, we are going to add two numbers and store them in a variable and display this variable.
/*Author : simplycoder*/
#include
#include

int main(int argc,char*argv[])
{
    int number1=5;
    int number2=10;
    
    int answer=number1+number2;//Add the two numbers
    printf("The answer is %d\n",answer);
    system("PAUSE");
    return 0;
}
In the above code,number1,number2,answers are called as variables.
int number1=5, this tells the compiler that the variable number1 is going to contain an integer,so allocate memory required to store an integer.
same is with number 2 and answer.
Take a look at the statement 'printf("The answer is %d\n",answer);'
As stated in tutorial-1, printf() takes the format specifier, "%d" is used when we expect to print an integer value.

Here is a list of format specifiers:
%c The character format specifier.
%d The integer format specifier.
%i The integer format specifier (same as %d).
%f The floating-point format specifier.
%e The scientific notation format specifier.
%E The scientific notation format specifier.
%g Uses %f or %e, whichever result is shorter.
%G Uses %f or %E, whichever result is shorter.
%o The unsigned octal format specifier.
%s The string format specifier.
%u The unsigned integer format specifier.
%x The unsigned hexadecimal format specifier.
%X The unsigned hexadecimal format specifier.
%p Displays the corresponding argument that is a pointer.
%n Records the number of characters written so far.
%% Outputs a percent sign.

try it out yourself.

Next to format specifier, you shall find "\n". This is called as an escape sequence.
An escape sequence is combination of a backslash '\' and a letter. Its taken as one single character.

The following is a list of commonly used escape sequences.
\n : Newline
\t : Horizontal Tab
\v : Vertical Tab
\b : Backspace
\r :Carriage Return
\f :Form feed
\a :Audible Alert (bell)
\\ :Backslash
\? :Question mark
\' : Single quote
\" : Double quote

************************************************************************************************
Exercise:
Write program to subtract,multiply and divide(this is slightly tricky, grasp the knowledge of data-types first).
Write program to find average of two numbers.
Write many simple programs till the time,either you are bored or you get proper hang of the syntax.😉
Play with different data-types and escape sequences.
************************************************************************************************

OK. Here I conclude this tutorial.Do let me know about this tutorial via a PM. Your feed-back will help me improve and in turn make better tutorials.
In next tutorial we shall learn how to take input from the users, something related to storage classes , constants and other related stuff.
Until then take care.
Ciao




simplycoder
simplycoder • Aug 20, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-3

Tutorial-3

Hello everyone again this is simplycoder and welcome to the 3[SUP]rd[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn about keywords,constants, reading input from user(scanf()).

What are keywords?
Keywords in C are the words which have special meaning.The meaning of these words is already explained to the compiler.
So a programer cannot use keywords as variable names. Please note that main is not a keyword.
Here is the list of keywords for C.
[TABLE="class: grid"]
[TR]
[TD]double[/TD]
[TD]int[/TD]
[TD]struct[/TD]
[/TR]
[TR]
[TD]else[/TD]
[TD]long[/TD]
[TD]switch[/TD]
[/TR]
[TR]
[TD]enum[/TD]
[TD]register[/TD]
[TD]typedef[/TD]
[/TR]
[TR]
[TD]extern[/TD]
[TD]return[/TD]
[TD]union[/TD]
[/TR]
[TR]
[TD]float[/TD]
[TD]short[/TD]
[TD]unsigned[/TD]
[/TR]
[TR]
[TD]for[/TD]
[TD]signed[/TD]
[TD]void[/TD]
[/TR]
[TR]
[TD]goto[/TD]
[TD]sizeof[/TD]
[TD]volatile[/TD]
[/TR]
[TR]
[TD]if[/TD]
[TD]static[/TD]
[TD]while[/TD]
[/TR]
[TR]
[TD]_Bool[/TD]
[TD]_Complex[/TD]
[TD]_Imaginary[/TD]
[/TR]
[TR]
[TD]restrict[/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[/TABLE]







What are constants?
Constants, as the name suggests, are some values that never change. In the previous tutorial, you have seen how a variable can be declared. You can declare a constant by using keyword called 'const' or by directly entering its value in the source code. For example, in this code:
#include 
#include 
/*Author : simplycoder*/
int main(int argc, char *argv[])
{
 const double pi=3.1416;
 float radius=10;
 double area=pi*radius*radius;//Calculate the area.
 printf("Area of the circle having radius %f is %lf\n",radius,area);
 
  system("PAUSE");    
  return 0;
}


Uptil now, we have seen how to carry out the operations by entering the values into the source.
However, this is not feasible all the time and hence we should try to take the input from the user, this will make our program more flexible.
Consider this situation of a post-man.
If I tell postman, "Can you please deliver this parcel at Mr.XYZ's house?"
Postman:"No Sir,I cannot."
Me:"Why not?"
Postman:"I cannot deliver this parcel for two reason, one I don't know the size of your parcel whether it will fit in my bag or not,second is I donot know the address of the destination."
Me: Ok if I can provide both details, then can you deliver it?
Postman: Sure.

So how to tell compiler to read the input from the user?
We can follow some simple steps like these:
1)Allocate the memory for expected input.
2)Pass on the address of the variable.

We shall rewrite our code for finding area of the circle,this time by taking input from the user.
#include 
#include 
/*Author : simplycoder
Task:      Calculate Area of Circle by reading input from user.
*/

int main(int argc, char *argv[])
{
 const double pi=3.1416;
 float radius;
 printf("Enter the radius : \n");
 scanf("%f",&radius);
 double area=pi*radius*radius;//Calculate the area.
 printf("Area of the circle having radius %f is %lf\n",radius,area);
 
   system("PAUSE");    
  return 0;
}

So to read the input, we use an inbuilt function called as scanf.
So the first argument is the expected size of the input and the second is the address of the variable.
At first this might sound wierd but then we are going to learn much more in detail regarding addresses and references in our later tutorials,until then, all you need to know is the format of scanf.


OK, I think this much is enough for tutorial-3, I shall start with storage classes in the next tutorial as it will be another lengthy, theoritical tutorial.
*****************************************************************************************************************
Exercises:
1)Rewrite all the programs from previous tutorials by reading input from keyboard.
2) Write a program(WAP) which will convert km/hr into m/s.
3) WAP to convert given length from inches to a)cms b)feet c)meters.
4)Practice as much as you can.
*****************************************************************************************************************
In tutorial-4 we shall see the concept of storage classes and other related stuff.
Until then, take care.
Ciao.
TheV
TheV • Aug 20, 2011
I am confused....lol...

this c code is going out of my mind...

float c = 0.7;
if(c < 0.7)
    printf("C");
else
    printf("C++");
in my Turbo C++ compiler it is printing C ... I don't know how.. plz any one explain it....!
Reya
Reya • Aug 20, 2011
@TheV: Hey 0.7 is double and c is float.0.7 is rounded to number of bits(0.7 is rounded from 0.69999999)

Ask your query in this thread : https://www.crazyengineers.com/forum...eginners-tutorial-c-language-discussions.html
TheV
TheV • Aug 21, 2011
Thank you reya .. . ! Now I understood .. . .!
simplycoder
simplycoder • Aug 21, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-4

Tutorial-4
Hello everyone again this is simplycoder and welcome to the 4[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn about scope,life of a variable,storage classes.

What is scope of a variable?
A scope is the region of the program, where the variable is accessible.

What is the life time of the variable?
A life time of variable is the duration of program where the variable can retain its value.

What are storage classes?
A storage class is something which sets or defines the scope (visibility) and the life time of the variables or functions.

This is an important concept in C-Programing.
We know how to allocate memory to a variable, now we can ask "how long will the piece of memory will be assigned to particular variable?"
The answer to this is give by storage class of the variable.
Storage class defines the visibility and life time of the variable, this means, a storage class will decide how long a piece of memory will be allocated to a particular variable.

There are four storage classes in C


  • auto
  • static
  • register
  • extern
1)auto: auto stands for automatic-storage class. 'auto' is a keyword.
auto is the default storage class for all the local-variables.(
A variable defined inside a block and is only visable from within the block is called as local-variable.)
  {
   int x;
   auto int y;
   }
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.
Thus the scope and the visibility of the the variables with automatic storage class is within the same block where they are defined.

2)static:static is the default storage class for global variables. The two variables below name and fame both have a static storage class.
static int name;
int fame
{
  printf("%d\n", name);
 }
static variables are visible within all functions in this source file.static storage class is default storage class for all the global variables.

3)register:register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word i.e. 16bits.) and cant have the memory access operator( unary '&') applied to it (as it does not have a memory location).
Syntax:

[FONT=arial][SIZE=2]
register int p;[/SIZE][/FONT][FONT=arial]
[/FONT]
4)extern: extern storage class is used for global variables when we want the global variables to be visible to all the files.
for example we have two files one.c and two.c
we want to make the global variable from one.c to be visible in two.c, then we can use the extern storage class.
Syntax for using extern storage class is as follows.
extern int hit;
Since this tutorial is going to be for begineers, I will stick more with auto and static storage classes.
For begining C-Programing, its enough to know outline of register and extern storage classes.
We would not use these storage classes as much as static and auto.
If need arises, I shall describe more on these two storage classes in another dedicated tutorial.

***************************************************************************************************************
Exercises:
1)Find the output of the following and why does it print that way?
int c=9;
int main(int argc, char *argv[])
{
    int c=0;
    printf("%d",c);
    system("PAUSE");
    return 0;
}
2)Find the local and global variables in above code?
3)Find the storage-classes of the above variables.
4)Try to code using various storage classes as long as you get bored.
5)Practice.
***************************************************************************************************************
I shall conclude this tutorial here and hopefully we can start with the interesting part of the language.
The Control-Structures.
TheV
TheV • Aug 21, 2011
Thank you ... simplycoder... this tutorial are very goood.

Keep posting.....
simplycoder
simplycoder • Aug 22, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-5

Tutorial-5
Hello everyone again this is simplycoder and welcome to the 5th tutorial of C-programing.
In this tutorial, we are going to learn about the operators which essentially is pre requisite before learning control structures.

What are operators in C?
In our previous tutorials, we have seen how to declare and define the variables,their scope and life time, but then we can ask ourselves a question here:"What exactly I am going to do with these variables and constants? Some how I need to perform some operation on them in order to achieve my goal. So how can I perform operations on it?"
The answer to this question is given by another great concept : The Operators and the Operands.
The variables and contants in our programs are operands.
Basically in C, there are only two types of operators:
  • Unary operators.
  • Binary operators.
By unary operator, it means that it requires only one operand,whereas by binary operator,it requires two operands.(Very simple).
Here is the list of commonly operators.
[TABLE="class: grid"]
[TR]
[TD="colspan: 6"]Operators[/TD]
[/TR]
[TR]
[TD]Sr.no[/TD]
[TD]Syntax[/TD]
[TD]Meaning[/TD]
[TD]Example[/TD]
[TD]Type[/TD]
[TD]Classification[/TD]
[/TR]
[TR]
[TD]1[/TD]
[TD]++[/TD]
[TD]Increment[/TD]
[TD]x++;++x;[/TD]
[TD]Unary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]2[/TD]
[TD]--[/TD]
[TD]Decrement[/TD]
[TD]x--; --x;[/TD]
[TD]Unary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]3[/TD]
[TD]+[/TD]
[TD]Positive[/TD]
[TD]+x;[/TD]
[TD]Unary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]4[/TD]
[TD]-[/TD]
[TD]Negative[/TD]
[TD]-x;[/TD]
[TD]Unary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]5[/TD]
[TD]=[/TD]
[TD]Basic Assignment[/TD]
[TD]x=y[/TD]
[TD]Binary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]6[/TD]
[TD]+[/TD]
[TD]Addition[/TD]
[TD]x+y[/TD]
[TD]Binary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]7[/TD]
[TD]-[/TD]
[TD]Subtraction[/TD]
[TD]x-y[/TD]
[TD]Binary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]8[/TD]
[TD]*[/TD]
[TD]Multiplication[/TD]
[TD]x*y[/TD]
[TD]Binary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]9[/TD]
[TD]/[/TD]
[TD]Divide(Quotient)[/TD]
[TD]x/y[/TD]
[TD]Binary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD]10[/TD]
[TD]%[/TD]
[TD]Modulo(Remainder)[/TD]
[TD]x%y[/TD]
[TD]Binary[/TD]
[TD]Arithmetic[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]11[/TD]
[TD]==[/TD]
[TD]Equal to[/TD]
[TD]x==y[/TD]
[TD]Binary[/TD]
[TD]Relational[/TD]
[/TR]
[TR]
[TD]12[/TD]
[TD]!=[/TD]
[TD]Not equal to[/TD]
[TD]x!=y[/TD]
[TD]Binary[/TD]
[TD]Relational[/TD]
[/TR]
[TR]
[TD]13[/TD]
[TD]>[/TD]
[TD]Greater than[/TD]
[TD]x>y[/TD]
[TD]Binary[/TD]
[TD]Relational[/TD]
[/TR]
[TR]
[TD]14[/TD]
[TD]<[/TD]
[TD]Less than[/TD]
[TD]x [TD]Binary[/TD]
[TD]Relational[/TD]
[/TR]
[TR]
[TD]15[/TD]
[TD]>=[/TD]
[TD]Greater than or equal to[/TD]
[TD]x>=y[/TD]
[TD]Binary[/TD]
[TD]Relational[/TD]
[/TR]
[TR]
[TD]16[/TD]
[TD]<=[/TD]
[TD]Less than or equal to[/TD]
[TD]x<=y[/TD]
[TD]Binary[/TD]
[TD]Relational[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]17[/TD]
[TD]![/TD]
[TD]Logical negation[/TD]
[TD]!x;[/TD]
[TD]Unary[/TD]
[TD]Logical[/TD]
[/TR]
[TR]
[TD]18[/TD]
[TD]&&[/TD]
[TD]Logical AND[/TD]
[TD]x&&y[/TD]
[TD]Binary[/TD]
[TD]Logical[/TD]
[/TR]
[TR]
[TD]19[/TD]
[TD]||[/TD]
[TD]Logical OR[/TD]
[TD]x||y[/TD]
[TD]Binary[/TD]
[TD]Logical[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]20[/TD]
[TD]~[/TD]
[TD]Bitwise NOT[/TD]
[TD]~x;[/TD]
[TD]Unary[/TD]
[TD]Bitwise[/TD]
[/TR]
[TR]
[TD]21[/TD]
[TD]&[/TD]
[TD]Bitwise AND[/TD]
[TD]x&y[/TD]
[TD]Binary[/TD]
[TD]Bitwise[/TD]
[/TR]
[TR]
[TD]22[/TD]
[TD]|[/TD]
[TD]Bitwise OR[/TD]
[TD]x|y[/TD]
[TD]Binary[/TD]
[TD]Bitwise[/TD]
[/TR]
[TR]
[TD]23[/TD]
[TD]^[/TD]
[TD]Bitwise XOR[/TD]
[TD]x^y[/TD]
[TD]Binary[/TD]
[TD]Bitwise[/TD]
[/TR]
[TR]
[TD]24[/TD]
[TD]<<[/TD]
[TD]Bitwise Left Shift[/TD]
[TD]x< [TD]Binary[/TD]
[TD]Bitwise[/TD]
[/TR]
[TR]
[TD]25[/TD]
[TD]>>[/TD]
[TD]Bitwise Right Shift[/TD]
[TD]x>>y[/TD]
[TD]Binary[/TD]
[TD]Bitwise[/TD]
[/TR]
[/TABLE]




There are more operators in C-Language, but we shall take a look at them in the comming tutorials.

Arithmetic operators are self explanatory.
We shall also see logical and relational operators in comming tutorials as they are easy to understand and wont take much of time.
Generally teachers avoid or give less time for bit operators.

So I think I shall give preference to write about operators.
Bit-wise Operators:
In computer science, everything boils down to binary.
In binary system, all we have is 0's and 1's.(we call them as bits).

Since the operators above are used to manipulate the bits, we call them as bitwise operators.
These are slightly difficult to understand if you are unaware of the binary system.

A binary system is a part of number system which uses only two values. 0 and 1.
1 is called as logical-high and 0 as logical-low.
In digital electronics, binary system is generally treated as a switch where 0 is OFF and 1 is ON.
In boolean algebra,0 is treated as false and 1 as true.

So this much is enough for basic understanding of binary systems.

Now we shall see how to convert a decimal number into binary.
The technique we use is called as successive division.
What we do in this technique is divide the number successively by 2 and note down the remainders.
Once we get the quotient as 0, we stop and reverse the order of remainders.
This is the binary representation of the decimal number.
for example lets take number (19)[SUB]10[/SUB] and convert it to binary.
************
Step 1:
Divide 19 by 2.
Quotient : 9
Remainder : 1
************
Step 2:
Divide 9 by 2.
Quotient : 4
Remainder : 1
************
Step 3:
Divide 4 by 2.
Quotient : 2
Remainder : 0
************
Step 4:
Divide 2 by 2.
Quotient : 1
Remainder : 0
************
Step 5:
Divide 1 by 2.
Quotient : 0
Remainder : 1
************
Now we reverse the order of the remainders. i.e, we write the remainders from last step to first step.
so the binary representation of (19)[SUB]10[/SUB] is (10011)[SUB]2[/SUB].

You can try for as many numbers you like.

Now we shall see how to convert a binary number to a decimal number:
Let us try to convert the number from (10011)[SUB]2[/SUB] to decimal.
Binary number is something which is always expressed in powers of 2.
the right extreme of the number has place value 0(LSB:Least Significant Bit) and is incremented by 1 everytime as we proceed from right to left,with rightmost bit having highest place value(MSB : Most Significant Bit).

We get the decimal number by adding all the bits,multiplied by 2[SUP]place value

[/SUP]So the place value of 1 in 10011 is 0.

so we start like this: 1*2[SUP]4[/SUP]+0*2[SUP]3[/SUP]+0*2[SUP]2[/SUP]+1*2[SUP]1[/SUP]+1*2[SUP]0
[/SUP]=1*16 + 0*8 + 0*4 + 2*1 + 1*1
=16+2+1
=19
Hence we have learnt a method to convert a number to binary and from binary back to decimal.
Be thorough in this part, we are going to use it in our next tutorial, where we would actually learn how to manipulate bits.
Its very interesting and I shall also try to explain, in computer science, why we would always prefer bit-operations on numbers where the numbers are large.
*******************************************************************************************
Exercises:
1)Convert as many numbers as you can from decimal to binary.
2)Repeat Q1 for binary to decimal.
3)Findout the relation between number of bits and the maximum number that can be represented by those bits.
4)How many bits will I require to represent (200000)[SUB]10[/SUB] in binary?
5)Maximum value that can be represented in each data-type we have studied in previous tutorial (V.Important).
*******************************************************************************************
I will conclude this tutorial here,We shall see how to manipulate the bits and to carry simple operations using bitwise operators in our next tutorial.
Until then take care and practice.
Ciao.
simplycoder
simplycoder • Aug 23, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-6

Hello everyone again this is simplycoder and welcome to the 6[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the bitwise operators NOT,AND,OR.

In the previous tutorial, we have seen how to convert a decimal number to binary and vice-versa.
In this tutorial, we are going to learn how to operate on the bits using bit-wise operators.

There is one more thing about binary system, which we havent seen in our previous tutorial and that is how to represent negative numbers in binary form.
The answer to this is something called as 2's complement.
Previously there was a method called as 1's complement,but I leave this exercise to readers as to why 1's complement was disapproved.

Since this is a C-programing course, I think I should limit myself only to the introduction of 2's complement and how to calculate 2's complement of any number.

We shall directly start with an example.
let us assume that we are dealing with signed numbers. lets take (9)[SUB]10[/SUB] as our example and limit ourself till 8-bit representation.
In signed numbers, the rightmost bit is used to indicate the sign of the number. (0 for positive number and 1 for negative)
(9)[SUB]10[/SUB] in binary is written as 0000 1001. (See the rightmost bit is 0, hence the number is positive.)

Step 1:
To take one's complement, just invert all the bits.
so 1's complement of (9)[SUB]10[/SUB] = 1111 0110.
Since this is signed number and the rightmost bit 1, inorder to find the decimal representation, all we have to do is multiply the rightmost bit by its place value taking the sign into consideration.
so 1*(-2[SUP]7[/SUP])+1*2[SUP]6[/SUP]+1*2[SUP]5[/SUP]+1*2[SUP]4[/SUP]+0*2[SUP]3[/SUP]+1*2[SUP]2[/SUP]+1*2[SUP]1[/SUP]+0*2[SUP]0[/SUP]
= -128+64+32+16+4+2
= -10

Step 2:
Now add one to this number to get 2's complement: -10+1=-9
This is how we represent the negative numbers in binary.

Before we can actually write programs, let us first know the advantages and disadvantages of bit-wise operation
Advantages:
Bit-wise operations are faster than the normal operations(By this, I mean they are really very very fast).
It gives us an insight on how simple things get computed in a computer. eg. Addition of two numbers takes place using bit-wise operators and not by '+' in lower computing or assembly. Similar fashion is in C. The '+' operator is broken down finally to its bit-operators while the things are computed. In short a C-compiler, doesnot understand anything except for bit-wise operators and binary numbers.

Disadvantages: They seem to be complicated,and a programmer must spend some time on bit-operators before he can master them.

Applications:The main areas of applications are in embedded systems and in microprocessor-microcontrollers, typically when either the input is large or space is small.

All the bitwise operators work using their respective truth-tables.

What is a truth-table?
A truth table is a form of mathematical table which is generally related to boolean alegra.
We shall come to know about it more when we discuss it.

Before going through our first bit-operator:: Bit-wise NOT, I encourage readers to read more on 1's and 2's complements and how to represent negative numbers in binary.


1)Bit-wise NOT :: ~
[TABLE="class: grid, width: 25%"]
[TR]
[TD]Truth-Table of Bit-wise NOT : : ~[/TD]
[/TR]
[TR]
[TD]Input[/TD]
[TD]Output[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]1[/TD]
[/TR]
[TR]
[TD]1[/TD]
[TD]0[/TD]
[/TR]
[/TABLE]


The bit-wise NOT is used when we have to reverse the bits of the number.
Interestingly, we have ~x== (-x-1).
Lets take the following program.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
  int x=9;
  int y=~x;
  printf("Original number %d on bit negation is %d\n\n\n",x,y);

   system("PAUSE");    
   return 0;
}
The above explaination of 1's complement of 9 is enough to understand the above code.

2)Bit-wise AND :: &
Our second bit-wise operator is &.
Truth-table for bitwise-AND is
[TABLE="class: grid, width: 20%"]
[TR]
[TD="colspan: 3"]Truth-Table for bit-wise AND.
[/TD]
[/TR]
[TR]
[TD="colspan: 2"]Inputs
[/TD]
[TD]Output
[/TD]
[/TR]
[TR]
[TD]A
[/TD]
[TD]B
[/TD]
[TD]Z
[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]0
[/TD]
[TD]0
[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]1
[/TD]
[TD]0
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]0
[/TD]
[TD]0
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]1
[/TD]
[TD]1
[/TD]
[/TR]
[/TABLE]



In short whenever all the inputs are 1,the output is 1, else its 0 (Simple).
Let us write a program for the same and then discuss the output.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=2;
   int b=3;
   printf("a = %d b = %d a&b = %d\n\n\n",a,b,(a&b));

   system("PAUSE");    
   return 0;
}

OK. Now let us see how does the following program executes.
a = 0000 0010
b = 0000 0011

Now compare the bits on their equal place values, if both of them are 1, then the result is 1 else its 0.
so we get
0000 0010
& 0000 0011
-------------
0000 0010 =(2)[SUB]10[/SUB]

Now we shall see another bitwise operator, its called as Bitwise-OR
3)Bitwise-OR :: |

[TABLE="width: 25%"]
[TR]
[TD="colspan: 3"]Truth-Table for bit-wise AND.
[/TD]
[/TR]
[TR]
[TD="colspan: 2"]Inputs
[/TD]
[TD]Output
[/TD]
[/TR]
[TR]
[TD]A
[/TD]
[TD]B
[/TD]
[TD]Z
[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]0
[/TD]
[TD]0
[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]1
[/TD]
[TD]1
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]0
[/TD]
[TD]1
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]1
[/TD]
[TD]1
[/TD]
[/TR]
[/TABLE]



This truth-table can be interpreted as: If anyone of the input is 1,the resulting bit is 1 else 0.


Let us write a program for the same and then discuss the output.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=2;
   int b=3;
   printf("a = %d b = %d a|b = %d\n\n\n",a,b,(a|b));

   system("PAUSE");    
   return 0;
}

OK. Now let us see how does the following program executes.
a = 0000 0010
b = 0000 0011

Now compare the bits on their equal place values, if both of them are 1, then the result is 1 else its 0.
so we get
0000 0010
| 0000 0011
-------------
0000 0011 =(3)[SUB]10[/SUB]

Ok then since this tutorial is going on to be lengthy, I shall wrap up the first part of bit operators here now.
********************************************************************
Exercises:
Findout the maximum number that can be stored in your system using only the bit operators.
Argue if only ones complement is enough to represent negative numbers.Reason it out.
Play around with the new operators learnt. Ofcourse till you get bored of them.
********************************************************************
In the next tutorial, I shall post on the remaining three bit operators and hopefully we shall be able to carryout our basic arithmetic operations using only bit operator.
Kindly give your feedbacks on the tutorial through a PM or by a visitor message.
Until the next time, take care
Ciao.
simplycoder
simplycoder • Aug 24, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-7

Tutorial-7


Hello everyone again this is simplycoder and welcome to the 7[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the bitwise operators Exclusive-OR, Right-Shift,Left-Shift.

In the last tutorial, we had basic information on bit-wise operators.
Now in this tutorial, we are going to learn about remaining 3 bit-wise operators listed above.

We shall start with our next biwise operator

4)Exclusive-OR(XOR):: ^
This too follows truth table as in AND and OR.
The truth table is given as follows.
[TABLE="class: grid, width: 20%"]
[TR]
[TD="colspan: 3"]Truth-Table for XOR
[/TD]
[/TR]
[TR]
[TD="colspan: 2"]Input
[/TD]
[TD]Output
[/TD]
[/TR]
[TR]
[TD]A
[/TD]
[TD]B
[/TD]
[TD]Z
[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]0
[/TD]
[TD]0
[/TD]
[/TR]
[TR]
[TD]0
[/TD]
[TD]1
[/TD]
[TD]1
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]0
[/TD]
[TD]1
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]1
[/TD]
[TD]0
[/TD]
[/TR]
[/TABLE]

Truth-Table for X-OR follows the same way as that of OR.
However, when all inputs are 1, the resulting output is 0
.
Lets now write a program and discuss how it works.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
  int a=2;
  int b=3;
  printf("a = %d b = %d a^b = %d\n\n\n",a,b,(a^b));

   system("PAUSE");    
   return 0;
}
a = 2 and in binary, 2 is 0000 0010.
b = 3 and in binary, 3 is 0000 0011.

Now compare the bits on their equal place values,
  • if both of them are 1, then the result is 0
  • if both of them are 0 then the result is 0,else its 0.
  • else result is 1.
so we get
0000 0010
^ 0000 0011
-------------
0000 0001 =(1)[SUB]10[/SUB]

Now we are going to see a bit operator, this is called as Left-Shift operator.

5)Left shift operator:: <<
This operator has no truth-table.
All it does is, it shifts the bits to left, by padding zeroes on right.
Syntax : <<.
Lets write a program and check how it works.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=2;
   int b=1;
   printf("a = %d b = %d a<a=2.
therefore in binary : a = 0000 0010
b= 1.(We need not know the bit details about this number in shifting.).
We can say that in the above code, a is left-shifted by b bits.
so 2 is left-shifted by 1 bit.
After shifting, a = 0000 0100(note the position of 1 in both the cases.)
so in decimal format, a=4.

In similar cases, we have the right shift operator.

6)The right-shift operator :: >>
This operator has no truth-table.
All it does is, it shifts the bits to right, by padding zeroes on left.
Syntax : >>.
Lets write a program and check how it works.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=2;
   int b=1;
   printf("a = %d b = %d a>>b = %d\n\n\n",a,b,(a>>b));

   system("PAUSE");    
   return 0;
}

a=2.
therefore in binary : a = 0000 0010
b= 1.(We need not know the bit details about this number in shifting.).
We can say that in the above code, a is right-shifted by b bits.
so 2 is right-shifted by 1 bit.
After shifting, a = 0000 0001(note the position of 1 in both the cases.)
so in decimal format, a=1.

Ok I think this much is enough for the basic introduction to Bit-Operators and Binary numbers.
I shall conclude this tutorial here.
********************************************************************************
Execrises:
1) Assume a=5 and b=10. Swap them by using a bitwise operator and without use of third variable.
2) Explain in laymans terms, what does right-shift and left-shift operators do?
3) WAP to find whether the pattern (111)[SUB]2[/SUB] exists in all numbers that can be represented by 4 bits.
4)Practice.
********************************************************************************
So in this tutorial, we have learnt about bit-operators.
In the next tutorial, we shall see relational operators.
I tried to make this tutorial as clear as possible and hopefully you to have liked it.
Your feedback is important so kindly let me know about your views.
Until the next time, take care.
Ciao.
ukanth19
ukanth19 • Aug 24, 2011
Very useful....keep on going 😀
durga ch
durga ch • Aug 24, 2011
😀,

Simplycoder, are you alright if this thread is moved to tutorials section and made a 'sticky'?
simplycoder
simplycoder • Aug 25, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-8

Tutorial-8
Hello everyone again this is simplycoder and welcome to the 8[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the relational operators.

Relational operators are also called as Comparison Operators.
There are six types of relational operators in C. Now we shall see them one by one.

1)Equal to :: ==
This operator check whether both the operands are equal or not.
It will return true if the the operators are equal else it shall return false.
In C all the conditions which are true, are returned with 1 and all the conditions which are false are returned by 0

Lets check a program on the same.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=5;
   int b=6;
   int c=5;
   
   printf("a == b , %d\n\n\n",a==b);
   printf("b == c , %d\n\n\n",b==c);
   printf("c == a , %d\n\n\n",c==a);
   
   system("PAUSE");    
   return 0;
}
This program, basically checks if the operators are equal.
the first statement is a==b this is false, hence the output will be 0.
the second statement is b==c this is also false, hence the output will be 0 in this case as well.
in the third case, c==a this is true and hence the output will be 1.

Now lets take a look at another relational operator called as not equal to.

2) Not Equal to :: !=
This operator works similar to that of '==' operator, however it returns true (1) if they are not equal and false (0) if they are equal.
We shall write a program here.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=5;
   int b=6;
   int c=5;
   
   printf("a != b , %d\n\n\n",a!=b);
   printf("b != c , %d\n\n\n",b!=c);
   printf("c != a , %d\n\n\n",c!=a);
   
   system("PAUSE");    
   return 0;
}
The code is now self explanatory and I leave the output as an exercise to the readers.

3) Greater than :: >
The above operator is which test whether the first operator is greater than second.
I will return true (1) if the first operator is greater than second operator, else it will return false.
A sample code for this will be
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=5;
   int b=6;
   int c=5;
   
   printf("a > b , %d\n\n\n",a>b);
   printf("b > c , %d\n\n\n",b>c);
   printf("c > a , %d\n\n\n",c>a);
   
   system("PAUSE");    
   return 0;
}
The working is self explanatory.

4) Less than operator :: <
This is similar to Greater than operator, only difference is that it will return true if the first operand is less than second else it will return false.
This is a good exercise for readers to write their own code or modify the above code to know more on this operator.

5)Greater than or Equal to :: >=
This operator will check for the condition where the first operator is either equal or greater than the first operator.
It will return true if the above condition holds, else shall return false.
Lets write a code for this.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a=5;
   int b=6;
   int c=5;
   
   printf("a >= b , %d\n\n\n",a>=b);
   printf("b >= c , %d\n\n\n",b>=c);
   printf("c >= a , %d\n\n\n",c>=a);
   
   system("PAUSE");    
   return 0;
}
In this case, the first statement will test for a to be greater than or equal to b, but this is false, hence it will return 0.
In the second statement, will test for b to be greater than ore equal to c, this is true as b is greater than a.
In the third statement, it will test c to be greater than or equal to a, this is also true as c is equal to a.

6) Less than or equal to :: <=
This operator is similar to above greater than or equal to operator.
However it will return true if the first operand is less than or equal to the second operator.
Working is self explanatory.

This is it about relational operators.
We shall see further use of these operators when we shall use control structures.
I shall conculde my tutorial now.
***********************************************************************
Exercise:
1)Play with relational operators.
2)Practice.
***********************************************************************
In the next tutorial, I shall explain the use of logical operators.
Until the next time, take care.
Ciao.
simplycoder
simplycoder • Aug 26, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-9

Tutorial-9

Hello everyone again this is simplycoder and welcome to the 9[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the logical operators.
There are only three logical operators in C.

1) Logical NOT :: !
This operator is called as Logical NOT as it will return an opposite value.
This means, it will return false if the statement is true and it will return true is the statement is false.
Above statement is equivalent to :: It will return 0 if value is not 0 and it will return 1 if value is 0.(Simple).
Please donot get confused with the bit-wise NOT, this operator has nothing to do with bits.

Let us write a program to understand things more clearly.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a = 20;
   int b = 0;
   printf("%d\t%d\n\n\n\n",!a,!b);
   
   system("PAUSE");    
   return 0;
}
Here a=20, this means that a not equal to 0, so !a will return 0.
In the next statement, b = 0, this means that b is equal to 0 and hence !b will return 1.

2) Logical AND :: &&
This operator test whether all conditions hold true.
It can be read as: Logical-AND will return true(1) if and only if both the conditions are true, else will return false(0).

Things will be clear now when we write our next program.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a = 20;
   int b = 0;
   printf("%d\n\n\n\n",((a==20)&&(b==0)));
   printf("%d\n\n\n\n",((a==21)&&(b==0)));
   system("PAUSE");    
   return 0;
}
The first statement is ((a==20)&&(b==0)), this can be split in two sub statements as:
1...."a is equal to 20"..... TRUE.
2...."b is equal to 0".....TRUE.

Now check the stament which describes Logical AND.
Since both the statements are true, it will return true(1).

Check for the second statement here, in this case, a equal to 21 is false, hence no matter what the second statement is, the overall statement is going to return false(0).
This is called as SHORT-CIRCUIT behaviour of the Logical AND.


3)Logical OR :: ||
This logical operator will return true if any one of the statement is true. If all statements are false, then and then only, it will return false.
To make things clear, we shall write a small program now,
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a = 20;
   int b = 0;
   printf("%d\n\n\n\n",((a==20)||(b==0)));
   printf("%d\n\n\n\n",((a==20)||(b==1)));
   printf("%d\n\n\n\n",((a==21)||(b==1)));
   system("PAUSE");    
   return 0;
}

In the first stament, a equal to 20, so now the overall statment will return true(1).(This is called as the SHORT-CIRCUIT nature of the Logical OR).
In the second statment, a equal to 20 true the overall statment will return true, it wouldnt even evaluate the other statements, in this case the second part of the statement is false, but by defination, entire statment will return true as it encounterd the first statement to be true(1).
In the third statment, a equal to 21 is false, so it will proceed to check the next statement, b equal to 1 this is also false, hence the over all statment will be false(0).

There is not much in logical operators on their own, however, a basic understanding is required as we will use them on regular basis when we go for control structures.
I shall conclude my tutorial here.
********************************************************************************
Exercises:
1)Play with Logical operators,develop strong understanding.
2)Practice.
********************************************************************************
In the next tutorial we shall finally begin with control structures, where we will allow the computer to make decisions on our behalf..
This is really important concept and very interesting indeed.
Until the next time, take care.
Ciao.
simplycoder
simplycoder • Aug 27, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-10

Tutorial-10
Hello everyone again this is simplycoder and welcome to the 10[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the Control Structures.
This tutorial can be treated as part-1 as here we shall only see the decision making control structures.

Until now, we have seen programs which have linear execution of the statements, but then its not enough in day to day life programing.
We might want to code a program which takes decisions, which can repeat set of instructions, which can bifurcate from the code and so on...
For this purpose C offers us set of keywords which allows us to tell the compiler what we want from the code and how to behave.
These set of keywords are called as Control-Structures.

OK, enough of introduction here, now we shall see the first control structure:

1) if :- This is the decision maker in C. It can interpreted in similar way as it is done in English.
Basically what it does is checks whether the code within the if(...) is true,if its true, then it executes the statement below it, if it is false, then it won't execute. Very simple.
Syntax
if (conditional)
    {
            block of statements executed if conditional is true;
    }
....
rest of the code.
    
consider this code.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a = 20;
   int b = 0;
   
   if(a==20)
   printf("Value of a = 20\n");
   
   if(a==21)
   printf("Value of a = 21\n");
  
  
   system("PAUSE");    
   return 0;
}

Check the first if statement, the condition holds true and hence the statement below it will be executed.
Now take a look at the second if statement, the second if statement is false and hence the condition below it wouldnot be executed.

2)if .... else
This is similar to if , here the program has to execute the decision if the statement is true or it will execute the statement below else.
This will be clear once we write a program.
Syntax
    if (conditional)
    {
            block of statements executed if conditional is true;
    }
    else
   {
            block of statements if condition false;
    }
consider the following program.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   int a = 20;
   int b = 0;
   
   if(a==20)
   printf("Value of a = 20\n");
   else 
   printf("Value of a != 20\n");
   
   if(a==21)
   printf("Value of a = 21\n");
   else 
   printf("Value of a != 21\n");
  
   system("PAUSE");    
   return 0;
}

The first if statement if(a==20) holds true, hence it executes the statement below if and skips the statement below else.
However the second if statement if(a==21) is false hence it skips the statement below if and executes the statement below else.

3) switch(expression) :
The switch and case statements help control complex conditional and branching operations.
The switch statement transfers control to a statement within its body.
They can be treated as a better option for conventional if or if...else

Syntax:
switch (expression)
  {
     case item-number:
                               statements;
     break;
     case item-number:
                                statements;
     break;
     case item-number:
                                statements;
     break;
     default: 
                                statement;
    break;
  }
the item-numbers should be compatible with an integer or a character, however cannot be a variable.
The execution is simple: Consider this statement,switch (expression), the term expression here denotes the case item-number.
If the expression is a number A, then the case item-number equal to A will be executed(Simple).

Now at first look, this will look a bit complicated, but need not worry, things will get clear as we write our simple program.
#include 
#include 
/*Author : simplycoder*/
 /*Task :  To find if the number is ODD or EVEN*/
int main(int argc, char *argv[])
{
 
 int a;
 printf("Enter the value of number :: ");
 scanf("%d",&a);
 int check_for_even=2;
 switch(a%check_for_even)
  {
     case 0: printf("\nEVEN\n");
     break;
  
     case 1:printf("\nODD\n"); 
     break;
     
     default:printf("\nNEITHER ODD NOR EVEN\n");
     break;                       
  }  
 
  
   system("PAUSE");    
   return 0;
}

Assume that in the above program, the user entered 10.
10%2==0 hence the expression will contain 0, the program will execute the case which has case-number 0.
Similarly,if the number entered is 11, then 11%2==1, the program will execute the case which has cas-number 1.
The case number is very important as the program will match the expression with the case number.
The default here is redundant as any number is either odd or even, so default here will never be executed.
The general understanding of default is that it will execute if none of the cases match the expression.

This is it for this tutorial, we now know how about the decision making control-structures in C.
Please understand any statements included in '{}', then the compiler will treat all of them as one combined statement.
I shall conclude my tutorial here.
*****************************************************************************
Exercises:
1)WAP to find whether the number is ODD or EVEN using if,if...else statements.
2)WAP to find if the enterd character was 'a' using switch, if, if...else statement.
3)WAP to print the maximum and minimum number of any three numbers.
4)WAP to print the 4[SUP]th[/SUP] bit of the decimal 10 is 1 or 0.
5)Practice a lot, now we are entering the heart of programing, this is valid for any language.
A good grasp now, will help your entire programing life.
*****************************************************************************
In the next tutorial, we shall see the looping-control-structures.
Until the next time,take care
Caio.
simplycoder
simplycoder • Aug 28, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-11

Hello everyone again this is simplycoder and welcome to the 11[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the remaining Control Structures.
This tutorial can be treated as part-2 as here we shall see the iterative control structures or looping control strucutres.

1)for

Syntax: for(initialization ; condition of termination ; increment or decrement)
Donot forget those semi-colons :: ;

for loop consists of three parts
  • initialization.
  • condition of termination.
  • increment or decrement.
Initialization:This is the first part in writing the for-loop structure.Here the loop is initialized to a desired value, the for-loop begins its execution from this value.

Condition of termination: This is the condition of termination, in most of the times, terminating condition is a relational operator. The for loop exits or terminates once the condition returns a false value.

increment or decrement: Based on the need of for loop, increment or decrement is applied.This puts a limit on number of interations and helps the loop to terminate the loop after those many number of iterations.

Basically, a for loop will repeat the same thing for the specified number of iterations. (and hence it is called as LOOP).
Things will be simpler when we write our first program using for loop.
Take a look at following code:
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
 int i;
 
 for(i=0;i<5;i++)
 printf("Hello\n");
 
  
   system("PAUSE");    
   return 0;
}

Here the variable i has been initialized to 0(i=0), the terminating condition is when x<5 returns false, and a post-increment operator is applied for increment in value of i.
so what this loop does?
The answer is, it prints Hello.
for how many iterations does it print hello?
This is what we are going to calculate now.Let us execute the program by hand.

Interation 1: i=0, is i less than 5(true) execute statement below for loop. (Print hello), increment i(now the value of i is 1)
Interation 2: i=1, is i less than 5(true) execute statement below for loop. (Print hello), increment i(now the value of i is 2)
Interation 3: i=2, is i less than 5(true) execute statement below for loop. (Print hello), increment i(now the value of i is 3)
Interation 4: i=3, is i less than 5(true) execute statement below for loop. (Print hello), increment i(now the value of i is 4)
Interation 5: i=4, is i less than 5(true) execute statement below for loop. (Print hello), increment i(now the value of i is 5)
Interation 6: i=5, is i less than 5(false) donot execute statement below for loop, terminate from the loop.

Hence from the above analysis,the program will print Hello 5 times and when i<5 will return false, it will terminate.

At first look things look difficult, so don't worry, later on eventually you will get hang of it, once we write programs using loops and other control structures.

2)while:
Syntax:
while(condition terminates)

This is called as while loop.
It is simple and can be read as while the loop terminates, do something(this is obvious).

Take a look at the program here,
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
 int i=0;
 
 while(i<5)
 {
    printf("Hello\n");          
    i++;
 }
 
  
   system("PAUSE");    
   return 0;
}

Here i is initialized to 0 (int i=0), the terminating condition is when i<5 will return false.
So let us execute the statements by hand:
Interation 1: i=0, is i less than 5(true) execute statement below while loop. (Print hello) and increment i(now the value of i is 1).
Interation 2: i=1, is i less than 5(true) execute statement below while loop. (Print hello) and increment i(now the value of i is 2).
Interation 3: i=2, is i less than 5(true) execute statement below while loop. (Print hello) and increment i(now the value of i is 3).
Interation 4: i=3, is i less than 5(true) execute statement below while loop. (Print hello) and increment i(now the value of i is 4).
Interation 5: i=4, is i less than 5(true) execute statement below while loop. (Print hello) and increment i(now the value of i is 5).
Interation 6: i=5, is i less than 5(false) donot execute statement below while loop, terminate the loop.

Here it can be seen that '{}' are used to tell compiler, to interpret printf("Hello\n") and i++ as single block of statement.

3) do... while(condition);
Syntax:
 do
{
//code here
}
while(condition is true);
Donot forget the semi-colon after while.

There is a subtle difference between do..while and while, which will be illustrated later as we see.
Take a look at the code:
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
 int i=0;
 
 do
 {
    printf("Hello\n");          
    i++;
 }
 while(i<5);
  
   system("PAUSE");    
   return 0;
}

the 'do' part will print hello for the first time without taking the terminating condition into consideration.
the while part will put restrictions on do from the second iteration.

Iteration 1:
do :: print Hello,increment i(value of i=1)
while :: i<5(true)
Iteration 2:
do :: print Hello,increment i(value of i=2)
while :: i<5(true)
Iteration 3:
do :: print Hello,increment i(value of i=3)
while :: i<5(true)
Iteration 4:
do :: print Hello,increment i(value of i=4)
while :: i<5(true)
Iteration 5:
do :: print Hello,increment i(value of i=5)
while :: i<5(false), now terminate from the loop.

So as you can see, a do...while loop executes first and then checks for the condition,whereas a while loop will check for the condition first and then execute.
Thus it can be said that a do..while loop will execute atleast one time,whereas while maynot execute at all.

Here I shall conclude with this part of my tutorial.
******************************************************************************
Exercises:
1)WAP to print numbers from 1 to n, where the input is take from user, using for,while and do...while looping structures.
2)Repeat 1 to print numbers from n to 1.
3)WAP to find sum of 1 to n integers where the input is take from user, using for,while and do...while looping structures(DONOT use formula, however verify using the formula).
4)WAP to find the sum of series 1+4+9+16+...n[SUP]2[/SUP] where the input is take from user, using for,while and do...while looping structures(DONOT use formula, however verify using the formula).
5)WAP to find the sum of series 1[SUP]3[/SUP]+2[SUP]3[/SUP]+3[SUP]3[/SUP]+4[SUP]3[/SUP]+...n[SUP]3[/SUP] where the input is take from user, using for,while and do...while looping structures(DONOT use formula, however verify using the formula).
6)WAP to find the factorial of number given by user.
7)WAP to find fibonacci series for n numbers where n is taken from user, refer this article for more information on fibonacci numbers Fibonacci Number -- from Wolfram MathWorld
8)WAP to reverse a number.
9)Program to print A for simple investment equation : A=P(1+r)[SUP]n[/SUP] where all inputs are given by user.
10)Develop a condition where a do...while loop executes atleast once whereas while loop doesn't execute at all. WAP to support your answer.
11)Practice.

These exercises are very important and are there for a purpose, so if you are interested to be a good programer, the start writing the code on your own.
If you are not able to get it correctly,you can do one of the following, ask in Discussions, PM me, VM me, I shall try to help.



******************************************************************************
In the next tutorial, we shall something called as nested loops and how to use decision making control structures along with iterative control structures.
Until the next time, take care.
Caio.
simplycoder
simplycoder • Aug 30, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-12

Hello everyone again this is simplycoder and welcome to the 12[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn further about the remaining Control Structures.
This can be treated as part-3 and considered as extension of previous tutorial.

In this tutorial, we will try to accomodate the decision making control-structures and the iterative control-structures.This is going to be the first tutorial in the series where we are not going to study any new thing, not even syntax, but we are going to apply whatever knowledge we have from our previous tutorial.

This can be marked as a check point, you should be able to grasp the contents of all the previous tutorials before proceeding any further else it will be point less and it maynot make any sense or worse shall confuse you even more.

Enough of introduction, now lets jump to the structure of the snippet.
control structure 1
{
   control structure 2
     {
        control structure 3...
          {
                ..............
           }
      }
}
As you can see control structure 3 is embedded in control structure 2. control structure 2 is embedded in control structure 1, this embedding is called as nesting.
so if a for loop is embedded in another for loop, then it is called as nested-for loop, when if is embedded in another if, its called as nested ifs, and so on.
It is very simple.

Another important concept is how do nested control structures work, this can be explained with example of nested for loops as follows:
for(initialization of variable 1;terminating condition of this for-loop;increment/decrement)
{
  for(initialization of variable 2;terminating condition of this for-loop;increment/decrement)
      { 
              ....
      } 
 }
Now in this case, the first for loop will initialize, test for the condition, if the condition is true, then it will execute the statement below it.(As regular for-loop).
But in above pseudo-code, we find another for loop embedded here, this will also run as regular for loop, so there will be initialization of variable 2,terminating condition, it will execute the statements below it, and now increment the value of variable 2. This will run till the termination condition of second for loop returns false.
Now is the most important part, it is now that the value of variable 1 will increment/decrement.
Same steps will follow, again the variable 2 will be initialized and again the loop will be carried out as before.
This will take place till the termination of first loop takes place.

Saying this, I have tried to explain the most difficult part of the control structures, if you have understood this, then there is no stopping from writing some real cool programs.

I think, now we are in a position to write some cool programs.

The first program that we are going to write is to print the even numbers from 1-50.(I know this is not kind of cool, but then this will surely make you understand the power of for-loop.)

#include 
#include 
/*Author : simplycoder*/
/*Task :    Print even numbers from 0 to 50*/ 
int main(int argc, char *argv[])
{
  //Variables.
  int index=0;//Index for the loop.
  int numbers=51;//Total numbers.
  int divide_by_two=2;// Divisor.
  int zero=0;//Value of zero.
  
  //Logic.
  for(index=zero;indexCheck the logic, its simple, in english if I were to describe the code, I would just say, Go through all the numbers from 0 to 50 and check if the number is divisble by 2, if it is, then print, if it is not divisible by 2, then go to the next number. This is exactly what the above code does.
The for loop will help in browsing the numbers from 0 to 50, and the if statement will help to find whether the number given by for loop is divisible by 2 or not.
So the exact working is summarized as follows:
Step 1: Take a number from for-loop
Step 2: Decide if it is divisible by two
Step 3: If it is divisible by two, then print it.
Step 4: Take the next number from the for-loop.

Now as to understand the power for loop, this loop has minimized writing 51 numbers by hand, so instead of using 51 variables,checking and printing the variables 51 times(considering the numbers are even ), all we have to do is write a single for loop and i
********************************************************************************************
Exercises:
1)WAP to find the odd numbers from range, input is taken from the user.
2)WAP to find the factors of any number, the input is taken from the user.
3)WAP to find the sum of all numbers which are multiples of 3 or 5.(Don't count the common multiples twice).
4)Practice a lot now.
**************************************************************************************

Ok then I shall conclude the tutorial here and in the next tutorial, We shall write more programs which would include printing *-patterns that can be created by control structures, finding GCDs, LCMs, trignometric values of a particular angles in radians, finding exponential value of any number, if time permits then we shall see even how to findout logarithms and other stuff.

I will appreciate feedbacks from you,send a PM or VM anything you like, it will help me in return to make tutorials better.
Until then, take care.
Ciao.
simplycoder
simplycoder • Aug 31, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-13

Tutorial-13
Hello everyone again this is simplycoder and welcome to the 13[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to write few programs, this shall give you good idea on control structures.
In previous tutorial, we have seen how to find out the even numbers.

Now in this tutorial, we shall see how to find factors of a number which is taken from the user.
  • Find and count all the factors of a number,taken from the user.
So we can have the following steps for the program,these steps can be called as algorithms.
  1. Take the number from the number.
  2. Try and divide the number by all numbers in range of 1 to number
  3. If the number is divisible by some number( say index), then count that index as factor of number and print the index.
  4. print the total number of factors.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
  //Variables.

  int number=0;//Taken from the user
  int zero=0;//zero = 0; used to avoid magic numbers.
  int index=0;//index used in for loop.
  int count=0;//Counting number of factors.

  //Take the input

  printf("Enter the number : ");
  scanf("%d",&number);
  printf("\n\n\n\n");

  //Logic

  for(index=1;index<=number;index++)
   {
      if(number%index==zero)
         {
            printf("%d is a factor of the %d \n",index,number);
            count++;
         }
   }
  printf("\n\n\n\nThere are %d factors of %d \n",count,number);
   
   system("PAUSE");    
   return 0;
}
Now lets analyze the above code.
I think its very easy to understand about variables and why they were used(look at the comments),so lets just jump onto the logic of the code.
its a normal for loop, it is initialized at index=1. The for loop will terminate when index>number, until then it will be incremented by 1.
The if statement will test if the number is perfectly divisible by the value of index at that particular moment.
If it is divisible, then print the factor and increment the value of count. Repeat this til the value of index exceeds the value of number(This is the terminating condition.)
In the final statement, just print out the number of factors.

  • Find if a given number is prime number or composite.
We can use the following algorithm:
  1. Take the number from the user.
  2. Divide the number by all numbers(say index) from 2 to n,
  3. If the index divides the number and the value of index is equal to number, then only the number is prime, else it is composite.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
  //Variables.
  int number=0;//Taken from the user
  int zero=0;//zero = 0; used to avoid magic numbers.
  int index=0;//index used in for loop.
  int isPrime=1;//isPrime will test for the number to be prime or not, if the number is prime, then isPrime is 1 else isPrime 0.
  //Take the input
  printf("Enter the number : ");
  scanf("%d",&number);
  printf("\n\n\n\n");
  //Logic
  for(index=2;indexWe have already seen the above code in our previous example.So there is no real piece of code which is new here.
I have assumed the number to be a prime, then test if it is not prime, if it has divisor other than itself, then it is not prime, this is conveyed to program,by changing the value of isPrime.
so finally the number is prime or not will be dependent on th value of isPrime.
This is taken care by the next if...else statments. This is very simple, if the value of isPrime is 1, then it is a prime number, else it is not a prime(composite) number.

Ok this is it for this tutorial,Today we have learnt things about using for-loops with if statments, then we also have used if statements on their own, to check for a condition.
*******************************************************************************************
Exercises:
1)WAP to generate first 100 prime numbers.
2)To generate all the prime numbers from 1 to 1000.
3)Check if a the number is an Armstrong number or not, the input is taken from the user. Refer this for armstrong numbershttps://mathworld.wolfram.comNarcissisticNumber.html
4)Print all the armstrong numbers from 100 to 999.
5)find if the pattern 101 in base 2, exisits in number,number is taken from the user.
6)Print all the numbers which has the 101 in its binary form , the range of numbers is given by the user.
*******************************************************************************************
In the next tutorial, I would proceed further, depending on the response, if you have tried enough to solve the problem, yet struggling with either logic or ideas,
I shall solve them in my next tutorial, else I shall go on for some new problems.

Until the next time,take care.
Ciao.
simplycoder
simplycoder • Sep 1, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-14

Tutorial-14
Hello everyone again this is simplycoder and welcome to the 14[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to write few programs, this can be treated as extension of previous tutorial.
I hope you have completed the exercises in the previous tutorials,this will speed up the learning process.

In previous tutorial, we have seen how to find out prime number and factors of any integer.
In this tutorial, we are going to see how to calculate the GCD of any two numbers.

Being an engineer, over the past four years, my mathematical abilities have developed, I am thankful to Mr.Euclid(I consider him as my tutor.).

Today, we are going to write the code for the same problem, in two different ways.This will also give you a feel that there are many algorithms to solve the same problem, the only difference is the efficiency of the algorithm, you are welcomed to write your own algorithms aswell.


Lets take a look at our first problem statement::


  • Find and Print GCD of any two numbers taken from the user.
Agorithm 1: Sloppy/Inefficient Algorithm.
The algorithm can be thought as follows.
  1. Take the two numbers.
  2. Find the minimum of them, lets call this min.
  3. Try to divide both numbers in the range from min to 2(assume the values in each iteration as index.)
  4. If the both numbers are divisible by index, then that is the GCD,print it.
  5. else print GCD as 1 (or NO GCD.).
Ok now that we know the algorithm,we shall proceed to code.
#include 
#include 
/*Author : simplycoder*/
 
int main(int argc, char *argv[])
{
   //Variables.
   int number_one;
   int number_two;
   int min;//variable to store the minimum value of the two.
   int gcd=1;//This is the gcd.
   int index;//used as iterating variable in for-loop.
   int value_one=1;//Used to initialize the value of 1, avoids magic numbers.
   int value_zero=0;//Used to initialize the value of 1, avoids magic numbers.

   //Take the input from the user.

   printf("Enter the numbers :: ");
   scanf("%d",&number_one);
   scanf("%d",&number_two);

   //Calculate the minimum of two numbers.
   
   min=number_one;//Initialize the value of min to be number_one, next statement check this.
   
   if(number_one>number_two)//Calculate the min.
   {
      min=number_two;
   }

      //Calculate the GCD.
   for(index=min;index>value_one;index--)
    {
      if(((number_one%index)==value_zero)&&((number_two%index)==value_zero))
         {
            gcd=index;
            break;
         }
    }
    
    printf("The GCD of %d and %d is :: %d\n",number_one,number_two,gcd);

   system("PAUSE");    
   return 0;
}

Ok now lets dissect the code.
We know how to find the minimum of two numbers, here we have solved 50% of the main problem(If you don't know, then you need to revise the previous tutorials.).
Now normally, we know the value of the GCD will be either equal to or less than the minimum of the two values, since we want to find the greatest common divisor, its better to start with the greatest value that can be the gcd, in this case its min and slowly decrement by 1 it to a value which is greater than 1. This is what the above for loop does, it is a regular for loop. Once we find a particular number(index) which divides both numbers, we need not carry on the iterations, because this is the greatest number that divides both the numbers i.e.GCD of two numbers.


This is it for this algorithm, now we proceed to check for Euclid's algorithm to find GCD!
Euclid's algorithms is simple as well as efficient (I will write more of the things considering efficiency in next post). Thus he proves the KISS principle!.

Let us see his algorithm.
  1. Take the two numbers.
  2. find the minimum number and the maximum number.
  3. assign value of max%min to a temperory variable(gcd).
  4. assign value of min to max.
  5. assign value of gcd to min.
  6. Repeat steps 3,4,5 until max is divisible by min.
Now we know the algorithm, lets write the code.
#include 
#include 
/*Author : simplycoder*/
/*Task : GCD of two numbers, Euclid's Algorithm*/ 
int main(int argc, char *argv[])
{
  
  int number_one;
  int number_two;
 int value_zero=0;//variable used to denote 0, avoiding magic numbers.
int value_one=1;//Above reason.
  int min;//Minimum of two numbers.
  int max;//Maximum of two numbers.
  int gcd=value_one;//Variable containing value of gcd.
  
  //Take the input from the user.
  printf("Enter the numbers :: ");
  scanf("%d",&number_one);
  scanf("%d",&number_two);
  //Compute the min and max.
  min=number_one;
  max=number_two;
  if(number_one>number_two)
  {
     min=number_two;
     max=number_one;
  }
  
  //Euclid's algorithm.
  while((max%min)!=value_zero)
  {
     gcd=max%min;
     max=min;
     min=gcd;
  }
  printf("The GCD of %d and %d is :: %d\n ",number_one,number_two,gcd);
  
  system("PAUSE");    
  return 0;
}

The heart of program, starts at the while loop.
Assuming that the above code works correctly,this is pretty much self explanatory from the above algorithm steps. If time permits, I shall prove or rather be precise and write why Euclid thought this would work and how it was proved.

Lets talk on the efficiency now, I know this is a advance topic, and we might not want to deal with it at beginner's level, yet to give some computer scientist + mathematician feeling, we shall just print the time required to calculate and print the GCD.

I shall make a test bench to calculate time required by both the algorithms to find the gcd.
This bench will contain random numbers,however, both the programs will get the same numbers in same order.
These all will be very huge numbers, so we shall see what happens.
Take a look at this figure(click on it to see it clearly, all values are not 0, but they are very much insignificant).
GCD_comp
This figure thus is sort of verification, that the euclid's algorithm takes lesser time to compute than normal naive algorithm to find gcd for input of the same size.

This was a heavy stuff, you need not bother which algorithm is efficient and which is not at a beginner stage, I have posted all the above analysis because if you are budding computer-science student, then it is crucial for you to get your mind in correct shape. All of this is not required for beginners stage, yet it wont do any harm knowing it.(If it confuses you, you can skip the analysis part and not the algorithm part).
I shall conclude this tutorial here.
***************************************************************************
Exercise:
1)Find LCM of any two numbers, input taken from user.
2)Practice a lot!!
***************************************************************************
In the next tutorial, we shall see how to compute the sines and the co-sines using there series.
Until the next time, take care.
Ciao.
simplycoder
simplycoder • Sep 2, 2011
Tutorial-15

Hello everyone again this is simplycoder and welcome to the 15[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to write few programs, this can be treated as extension of previous tutorial.
I hope you have completed the exercises in the previous tutorials,this will speed up the learning process.

In this tutorial, we are going to see how to print some amazing patterns using control statements.

The first pattern we try to analyze is something like this.Thisi s called as floyd's triangle.
1
2 3
4 5 6
7 8 9 10
....
In any pattern, we should know how to analyze it and then try to code what we have analyzed.
So enough of talking, lets analyze:

If we observe carefully, we print one number on first line,two numbers on second line,three numbers on third line... and so on.
So we can in general say that, we print n numbers on n[SUP]th[/SUP] line.
Ok this is the first part of analysis.

Now we have to see what to print.
Again observe carefully, we printconsecutive numbers.

So by above two observations, we can say that, print n consecutive numbers such that there are n numbers on n[SUP]th[/SUP] line.
The above can be said as an algorithm to print floyds triangle.

So now what to we need?
We need something which can print the numbers and something which can give us the line break.

So now we are in a position to write the code.
#include 
#include 
#include 
/*Author : simplycoder*/
/*Task : Print the floyd's triangle.*/ 
int main(int argc, char *argv[])
{
 //Variables.
  int index_one;//iterative index for first for-loop.
  int index_two;//iterative index for second for-loop.
  int value_zero=0;//Value 0, used to avoid magic numbers.
  int number_of_lines=0;//User desired number of lines to print floyd's triangle.
  int k=1;//Provides consecutive numbers.
  
  //Take the input from the user.
  printf("Enter the number of lines :: ");
  scanf("%d",&number_of_lines);
  
  //Logic for floyd's triangle.
  for(index_one=value_zero;index_oneLets just jump to the logic. 
Here index_one in the first for loop, will iterate over number of lines(number_of_lines).(This is our first task).
The second loop will provide us with printing consecutive numbers on same line till the value of index_two is equal to index_one[SUP]th [/SUP]line.
In short, it will print n consecutive numbers on n lines.(This is our second task).
Note the position of second-for loop, its the nested for loop.

The printf("\n"), provides us with the necessary line-break.

To verbalize, we can assume that we want to print the first 4 lines of floyd's triangle.

Iteration 1: value of index_one :: 0, 0 less than 4 is true, proceed with next statment.

Iteration 1.1 : value of index_two=0; 0 less than equal to 0 is true, proceed with the loop.Print value of k (k is initialized to 1), at this moment, k=1.So program prints 1 on first line and now increment value of k(value of k now is 2).

Iteration 1.2: value of index_two=1; 1 less than equal to 0 is false, terminate the loop.

Iteration 2: value of index_one :: 1, 0 less than 4 is true, proceed with next statment.

Iteration 2.1 : value of index_two=0; 0 less than equal to 1 is true, proceed with the loop.Print value of k (k is now 2), at this moment, k=2.So program prints 2 on second line and now increment value of k(value of k now is 3).

Iteration 2.2 : value of index_two = 1; 0 less than equal to 1 is true, proceed with the loop.Print value of k (k is now 3), at this moment, k=3.So program prints 3 on second line and now increment value of k(value of k is now 4).

Iteration 2.3: value of index_two = 2; 1 less than equal to 1 is false, terminate the loop.
....
So on it proceed.
I think this clearly explains how to nested for loops work.

Lets see our second problem statment for the tutorial:
Write a code to print the following pattern:

* * * * *
* * * *
* * *
* *
*
Where number of lines printed with '*' is taken from the user.

Ok. Now let us analyze the following pattern.
on 1st line there are n '*'.
on 2nd line there are (n-1)'*'.
on 3rd line there are (n-2)'*'.
....
so on (n-1)th line, there is 1 '*'.


So now we ask ourselves, what do we require?
We require something which can print n'*' on 1st line.
We also require to take line break at required interval.
so we know that we are going to require two for loops.
Ok now we are in a position to write a code for it.
#include 
#include 
#include 
/*Author : simplycoder*/
/*Task : Print the pattern*/ 
int main(int argc, char *argv[])
{
 //Variables.
  int index_one;//iterative index for first for-loop.
  int index_two;//iterative index for second for-loop.
  int value_zero=0;//Value 0, used to avoid magic numbers.
  int number_of_lines=0;//User desired number of lines to print pattern
    
  //Take the input from the user.
  printf("Enter the number of lines :: ");
  scanf("%d",&number_of_lines);
  
  //Logic for triangular pattern.
 for(index_one=number_of_lines;index_one>0;index_one--)
 {
    for(index_two=value_zero;index_twoSee the first for-loop, it starts with the maximum number of lines and then it is decremented by 1.
Take a close look at nested for loop, this starts with zero and then has limit of maximum number of lines, and it is then incremented by 1.
So in order to verbalize it,we assume number_of_lines=5 we can say that::
Iteration 1:
index_one=5
Iteration 1.1
index_two=0,0 is less than 5,print a *.
...
Iteration 1.4
index_two=4,4 is less than 5,print a *.
Iteration 1.5
index_two=4,5 is less than 5 this is false,terminate,donot print a *.
So at end of first iteration, the program has printed 5 *.
Now, execute the statement printf("\n"), this will take teh program to new line.
Now decrement the value of index_one.

See similarly iteration 2 will take place, this time the value of index_one will be 4, so the terminating conditions will be index_two greater than 4, but rest things will be the same, thus printing the desired pattern.

I shall conclude my tutorial here.
**********************************************************************************
Exercises:
1)Code for this pattern
* * * * *
* * * *
* * *
* *
*
2)Code for this pattern:
*
**
***
****
*****
3)Code for this pattern:
4 3 2 1
3 2 1
2 1
1

Due to editorial problems, I have to put images of patterns, click on them.


patterns
paterns-2
patterns-3

Last we have the pascals triangle.
1
1 2 1
1 3 3 1
1 4 6 4 1
**********************************************************************************
I had promised to code trignometric relations,but I think it will be ideal as of now to postpone it, but surely you are going to find it before I conclude this series on beginners series.
Next time we are going to know more about switch statement, I am quiet sure, we are going to build a basic calculator which performs addition,subtraction,multiplication and division.
Until the next time,take care.
Ciao.
simplycoder
simplycoder • Sep 5, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-16

Tutorial-16

Hello everyone again this is simplycoder and welcome to the 16[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to write few programs, this can be treated as extension of previous tutorial.
I hope you have completed the exercises in the previous tutorials,this will speed up the learning process.

In this tutorial, we are going to make a basic calculator in C language using switch control structure.
This is very simple, and readers might find it to be lengthy, however, just take a look at the logic, its very simple.

The problem statement is::
Write a code for calculator which can add,subtract,multiply and divide.

So, we should follow the same old procedure.
Declare the variables,write the logic.
Following can be considered as the algorithm.

  • We take the input from the user.
  • We take the option from the user.
  • Execute the option using switch case.
  • Display the answer.


We plan to take two numbers as input,provide a menu driven code to user, and user has to select option number.
So this is the code for the same.
#include 
#include 
#include 
/*Author : simplycoder*/
/*Task : Calculator for two numbers*/ 
int main(int argc, char *argv[])
{
//Variables:
   float number_one;
   float number_two;
   int option;
   double answer;

   printf("Enter the numbers");
   scanf("%f",&number_one);
   scanf("%f",&number_two);

   printf("Enter the following options : \n");
   printf("1. ADDITION\n");
   printf("2. SUBTRACTION\n");
   printf("3. MULTIPLICATION\n");
   printf("4. DIVISION\n");
   printf("Enter your choice number");

   scanf("%d",&option);

   switch(option)
    {
       case 1: 
               {
                 answer=number_one+number_two;  
               }
        break;
   
   
        case 2: 
               {
                 answer=number_one-number_two;           
               }
        break; 
   
        case 3: 
               {
                 answer=number_one*number_two;
               }
        break;
   
        case 4: 
               {
                     answer=number_one/number_two;
               }
        break;
   
       default :
                 {
                     printf("Please select a valid choice\n"); 
                 }
        break;
    }

    printf("ANSWER :: %lf\n",answer);
    
    system("PAUSE");    
    return 0;
}

Lets jump to the logic.
Here the option is the case number.
So when the user enters the option, the program takes this option and matches with each of the case-numbers.
When a match is found, it executes the correspoding statements of that case-number.

If no match is found, then default statment is executed.

Very simple!

This is it for this tutorial.
************************************************************************************
Execrises:
1)WAP to print the day. Assume 1 to be sunday,2 to be monday and so on...
2)WAP to encrypt a sentence all in upper case. User enters a character, the code would be the corresponding number. User enters '~' character to terminate the input.
eg: HELLO<=>7 5 12 12 15.
3)WAP to encrypt the english to morse code.
4)WAP to decrypt morse code back to english.
************************************************************************************
Ok in the next tutorial.
In the next tutorial, we shall see some thing new and very important :: ARRAYS.
Until the next time,take care.
Ciao.
simplycoder
simplycoder • Sep 6, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-17

Hello everyone again this is simplycoder and welcome to the 17[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn new things, which can be treated as section-II of the tutorial.
From this tutorial onwards, we are going to learn other basic data-types:: The Derived Data Types.

In C we have two main types of data-types
  • Primitive data-types.
  • Derived data-types.
In previous tutorials, we have learnt about the primitive data types.
In day to day programing,we may have to deal with many values.
Say we have to take 5 numbers and print them in the descending order.
We can do this by our previous logic,we can follow this
  • make 5 different variables.
  • assign each variable a value.
  • sort them using if and else
  • print them.
Now this was simple and manageable.
But now let us increase the number of variables to 20.
We still follow our previous algorithm, even though it is manageable, it has certainly become complex.
Now lets take a step forward and increase the variables to 1000.
If we try to write code using above algorithm, its not manageable,its highly complex, its just PAIN...

So the programing language developers thought that there should be something which can manage large numbers of data of similar type in order to make the code less complex and manageable.So they designed a technique by which the programers were able to store large numbers of identical data-types using just one data-type.
We know that all computer scientists are brilliant mathematicians, they corresponded this technique to matrix representation of numbers.In technical terms a matrix is also called as an ARRAY, and that is how the word array was derived.

Since an Array contains group of primitive(basic) datat-types, it is called as derived data-type.

Since this is a C tutorial, I wouldnt go much into the details of Computer Architecture and Memory storage, rather focus on how to use the arrays in our programs.

So in short, any variable which has capacity to store finite number of identical data-types is called as an array.

There are two types of arrays.
  • One-Dimensional Array.
  • Multidimensional Array.
single dimensional array can be visualized as series of block of elements, just like railway-trains, one bogie follows other..
Here is how you can visualize the one dimensional array(The drawing is not quiet good, but then it will surely give you hang of what single dimensional array is.).
Untitleddrawing

There is a visualization of single dimensional array.
You should have asked yourself a question as how can we decide the position of values in an array or on what is the position of a value in that array?
As in railway trains, we have named the bogies, similarly we have indices(index) for the arrays. This is used to find the position of a particular value in array.
In general programing practice,In an n element array,the first index is 0 and the last index is (n-1).

This is about the single dimensional array, now let us see more on multi dimensional array.
Just think multi dimensional array as a matrix. Simplest multidimensional array is a 2-d array.
Just think 2 dimensional array as placing 1-d array below eachother.
Thus you shall get a matrix with rows and columns.
In programing, generally we access a value 2d array as (row,column).
This will give some visual representation like this.
Untitleddrawing(1)
Now last thing for this tutorial.
The syntax used for single dimensional arrays is
data-type of array array_name [size_of_array];
Note that the number of '[]' depends on dimension of array.
The syntax used for 2dimensional arrays is
data-type of array array_name [size_of_rows][size_of_columns];
Can you figure out how to determine syntax for 3 dimensional array and then for n dimensional array?

Enough of introduction to arrays, in the next tutorial, we shall see how to use arrays in our program and how does it help to minimize the efforts.
Until the next time, take care.
Caio.
simplycoder
simplycoder • Sep 9, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-18

Hello everyone again this is simplycoder and welcome to the 18[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on arrays.
In last tutorial, I wrote about advantages of arrays, here, I shall try to demonstrate the same.

Let us start with 1 dimensional array.

We shall know more on how to access elements of arrays and now to operate them by writing programs.
Ok, so now we write our first program on array.

  • WAP to initialize array of integers with 4 numbers and print them.
So all we have to do is initialize the integers and then print out. Simple.
Go to the previous tutorial and visualize your array as series of blocks connected back-to-back.

To initialize the elements in an array, we use the following syntax.
data_type_of_array array_name []={..elements..};
we access the elements of arrays using the indices.

Remember in previous tutorial we have understood that starting index of any array is 0.
So let us write the code.

#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int array[]={1,2,3,4};//Initializes the array.
printf("%d ",array[0]);//Print the element from the array which is at the index 0
printf("%d ",array[1]);
printf("%d ",array[2]);
printf("%d ",array[3]);

    system("PAUSE");    
    return 0;
}

So as expected it will print 1 2 3 4 as the output.
So I think it is clear how to initialize and print the array, so let us try to modify our problem statement a bit.
  • WAP to initialize 10 integers and print them.
We shall initialize the 10 integers as we did for previous program.
To print them, we could use for-loop, in this way, we need not use printf statment 10 times.
So the code would be as follows.

#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int array[]={1,2,3,4,5,6,7,8,9,10};
int array_length=10;
int index=0;
for(index=0;indexrun this code for yourself and see and it is not quiet hard to understand working if you have understood the first example and the control strutures.

Now let us just change the program statment slightly.
  • WAP to initialize the array from 1....100 and then print.
If we want to then we can initialize the array like we did for previous examples, but then 100 elements is just too much.

Again our super-hero the for control structure helps us out.

So effectively, we would run the for loop from 0 to 99 (array index starts with 0,and the 100th element is located at index 99) and fill it up,with a value which is (index+1).
We print out the values using same method as we did for our last example.

#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int array_length=100;
int array[array_length];
int index=0;

for(index=0;indexSo now I think I have proved why arrays are superior to variables when we need many values of same type.
If you are not convinced, I shall demonstrate one more program.
  • WAP to calculate the maxium of 3 numbers.
Let us do this program by using 3 variables.
Let us assume that the three variables are a=30,b=41,c=50.
So now let us jump to the logic
  1. Assume max=a.
  2. Compare max and b and select the maximum, assign correct value to max.
  3. Compare max and c and select the maximum, assign correct value to max.
So this can be the code for the same.

#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int a=30;
int b=41;
int c=50;
int max=0;
//Assume max=a.
   max=a;
   if(b>max)
    max=b;
   if(c>max)
    max=c;

   printf("%d",max);

    system("PAUSE");    
    return 0;
}

If you take a look carefully, we write 2 if statements for 3 variables.
so we write 3 if statements for 4 variables and so on...
so if I want to compare 100 values, I should write 99 if statments.

This is boring,unmanageable and very sloppy coding.

What if we have to compare 1000 values, this is surely not a way to go.
first of all we require 1000 variables, here only we find it to be unmanageable.

So what to do?
The answer is simple.. The Arrays and the control structures!(They are super heroes for us as of now).
Let us rewrite the above program in terms of arrays.

#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int array[]={30,41,50};
int array_length=3;
int max;
int index;
//Logic
max=array[0];
for(index=1;indexmax)
  {
    max=array[index];
  }
}

   printf("%d",max);

    system("PAUSE");    
    return 0;
}

We followed exactly the same logic.
We intialized the array elements in the same order.
We assigned max the value of first element, in previous example, we had assigned max=a.
Then we traverse through the array from the next index and compare the value with max and assign the correct value to max.
Here we have used only one if statment and a for loop.
We can use the above approach for any number of elements.
We need not write if statements again and again.

Ok this is it for this tutorial.
******************************************************************************************
Exercises:
1)WAP to find minimum number from any 4 numbers(intialized).
2)WAP to find the sum of numbers in array.Initialize it with whatever you want.
3)Play and Practice more on the same.
******************************************************************************************

In next tutorial, we would find out how to play more with arrays, how to reverse the input and many more stuff.
Until the next time,Take care
Ciao.
simplycoder
simplycoder • Sep 13, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-19

Hello everyone again this is simplycoder and welcome to the 19[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on arrays.
In last tutorial, I wrote about advantages of arrays, in this tutorial I am going to write more on how to use 1 dimensional arrays.

Let us write a program that will reverse the contents of the array.

  • WAP to reverse the contents of an integer array.
Ok let us assume the array to 1,2,3,4,5,6. And we expect the output to be 6,5,4,3,2,1.
So the array is broken down as follows.
array[0]=1.
array[1]=2.
array[2]=3.
array[3]=4.
array[4]=5.
array[5]=6.
Our expected algorithm should swap the contents stored at respective extremes.
i.e array[0]<->array[5]
array[1]<->array[4]
array[3]<->array[2]
.....
This yeilds to a pattern of
temp=array[index];
array[index]=array[(length_of_array-1)index];
array[(length_of_array-1)index]=temp;
If you observe it properly, the minimum number of swaps we need to do is (number_of_elements)/2.
We know how to swap two numbers, if you dont remember, then brush up the previous tutorials.

So let us proceed to write the program.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int array[]={1,2,3,4,5,6};
int temp;
int index=0;
int len=sizeof(array)/sizeof(int);//length_of_array.
//printf("%d\n",len);

printf("The original array is : ");
for(index=0;indexThis code works exactly as stated above.

Lets now take another problem.
  • WAP to count number of students that obtained each possible marks in the range of 0-100 given 10 students. Assume marks.
Ok so let us assume 10 values for marks for 10 students.
Let the marks be 10,50,30,60,35,40,100,90,75,50.
Let us make an array with maximum marks possible, i.e 100 and treat them as indices.
Everytime we encounter marks of a new student, we would increment the value in that particutlar index by 1.
e.g. So if we encounter 10,then increment the value stored in index 10 by 1.
Finally print the array using a for loop.
So now I think we are in a position to write the code.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
int histogram[101];
int marks_of_students[]={10,50,30,60,35,40,100,90,75,50};
 
int len_of_marks_students=sizeof(marks_of_students)/sizeof(int);//length of array marks.
int len_of_histogram=sizeof(histogram)/sizeof(int);//length of array histogram.

int index=0;
//initialize the histogram array.
for(index=0;indexThis code also works the same way as described above.
Ok then this is it for this tutorial.
In the next tutorial, we shall take a look how to delete duplicates and How to sort an array.
simplycoder
simplycoder • Sep 15, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-20

Hello everyone again this is simplycoder and welcome to the 20[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on arrays.
In last tutorial,we have seen how to reverse an array and concept of histogram using arrays.

In this tutorial, we are going to see how to sort an array using different algorithms.

So let us begin with our first program.
  • WAP to sort an array of integers in acending order.
So how shall we go about this program?
Solution 1:
  1. Take the array, and compare the values, in current location and rest of the array . Swap if necessary.
  2. Repeat the step-1 for n-1 times, where n are the number of elements.
So from the above steps, we can easily come to know that we require nested for-loops.
The first for loop is required to traverse the array from index 0 to index n-1.
The second for loop is required to compare the indices and traverse the array.

let us assume the array to be
array[]={4,3,2,1}
The expected output is 1,2,3,4
array[0]=4.
array[1]=3.
array[2]=2.
array[3]=1.

Let us follow our algorithm.
let us assume our index of first for loop to be index_one and that of second for loop is index_two.
to compare the elements, we know that index_two=index_one+1.

so let us start now.

array is {4,3,2,1}
Iteration 1.1:
Value of index_one=0.
Value of index_two=1.
Compare array[0] with array[1], is swap required? Yes.
Now the array is {3,4,2,1}

Iteration 1.2:
Value of index_one=0.
Value of index_two=2.
Compare array[0] with array[2], is swap required? Yes.
Now the array is {2,4,3,1}

Iteration 1.3:
Value of index_one=0.
Value of index_two=3
Compare array[0] with array[3], is swap required? Yes.
Now the array is {1,4,3,2}

See after the first main interation, we have found the smallest value in the array and have placed it in correct place aswell.
Now let us go for the second iteration.

the array is {1,4,3,2}

Iteration 2.1:
Value of index_one=1.
Value of index_two=2.
Compare array[1] with array[2], is swap required? Yes.
Now the array is {1,3,4,2}

Iteration 2.2:
Value of index_one=1.
Value of index_two=3.
Compare array[1] with array[2], is swap required? Yes.
Now the array is {1,2,4,3}

So now let us go to our third iteration.
the array is {1,2,4,3}

Iteration 3.1:
Value of index_one=2.
Value of index_two=3.
Compare array[2] with array[3], is swap required? Yes.
Now the array is {1,2,3,4}

Thus you can now see that the array is sorted.
We are now in a position to write code for above algorithm.

#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
    int index_one,index_two,temp;

int array[]={4,3,2,1};
int size_of_array=sizeof(array)/sizeof(int);

for(index_one=0;index_onearray[index_two])
     {
        temp=array[index_one];
        array[index_one]=array[index_two];
        array[index_two]=temp;
       
     }
    
  } 
  
 
}

for(index_one=0;index_oneOk this one was one simple type of sorting, at this moment we are not interested in performance of algorithms, efficiency and other advance stuff.
We are not even interested in the names of algorithms that we are going to use. In this way, we would avoid being channelized.
So above algorithm finds the smallest value in the first main iteration and places it correctly, then it finds out the second smallest element,places it correctly.

In our next solution, we are going to modify above algorithm such that it finds the greatest value first and places it in the correct place.
So how do we proceed it.

We shall compare the adjacent elements, find the greater of the two and swap the places.
Repeat this till we have compared all the elements in array.

We shall assume the array to be{4,3,2,1}

Iteration 1.1:
Value of index_one=0.
Value of index_two=0.
Value of index_two+1=1.
Compare array[0] with array[1], is swap required? Yes.
Now the array is {3,4,2,1}

Iteration 1.2:
Value of index_one=0.
Value of index_two=1.
Value of index_two+1=2.
Compare array[1] with array[2], is swap required? Yes.
Now the array is {3,2,4,1}

Iteration 1.3:
Value of index_one=0.
Value of index_two=2
Value of index_two+1=3.
Compare array[2] with array[3], is swap required? Yes.
Now the array is {3,2,1,4}

See after the first main interation, we have found the largest value in the array and have placed it in correct place aswell.
Now let us go for the second iteration.

the array is {3,2,1,4}

Iteration 2.1:
Value of index_one=1.
Value of index_two=0
Value of index_two+1=1
Compare array[0] with array[1], is swap required? Yes.
Now the array is {2,3,1,4}

Iteration 2.2:
Value of index_one=1.
Value of index_two=1.
Value of index_two+1=2.
Compare array[1] with array[2], is swap required? Yes.
Now the array is {2,1,3,4}

So now let us go to our third iteration.
the array is {2,1,3,4}

Iteration 3.1:
Value of index_one=2.
Value of index_two=0.
Value of index_two+1=1.
Compare array[0] with array[1], is swap required? Yes.
Now the array is {1,2,3,4}

Thus you can now see that the array is sorted.
We are now in a position to write code for above algorithm.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
    int index_one,index_two,temp;

int array[]={4,3,2,1};
int size_of_array=sizeof(array)/sizeof(int);


for(index_one=0;index_onearray[index_two+1])
{
   temp=array[index_two];
   array[index_two]=array[index_two+1];
   array[index_two+1]=temp;
   
}  

}
}


for(index_one=0;index_oneThis is it for this tutorial, In the next tutorial, we are going to see how to delete duplicates in the array.
Its very important to practice. Try comming up with your own algorithms of sorting an array.
Until the next time, take care.
Caio.
simplycoder
simplycoder • Sep 19, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-21

Hello everyone again this is simplycoder and welcome to the 20[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on arrays.
In last tutorial,we have seen how to sort the contents of an array

In this tutorial, we are going to see how to delete the duplicates from an array.
  • WAP to delete the duplicate values from an array of integers.
So do we go about this, in problem, We donot know how many duplicates we have.
Thus we have to think a way to tackle it.

Simple algorithm will be our first choice.
We shall just follow these steps.
  1. Consider the first element
  2. Compare this element with all elements in array.
  3. If a match is found at a particular location then delete the element by overwriting it.
  4. Try to find another match.
  5. If a match exists, then repeat 3 and 4.
  6. Do this for all elements.
Ok, let us assume the array to be {1,1,2,3,3,3,1};
So now let us think how to tackle this.
We shall start with our first element this is array[0]=1;
Now we shall compare it with each element.
We find a match in the next element(arr[1]), so overwrite it by shifting all the remaining elements towards left.
i.e. arr[1]=arr[2],arr[2]=arr[3].. and so on.
decrement the length of array as an element is effectively been deleted.
so now the array is {1,2,3,3,3,1}.
repeat the above steps and we shall get rid of all duplicates.

So I think now we are ready to write a code for it.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
    int i,j,k;
int current=0;
    int arr[]={1,1,2,3,3,3,1};
        int size=sizeof(arr)/sizeof(int);
     //printf("%d ",size);
    for(i=0;iThe tricky part is of j--, this will help to scan for more duplicates by reassigning the value of j=i+1. and the rest works in same manner as of our algorithm.


Now let us see another program.
  • WAP to find maximum sum of consecutive elements in the array.

Basically this program asks us to find the maximum sum possible from the consecutive elements.
Algorithm:
  1. Take the first element and add the successive elements.
  2. If the sum is greater than the previous sum, then assign the maximum value to sum.
  3. Repeat this for next values.
Let us assume our array to contain both positive and negative values.
let it be {-2, 1, -3, 4, -1, 2, 1, -5, 4}.
So let us follow the algorithm and assign sum and max_sum as 0.

Iteration 1.1
i=0,j=0.
-2+1=1 so now sum=1 sum>maximum_sum so max_sum=1.
Iteration 1.2
-2+1-3 so now sum = -2 sum not greater than max_sum so no change.
Iteration 1.3
-2+1-3+4 so now sum = 0 sum not greater than max_sum so no change.
Iteration 1.4
-2+1-3+4-1 so now sum = -1 sum not greater than max_sum so no change.
Iteration 1.5
-2+1-3+4-1+2 so now sum = 1 sum not greater than max_sum so no change.
Iteration 1.5
-2+1-3+4-1+2+1 so now sum = 2 sum greater than max_sum so max_sum=2.
Iteration 1.6
-2+1-3+4-1+2+1-5 so now sum = -3 sum not greater than max_sum so no change.
Iteration 1.6
-2+1-3+4-1+2+1-5+4 so now sum = 1 sum not greater than max_sum so no change.
now since we have finished with our this iteration, we assign 0 to sum to start whole new series.

So as we can see the maximum sum is 2 when we start from the first element.
We proceed in the same manner. The code below will guide you to find the correct sum and its lower and upper bounds of position starting with 1...n.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{
//int arr[]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
int arr[]={-2, 1, -3, 4, -1, 2, 1, -5, 4};
int sum=0,max_sum=0;
int i,j,k,i1,i2;
int size=sizeof(arr)/sizeof(int);

for(i=0;imax_sum)
     {
     max_sum=sum;
     i1=i;
     i2=j;
     }
       
    }
    sum=0;
    
}

printf("sum : %d\t j : %d\t k : %d\n",maxsum,(i1+1),(i2+1));


    printf("\n\n\n");

    system("PAUSE");    
    return 0;
}


It so happens that the maximum sum obtained is 6 in the array starting from 4th(arr[3]) element and ending at 7th(arr[6]) element.
The commented array is taken from a well known book of algorithms, authored by Thomas Cormen.
This is it for this tutorial, in the next tutorial, we shall see how to play around more with arrays and may be will take a look at multidimensional arrays as well.

Until the next time, take care.
Ciao.
simplycoder
simplycoder • Sep 24, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-22

Hello everyone again this is simplycoder and welcome to the 22[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on arrays.
In last tutorial,we have seen how to delete the duplicates and how to find the maximum sum in the sub array.

I think I have covered sufficient number examples of ranging difficulties considering one dimensional array.

In this tutorial, for the very first time I would make use of multi dimensional arrays.

In previous tutorials, I had introduced how to declare and define multidimensional arrays.

Enough of blabbering from my side, we shall just start to use these mutidimensional arrays.

  • WAP to print a matrix, input is initialized for 3x3 matrix.
Ok, since its a 3x3 matrix, we have 9 elements, for sake of simplicity, we shall assume the elements as {1,2,3,4,5,6,7,8,9}.
We have done enough examples on control structures to print patterns, so in this case we have to print a pattern similar to this.

* * *
* * *
* * *
So this program shouldnot be much difficult to understand and there is nothing much to explain so lets just jump on the code.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{

    int size=3;
    int index_one,index_two;
    int matrix[100][100]={{1,2,3},{4,5,6},{7,8,9}};
    
    for(index_one=0;index_oneNothing much to explain here, only the syntax changes, no new logic applied.
So let us take a step forward and WAP to add two matrices and save the result in the third matrice and print all the three matrices.
  • WAP to add two matrices and save the result in third matrix.Print all the matrices.
So basically we have to add the matrices.
Let matrix_one and matrix_two be two matrices and the answer be stored in array called as matrix_ans.

So we shoud do something as follows.
matrix_ans[0][0]=matrix_one[0][0]+matrix_two[0][0].
matrix_ans[0][1]=matrix_one[0][1]+matrix_two[0][1].
matrix_ans[0][2]=matrix_one[0][2]+matrix_two[0][2].
and so on...
If you watch this carefully, you will note that the indices of all the matrices at a particular instance is the same.
So we can write a code similar to matrix_ans[index_one][index_two]=matrix_one[index_one][index_two]+matrix_two[index_one][index_two].

Knowing this, we are in a position to write the code.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{

    int size=3;
    int index_one,index_two;
    int matrix_one[100][100]={{1,2,3},{4,5,6},{7,8,9}};
    int matrix_two[100][100]={{9,8,7},{6,5,4},{3,2,1}};
    int matrix_ans[100][100];
  
    printf("First matrix is : \n");
    for(index_one=0;index_oneKnowing this, you can write the code to subtract two matrices.

This is it for this tutorial, in the next tutorial, I shall explain how to multiply two matrices, finding the saddle point and etc.
keep practicing.
Until the next time, take care.
Ciao.
simplycoder
simplycoder • Sep 29, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-23

Hello everyone again this is simplycoder and welcome to the 23[SUP]rd[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on two dimensional arrays.
In last tutorial,we have seen how to print and add two matrices.

In this tutorial, we shall see how to multiply two matrices and store the answer in an array.

The only pre requisite for this is the basic math background to multiply matrices.

Lets the first matrix as
1 2 3
4 5 6
7 8 9

and second matrix is
9 8 7
6 5 4
3 2 1
To multiply them, we multiply row1*col1. to get the first element in matrix and so on.
so the answers are as follows.

1*9 + 2*6 + 3*3 = 30.
1*8 + 2*5 + 3*2 = 24.
1*7 + 2*4 + 3*1 = 18.

and we continue to get the enitre matrix.
the final answer is ::
30 24 18
84 69 54
138 114 90

Thus if you observe it carefully, we can see that we take a row and multiply it with its correct column to get the value at correct position in final matrix.
so all we have to do is multiply correct elements and sum them up.

Knowing this, we would write a code for it.
#include 
#include 
#include 
/*Author : simplycoder*/

int main(int argc, char *argv[])
{

    int size=3;
    int index_one,index_two,index_three;
    int matrix_one[100][100]={{1,2,3},{4,5,6},{7,8,9}};
    int matrix_two[100][100]={{9,8,7},{6,5,4},{3,2,1}};
    int matrix_ans[100][100];
  
    printf("First matrix is : \n");
    for(index_one=0;index_onetake a look at this part
for(index_one=0;index_oneLet us work out for the first element.
index_one=0.
index_two=0.
so we are dealing with matrix_ans[0][0].
index_three =0.
matrix_one[index_one][index_three]=matrix_one[0][0]=1.
similarly:
matrix_two[index_three][index_two]=matrix_two[0][0]=9.
so matrix_ans[0][0]+=matrix_one[0][0]*matrix_two[0][0].
so matrix_ans[0][0]=0+1*9=0+9=9.

now index_three increments,index_three=1.
matrix_one[index_one][index_three]=matrix_one[0][1]=2.
similarly, matrix_two[index_three][index_two]=matrix_two[1][0]=6.
so matrix_ans[0][0]+=matrix_one[0][1]*matrix_two[1][0].

so matrix_ans[0][0]=9+2*6 = 9+12 = 21.

now index_three increments,index_three=2.
matrix_one[index_one][index_three]=matrix_one[0][2]=3.
similarly,matrix_two[index_three][index_two]=matrix_two[2][0]=3.
so matrix_ans[0][0]+=matrix_one[0][2]*matrix_two[2][0].

so matrix_ans[0][0]=21+3*3=21+9=30.

now index_three increments,index_three=3, loop terminates.
hence the final value in matrix_ans[0][0]=30.

Execute this for all elements.

This was a big piece of code, however once you can understand the logic, nothing is difficult, execute this program once or twice by hand, you would get a hang of it.

This is it for this tutorial.
Until the next time, take care.
Ciao.
simplycoder
simplycoder • Oct 2, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-24

Ok we are done with our basic introduction of arrays, and now we would proceed to deal with another derived data-type 'structs or structures'.

Structs are record keeping derived data types which unlike arrays have capability to store unidentical objects.
Say if I want to maintain the record of name of students and his marks, then one structure is enough to do this.

The basic syntax for structured data-type is

struct name_of_structure{ identical/unidentical datatypes.} instance_name;
If we want to maintain record of a class of students, then we can make array of the structures.

We shall see this with examples.
  • WAP to take in name of student,and marks using structure.
We already know the syntax of the structure,so just let us go on writing the code.
#include
int main(int argc,char**argv)
{
struct student{
       char name[20];
       int marks;
       }student;  
       
       printf("Enter the name of the student\n");
   
       scanf("%s",&student.name);
       printf("Enter the marks of the student\n");
       scanf("%d",&student.marks);  
       printf("Names\tMarks\n");
       printf("%s\t%d",student.name,student.marks);
            
   printf("\n\n\n\n");
   system("PAUSE");
   return 0;
   
}
While accessing the array, we must choose the field which we want to access. This is done with help of "."(Period).
so students.name is equivalent to selecting the field name from structure student.

This was easy,piece of cake,if you think so,then I am pretty much satisfied with my effort.

Now let us make a record of students in a class let us assume 5 students.
Things are pretty much the same,just some syntax issues,these all will be resolved once you go through the code.
#include
int main(int argc,char**argv)
{
struct student{
       char name[20];
       int marks;
       }student;  
       
       int number_of_students=5;
       
       struct student s[100];

       int index;
       for(index=0;indexThe new thing about this code is 
struct student s[100];
Just treat this as a way to create array of structures;
It can be read as follows: Create a array of structures of type students and name the array as s.
So visualize the array of structures of type student as block of elements,similar to one dimensional array, only difference is each block will contain memory allocated for an array of characters of size 20 and for integer which will contain the marks.

Ok this is it for this tutorial, in the next tutorial, we shall see more on how to sort the array of structures based on highest marks and some similar examples.
Until the next time,take care.
Ciao.
simplycoder
simplycoder • Oct 5, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-25

Hello everyone again this is simplycoder and welcome to the 25[SUP]th[/SUP] tutorial of C-programing.
In this tutorial, we are going to learn more on structs.
In last tutorial,we have seen how to define/declare a struct,take the input in the struct and printout the fields in struct. We have also seen how to make arrays of structs and how to print the arrays of structs.

In this tutorial, we are going to sort the details of the structs.
Lets take a typical example
  • Make a record of n students and their total marks and sort them according to marks(highest first).
This is simple,
We know how to take input in structs.
We know how to sort the arrays, in case if you don't know, then I will suggest you to read the tutorial in which I have discussed sorting of arrays.

So lets write it.
#include
int main(int argc,char**argv)
{
struct student{
       char name[20];
       int marks;
       }student,temp;  
       
       int number_of_students=3;
       
       struct student s[100];

       int index,index_one,index_two;
       for(index=0;indexOk now lets discuss the same.
I have created a new instance of student as temp, this is only to help me in sorting and has no other significance.
Since we are sorting on based on marks,that is why s.marks is chosen as basis of comparison.
The heart of this program is sorting,for which I would recommend referring the previous article.

Ok this is it for this tutorial,in next tutorial we shall take a look another record keeping data-type:: UNIONS.
Until the next time, take care.
Ciao.
simplycoder
simplycoder • Oct 14, 2011
Re: Beginners Tutorial : The C-language:: Tutorial-26

Unions in C.
Unions in C are another record-keeping data type available in C++.
Unions are similar to Structures,but the main difference is that we can save only one piece of information at a time.
Syntax, format and use of tags and declarators like struct, but members overlay each other, rather than following each other in memory.
Size of structure is some of the size required by all elements + by padding(lets not get into this as it requires basis of computer organization and fundamentals of memory organization) whereas size of an union is the size of the largest data-type in union.

Syntax: Union {..};

For beginners, this much is more than enough to know and we shall begin with a program to make things simpler.

  • WAP for finding the size of the union.
This is simple and has really no algorithm as such.
Its all syntax.
#include 
int main(int argc,char**argv)
{ 
   
  union{
        int a;
        double b;
        }uni;
        
        printf("Integer on this machine requires %d bytes\n",sizeof(int));
        printf("Double on this machine requires %d bytes\n",sizeof(double));
        
        printf("Size of the union \"uni\" is :: %d bytes\n",sizeof(uni));
        
        printf("\n\n\n\n\n");
   system("PAUSE");
   return 0;
}

This is very simple.
From the above program, we can say that the memory allocated for all the members is the same and its size is the size of the largest data-type.

There is nothing more to add into unions.

I suggest you guys extend the above code for printing the size of structure as well.

This was a very small tutorial, but then since its a part of C,even though its not as popular as structs, still is handy some times.
In the next tutorial, I shall write on most interesting thing in C, the POINTERS.

Until the next time,take care.

Ciao.
Khan Hussain
Khan Hussain • Jun 16, 2012
Thanks for a nice tutorial but where I find the next tutorials. 😁
sulochana anand
sulochana anand • Sep 1, 2012
i
TheV
I am confused....lol...

this c code is going out of my mind...

float c = 0.7;
if(c < 0.7)
    printf("C");
else
    printf("C++");
in my Turbo C++ compiler it is printing C ... I don't know how.. plz any one explain it....!
instead of float data type use integer
[Prototype]
[Prototype] • Sep 1, 2012
sulochana anand
i

instead of float data type use integer
How will you compare 0.7 with integer?

This issue is not related to data type but the floating point representation that is done, the IEEE standard.

The actual value of 0.7 stored in a variable is 0.6999999881. You should do the comparison specifying the 0.7 to be as of same storage class as the one stored in the variable.

float c = 0.7;
if(c < 0.7f)
    printf("C");
else
    printf("C++");
The above code will give desired results.
sulochana anand
sulochana anand • Sep 1, 2012
[Prototype]
How will you compare 0.7 with integer?

This issue is not related to data type but the floating point representation that is done, the IEEE standard.

You actual value of 0.7 stored in a variable is 0.6999999881. You should do the comparison specifying the 0.7 to be as of same storage class as the one stored in the variable.

float c = 0.7;
if(c < 0.7f)
    printf("C");
else
    printf("C++");
The above code will give desired results.
ok i was unaware.
Good basics for beginers..

Keep posting.
babloo0311
babloo0311 • Nov 1, 2012
very useful
varshiva
varshiva • Nov 2, 2012
how can we understand the radius as float

and when will we use const

please explain how to use float,double
varshiva
how can we understand the radius as float

and when will we use const

please explain how to use float,double
I didn't understand your 1st question..
Coming to the second one, we use const mainly when we are passing an array or a string in the function. Sometimes, there is a possibility that the size of array gets disturbed during passing. so to avoid that we use const key word, which doesn't allow any change in size. i.e. keeps it constant.

We use float and double depending on the situation. like, we know that the percentage of a student can even be in decimals.. Hence, we use float in that situation..
Jeffrey Arulraj
Jeffrey Arulraj • Nov 2, 2012
varshiva
how can we understand the radius as float

and when will we use const

please explain how to use float,double
All values entered by the user can never be determined that easily by the programmer in advance that is the reason why we go for float than int in many times

In practical thinking a radius can be both of float value and also an integer so to randomise and to get more accurate value in the op we go for Float instead of int
varshiva
varshiva • Nov 3, 2012
thank you guys
Chinu1
Chinu1 • Nov 27, 2012
You are doing a great job. Thank you so much. Now, I understand the difference between local and global variables.
SamiZzY
SamiZzY • Jan 5, 2013
#include 
#include 
int main(int argc, char *argv[])
{
 
  int a,b,i,c;
  printf("Give the number upto which the squares of the numbers are to be added\n\n");
  scanf("%d",&a);
 
 
  c=0;
 
  for(i=0;ifirst of all thankyou for all the great tutorials simplycoder 😀. And i am kind of stuck in tutorial 11 exercises, the one where you have to find the sum of squares of n numbers. Above is the code i wrote, i am just a newbie its hardly been 3 days since i started C so excuse the noobness please.
 
simplycoder
simplycoder • Jan 5, 2013
SamiZzY
#include 
#include 
int main(int argc, char *argv[])
{
 
  int a,b,i,c;
  printf("Give the number upto which the squares of the numbers are to be added\n\n");
  scanf("%d",&a);
 
 
  c=0;
 
  for(i=0;ifirst of all thankyou for all the great tutorials simplycoder 😀. And i am kind of stuck in tutorial 11 exercises, the one where you have to find the sum of squares of n numbers. Above is the code i wrote, i am just a newbie its hardly been 3 days since i started C so excuse the noobness please.
First of all welcome to CE.
There are few pointers which I like to add.
1)Declaration : Since this is very short program, I dont have to worry much on which variable is used for what purpose. But its slightly tedious when it comes to medium or lengthy programs.
So to avoid this, make sure you use meaningful variable and method names, you would make life easy for person reviewing or understanding you code. Trust me this is very important.
2)Comments : You should and must comment or even better, document your code no matter how small or big the assignment is. This helps a lot and also would be helpful in the future. Comment on the key points and what variable is doing,how it is used,why it is used and so on.
3)Make sections in your code : Sections are always readable and gives a nice impression.
Say you have a program where in you have variable declarations, put them under variable declaration section. Organize your code, I know this is not required in small programs, but doesn't hurt to be more organized, and if you don't do this in lengthy codes, trust me, you are going to end up doing a messy code which would be hard to debug.
4)Write the code in such a way that any person with basic understanding of language can understand your code. as the saying goes and I quote Any fool can write code that a computer can understand. Good programmers write code that humans can understand.- Martin Fowler
5)Solve the problem on piece of paper, write the steps down and also track the program for small input, if this is done, then only try to code in programming language (VVIMP).


Now coming back to your problem.
a is used for totalNumbers,
b is where you assign the current number,
c is the output variable.

I understood this line b=1+i; as i starts from 0 which is the index of for loop, so b=i+1 so when i=0, b=1 and so on. I understood this as the current number whose square you are calculating.
However, I am not able to understand this line
c*c=b*b+c*c; /*help needed in this line*/
Why have you squared the left hand side? The C-compiler will definitely throw an error on compilation, and it should be something like 'Invalid lvalue assignment'.
I am even more confused when you used printf("%d\n",(c*c));
I suggest you should focus more on algorithmic aspect of the problem. Donot worry much about C-Language, any one can program in C language with practice of about a month or two(I am talking about just writing and not being expert in C). And programming a problem is simpler as compared solving and developing an algorithm for the problem as you can see, you can program in C, but its the algorithm and the approach that has led you to trouble.(Donot misunderstand me, I am writing this much not to brag about me, but rather I recalled the days when I began to program, it was worse than this and had to undergo a lot of trouble to make things work, so trying to make your life easier. You would be going through some hard stuff, just dont give up in case of any doubt post, on a new thread,
Above is the code i wrote, i am just a newbie its hardly been 3 days since i started C so excuse the noobness please.
On this forum, we share, no one is noob, we share and gain knowledge that is one of the best things on this forum so feel free to post.
Anyways here is what I have coded for you, ask if you are stuck any where.


//Author: SimplyCoder.
//Date: 06/12/2012.
// IDE : Dev C++
/********************************************************************************/
                            //Problem Statement.(Tutorial 11, Problem 4)
/********************************************************************************/
/*****WAP to find the sum of series 1+4+9+16+...n^2 where the input is take from */
/*****user, using for,while and do...while looping                              */
/*****(DONOT use formula, however verify using the formula).                    */
/********************************************************************************/
 
//Macros Declaration-Start.
#include
//Macros Declaration-End.
 
//Function-Declaration-Start.
    
int findSum(int totalNumbers);
//Function-Declaration-End.
//Main Method-Start.
    
int main(int argc,char**argv)
        {
        
//Declaration for local variables-Start.
            
int totalNumbers=0// total numbers in the series : 1+4+9...+n^2, correponds to n.
            
int finalAnswer=0// final answer : Sum of the given series.
        //Declaration for local variables-End.
   
        //Take the User Input-Start.
            
printf("Give the number upto which the squares of the numbers are to be added :: ");
            
scanf("%d",&totalNumbers);
        
//Take the user Input-End.
   
            
finalAnswer=findSum(totalNumbers);//Calculate the output.
            
printf("\nThe sum is :: %d\n",finalAnswer);//print the answer.
   
            
printf("\n\nExecution Complete, System Paused.\n");
            
system("pause");
        }
//Main Method-End.
 
//Local Methods-Start.
 
//findSum Method-Start.
/***************************************************************************/
//Accepts an integer.
//Returns an integer.
//Used to calculate the sum of the series.
/***************************************************************************/
 
    
int findSum(int totalNumbers)
        {
        
//Variable Declaration-Start.
            
int index=0//index for the 'for-loop'
            
int finalAnswer=0// final answer : Sum of the given series.
        //Variable Declaration-End.
           
        //for loop below calculates the sum for the required
            
for(index=1;index<=totalNumbers;index++)
                {
                    
finalAnswer=finalAnswer+(index*index);
                  }
            return 
finalAnswer;
        }
//findSum Method-End.
 
 
//Local-Method-End.
Take care,
SimplyCoder.
SamiZzY
SamiZzY • Jan 6, 2013
Wasn't expecting a reply but this is amazing 😁 ,nice people still exist. Thankyou very much for the reply😀.
Regarding the line ,c*c=b*b+c*c.... i didnt know about the findsum function , so i started with a code for the ' find the sum of n numbers' which is

final_ans=0
for(index=0,index { current_number=1+index;
final_ans=final_ans+index;
}
printf("%d",final_ans);

so i figured if i wanted to find the sum of squares of the numbers , i just have to square the final equation terms i.e,( final_ans*final_ans)=(final_ans*final_ans)+(current_number*current_number);
which turns out is absolutely wrong and i get why, thanks to you.And also thankyou for valuable tips will make sure to follow them.
SamiZzY
SamiZzY • Jan 6, 2013
when i execute the 'find sum of n number' program, it gives an error "undefined reference to' findsum' ".
some prob with my compiler or something ?
simplycoder
simplycoder • Jan 6, 2013
SamiZzY
Wasn't expecting a reply but this is amazing 😁 ,nice people still exist. Thankyou very much for the reply😀.
Thanks for the compliment.

SamiZzY
when i execute the 'find sum of n number' program, it gives an error "undefined reference to' findsum' ".
some prob with my compiler or something ?
Which compiler are you using?
I am using Dev C++ as my IDE and its default compiler.

Please donot use Turbo C (One with Blue Screen).
SamiZzY
SamiZzY • Jan 6, 2013
yes I am also using Dev C++ v 4.9.9.2, downloaded it from the link provided in the 1st page.
simplycoder
simplycoder • Jan 6, 2013
In that case, kindly verify the it with my code, if you have copy pasted it, copy paste it again and let us know.
rahul69
rahul69 • Jan 6, 2013
SamiZzY
Regarding the line ,c*c=b*b+c*c.... i didnt know about the findsum function
and
it gives an error "undefined reference to' findsum' "
From above quotes I guessed that u are probably considering findsum as pre-existing like Library functions, which is not true, this findsum function is a user defined function and hence u will have to also write the function definition (ie function code) in your program. This "undefined reference" error also comes when u use a function without including its definition, and only declaration. Hope it helps!!!👍
SamiZzY
SamiZzY • Jan 6, 2013
#include 
#include 
 
int main(int argc, char *argv[])
{int total_number,index,final_ans;
 
printf("Give the number upto which the square of the numbers are to be added::\n");
 
scanf("%d",&total_number);
 
final_ans=0;
 
for(index=1;index<=total_number;index++)
{
final_ans=final_ans+(index*index);
}
printf("The Sum of the squares of %d numbers is %d",total_number,final_ans);
  system("PAUSE"); 
  return 0;
}
the code you gave me , it worked but now i am even more confused.😕
Above is the code which i wrote after observing yours(for finding sum of squares of n num and it works XD).
the reason why it was giving error was because i copy pasted the code only uptill Main Method-End.
I thought above and below main method-end in your program are two different codes , one for the sum of n numbers and the other for the sum of the squares of n numbers.
confused confused confused.!
Jeffrey Arulraj
Jeffrey Arulraj • Jan 6, 2013
That main method end was in comment and SC used Function call in his program The findsum function was called in the main program.

They are different functions But they are same programs

PS: // any line beginning with this '//' is a comment line and they are not considered by the compiler They are given for your understanding and does not mark the end of the program
SamiZzY
SamiZzY • Jan 6, 2013
rahul69
SamiZzY

and

From above quotes I guessed that u are probably considering findsum as pre-existing like Library functions, which is not true, this findsum function is a user defined function and hence u will have to also write the function definition (ie function code) in your program. This "undefined reference" error also comes when u use a function without including its definition, and only declaration. Hope it helps!!!👍
yeah i was beginning to think like that thanks for clarification. See the program worked now because i copied the whole code. so maybe it is defined somewhere ? i cant find it lol help
SamiZzY
SamiZzY • Jan 6, 2013
Conqueror
That main method end was in comment and SC used Function call in his program The findsum function was called in the main program.

They are different functions But they are same programs

PS: // any line beginning with this '//' is a comment line and they are not considered by the compiler They are given for your understanding and does not mark the end of the program
yes i knw that they are comments, i just used it so as to say below or above it.
simplycoder
simplycoder • Jan 6, 2013
SamiZzY
#include 
#include 
 
int main(int argc, char *argv[])
{int total_number,index,final_ans;
 
printf("Give the number upto which the square of the numbers are to be added::\n");
 
scanf("%d",&total_number);
 
final_ans=0;
 
for(index=1;index<=total_number;index++)
{
final_ans=final_ans+(index*index);
}
printf("The Sum of the squares of %d numbers is %d",total_number,final_ans);
  system("PAUSE");
  return 0;
}
the code you gave me , it worked but now i am even more confused.😕
Above is the code which i wrote after observing yours(for finding sum of squares of n num and it works XD).
the reason why it was giving error was because i copy pasted the code only uptill Main Method-End.
I thought above and below main method-end in your program are two different codes , one for the sum of n numbers and the other for the sum of the squares of n numbers.
confused confused confused.!
Check in function declaration section.
SamiZzY
SamiZzY • Jan 8, 2013
sir, ... it seems i am stuck again but this time for sure, i know the logic.
Below is the code for verifying an armstrong number(tut: 13 exercise 3) and thankfully it works.😉

#include 
#include 
 
int main(int argc, char *argv[])
 
{int input,index,final_ans,index2,n,temp,digit,original_input;
printf("Give the number to be verified if it's an armstrong number or not ::\n");
scanf("%d",&input);
final_ans = 0;
index=0;
n=0;
//FINDING THE NUMBER OF DIGITS-START.                                     
while(temp!=0)          //when temp reaches 0 stop the loop
{index=index+1;       
temp=input/pow(10,index);
n++;                    // n is initially 0 , placed n here as there will be an increment in n by +1 with each loop
 
}
//FINDING THE NUMBER OF DIGITS-END.
original_input=input; // storing the input in another int as our integer will be changing in the main code
 
               
//FINDING THE FINAL ANSWER PART.(MAIN CODE)
for(index2=1;index2<=(n);index2++)
{
  digit = input%10;          //we get the unit place digit for the input
final_ans = final_ans + pow(digit,n); //the digit is raised to nth power and added to other nth power digits.
input=input/10;                      //since the input's last digit is found, in order to remove last digit we divide by 10.
                                       
}
if(final_ans==original_input)
printf("The given number %d is a Armstrong number\n",original_input);
else
printf("The given number is not a Armstrong number\n");
 
  system("PAUSE");   
  return 0;
}
so one may think that, if verifying a number is possible then printing armstrong number is no biggie.
I thought so too. i wrote the code, and i have no idea why it just prints 1 infinitely.
#include 
#include 
 
int main(int argc, char *argv[])
{    int index,index2,final_ans,original_index,digit;
 
for(index=100;index<=999;index++)
{
original_index=index;
final_ans=0;
 
for(index2=1;index2<=3;index2++)
{
digit=index%10;
final_ans=final_ans+pow(digit,3);
index=index/10;
}
 
if(final_ans==original_index)
printf("%d\n",final_ans);
}
 
  system("PAUSE");   
  return 0;
}
Above is the code for printing armstrong number from 100 to 999(tut 13 exercise 4).
It would be very helpful if you could correct me. Thankyou in advance.
Jeffrey Arulraj
Jeffrey Arulraj • Jan 9, 2013
for(index2=1;index2<=3;index2++)
{
digit=index%10;
final_ans=final_ans+pow(digit,3);
index=index/10;
}
instead of the variable index use original_index here that should solve the problem here
SamiZzY
SamiZzY • Jan 9, 2013
i replaced the l.h.s index with original index int the last line(is that what you meant?😕 ) , and the output was 24 and 81. pretty strange because index changes from 100 to 999 but thankyou for the reply mr.jeffrey 😀
Jeffrey Arulraj
Jeffrey Arulraj • Jan 9, 2013
for(index2=1;index2<=3;index2++)
{
digit=index%10;// Replace this index
final_ans=final_ans+pow(digit,3);
index=index/10;// and also here both the index has to be varied
}
Cos your program is having a logical error since you are manipulating the the control variable of the outer loop in the inner most loops So you are getting an error here
SamiZzY
SamiZzY • Jan 9, 2013
thankyou sir.! noting what you said , replaced all the var index with original index in the 2nd loop
and at the bottom if condition replaced original index with var index and by god's grace it worked .!
thankyou again.
Jeffrey Arulraj
Jeffrey Arulraj • Jan 9, 2013
SamiZzY
thankyou sir.! noting what you said , replaced all the var index with original index in the 2nd loop
and at the bottom if condition replaced original index with var index and by god's grace it worked .!
thankyou again.
It is my pleasure to help you Pls avoid Siring me I ama student just like you

We are all are here to help you and learn from you
Ashish Saklani
Ashish Saklani • Feb 20, 2013
thank u simplycoder this tutorials will help me in programming.
simplycoder
simplycoder • Feb 20, 2013
Ashish Saklani
thank u simplycoder this tutorials will help me in programming.
Its glad to hear.
lit-857
lit-857 • Mar 27, 2013
sir u should give the ans of exersies
simplycoder
simplycoder • Mar 27, 2013
lit-857
sir u should give the ans of exersies
The best part about programming is that you know the correct answer.
If you follow the tutorial throughout then I think you wouldn't find it difficult(challenging has a different meaning.)

Still if you don't get the output, show your work and then we can debug it or see where it goes wrong.

Tip:The best way to solve is to execute it by hand for small input.
lit-857
lit-857 • Apr 2, 2013
what d/f b/w float and double datatype
Jeffrey Arulraj
Jeffrey Arulraj • Apr 2, 2013
lit-857
what d/f b/w float and double datatype
float datatype allows only 4 bytes of memory Whereas the double type allows 8 bytes

Only the range of these two differs not their other types
lit-857
lit-857 • Apr 4, 2013
i know very well but i want to get understend with exmple
Ganesh MSD
Ganesh MSD • Apr 7, 2013
Nice article...!! This is simply awesome. So useful.
lit-857
i know very well but i want to get understend with exmple
As already stated before, the main difference lies in the range. Float is single precision and double is double precision floating number. It is called double precision as it is twice of a normal float variable.

As per your request here is an example:

Suppose ABC person is very rich and has a huge amount of money (so much that it cant be represented in a single precision number). If you want to store that amount of money in a float variable, then it will truncate the double precision number to single precision which in turn will reduce the amount of money that the person holds. Isn't it a problem? Yes it is. That is the main reason for existence of double precision data types i.e. to store huge values.

The example that I gave is quite vague but I think it will help you in understanding the difference clearly..
try coding this!!! A good question!

Write a C program to Remove even numbers and fill it with zeros.
Note: You can use only one loop for your logic.
Two variables apart from the array.
Input array 1,2,3,4,5,6
Output 1,3,5,0,0,0
Vishal0203
try coding this!!! A good question!

Write a C program to Remove even numbers and fill it with zeros.
Note: You can use only one loop for your logic.
Two variables apart from the array.
Input array 1,2,3,4,5,6
Output 1,3,5,0,0,0

no one is answering to this?
Nayan Goenka
Nayan Goenka • Aug 13, 2013
Vishal0203
no one is answering to this?

I didnt read this. I will post my code soon enough. Give me some time to code. By the way, you want the complete code or just function?
Nayan Goenka
Nayan Goenka • Aug 13, 2013
Here is my code. 😁 Its quite tricky to get the output as you wanted. Odds first then 0's 😛 Anyways it was good exercise with C++ for me.

#include
#include
void main()
  {
    clrscr();
    int input[6],output[6],i,j=0;
    cout<<"\n Enter the Inputs :";
 
 
    while (j>=0)
      {
    for(i=0;i<6;i++)
      {
        cin>>input[i];
        if( input[i] % 2 != 0)
          {
        output[j] = input[i];
        j++;                                                              }
      }
    break;
    }
 
 
    for(j;j<6;j++)
      {
    output[j]=0;
      }
 
    cout<<"\n The output is: ";
 
    for(j=0;j<6;j++)
      cout<<" "<
 
Nayan Goenka
Here is my code. 😁 Its quite tricky to get the output as you wanted. Odds first then 0's 😛 Anyways it was good exercise with C++ for me.

#include
#include
void main()
  {
    clrscr();
    int input[6],output[6],i,j=0;
    cout<<"\n Enter the Inputs :";
 
 
    while (j>=0)
      {
    for(i=0;i<6;i++)
      {
        cin>>input[i];
        if( input[i] % 2 != 0)
          {
        output[j] = input[i];
        j++;                                                              }
      }
    break;
    }
 
 
    for(j;j<6;j++)
      {
    output[j]=0;
      }
 
    cout<<"\n The output is: ";
 
    for(j=0;j<6;j++)
      cout<<" "<
Was I not clear??? read the question! just 1 loop and 2 variables apart from array!
Nayan Goenka
Nayan Goenka • Aug 13, 2013
Vishal0203
Was I not clear??? read the question! just 1 loop and 2 variables apart from array!


Meh, Put the for loop outside while, inside. It will work that way too. And if you are using 2 arrays, you have to use two loops atleast.

If you want ONE loop then the output you will get will be 103050 and not 135000
Nayan Goenka
Meh, Put the for loop outside while, inside. It will work that way too. And if you are using 2 arrays, you have to use two loops atleast.

If you want ONE loop then the output you will get will be 103050 and not 135000
hahahahahahha... 😁
that's the challenge bro don't tell me that it cant be done. It can be done! try!
one loop.. one array.. 2 supporting variables
Nayan Goenka
Meh, Put the for loop outside while, inside. It will work that way too. And if you are using 2 arrays, you have to use two loops atleast.

If you want ONE loop then the output you will get will be 103050 and not 135000

and yeah! the loop should be common to take inputs arrange values and to display output!
simplycoder
simplycoder • Aug 15, 2013
I would take a try to crack this,
 
#include "stdio.h"
 
int main(int argc,char**argv)
{
int index=0// Variable 1
int temp_index=0// Varible 2
 
// Size considered as 6 hardcoded :(
for(index=1,temp_index=1;index<=6||temp_index<=6/2;index++) // One Loop.
{
// Print the odd numbers first.
if((index&1)&&(index<=6))
{
printf("%d",index);
}
// Print 0 for the even number later.
else if(index>6)
{
temp_index++;
printf("0");
}
 
}
printf("\n");
return 
0;
}
Didn't utilize array part as well I have hard coded the values.
and my code for the question is this... kinda similar! and for n values!

#include
int ar[100],i = 0; //array and 1 var
 
int main() {
    int n; //2nd var
    printf("enter range : ");
    scanf("%d",&n);
    printf("enter the numbers : ");
    while(i < n) {
        if(i >= n/2) {
            printf("%d, ",ar[i]);
            i++;
            continue;
        }
        scanf("%d",&ar[i]);
        if(ar[i]%2 == 0) {
        }
        else {
            ar[i] = ar[i];
            printf("%d, ",ar[i]);
            i++;
        }
    }
    return 0;
}
simplycoder
simplycoder • May 4, 2014
Re: Beginners Tutorial : The C-language:: Tutorial-27
Pointers in C
I would break this main tutorials in many sub tutorials in order to highlight each of the concept related to pointers.
In this tutorial I would be covering the basic definition,usage,need and the Address Of Operator in C POINTERS.
---------------------------------------------------------------------------------------------------
If I have to point out the feature in C language, which is most widely misunderstood by begineers in C, then I wouldnot have second thoughts to say its POINTERS.
Basically begineers have difficulty in understanding the pointer terminology implemented by C.
There is no programing language, which doesnot use pointers. However, very few (C being one of them) gives programmers a chance to use it in day to day coding.

Pointers are like double edge swords and programmer must take care to use it properly.

  • #What are pointers:
A pointer is a variable which has address of the memory location of another variable.
eg. Suppose I declare an integer 'A' and compile the program. The compiler would store a finite memory for this integer at some location. Every memory location has unique address. So its safe to say that a memory location is like a house and like every house has unique address, every memory location would have unique address.

Now I would like to store the address of the memory location where integer 'A' has been stored in a variable 'X'.
This variable 'X' is called as pointer.

  • Basic Pointers:

  1. Address Of Pointer:
Assume a declaration like
int x=4;
When we compile the program, compiler does the following tasks:

->Reserve space in memory to hold the integer value.
->Associate the name x with the above memory location.
->Save value 4 in this memory location.

Lets say that compiler chose the memory location with address '1000' to store the variable x.
Then the pointer of x would have value 1000 in it.

Let us write a sample code for this.

//Code

#include 
int main(int argc,char**argv)
{
  
int x=4;
printf(" Value of x : %d\n",x);
printf(" Address of x : %d\n",&x);
   system("PAUSE");
   return 0;
}


//Output :
Value of x : 4
Address of x : 2686788
Press any key to continue . . .
The '&' operator that is being used here, is called as the 'Address Of' operator.
This operator, returns the address of the memory location where in the value of the variable is stored.
Please note the output of the address may(and would in most of the cases) differ from the output given here.

I leave the task of reading further about Address Of operator and linking it to the scanf functionality, to the reader.
In the next tutorial, I shall write on Value At Address (*) operator.

Until the next time,take care.
Ciao.

I thought of sharing this with everyone. A good way to program and test your programs. Most of beginners generally code every logic inside the main() and to test their program they execute the code n number of times (n test cases) each time entering a test case. That's really annoying for the person who has written the code and they may skip most of the test cases thinking they'll get a correct output for all of them. But, this can be done in an interesting way where the evaluation of the code is done by the code itself i.e. no need of executing the code again n again.

A programmer needs to understand that it is always a good practice to divide the problem in as many functions as possible, keeping in mind that each function performs only a particular task.
I'll not make the post much longer so we'll have a quick look on an example.
Let us pick up a small program like, Sum of the elements of an array. Now how to start? Well, just define a structure first (I'll explain why we are doing it)

struct test
{
    int input[10];    // involves your test case arrays
    int terms;         // the number of term in your array
    int output;        // the output which you are expecting
} testVals[4] = {   // these are your test cases you can add as many you like (4 here)
                            {{1,2,3,4,5,6,7,8,9,10} , 10, 55},  // initializing input, terms, expected output
                            {{2,4,6,8} , 4, 20},
                            {{3,6,9} , 3,  18},
                            {{1,2,3,4,5} , 5, 15}
                };
I've added comments and it's self explanatory. Once we are ready with the structure which holds our inputs, we need to have a function which will solve our base problem that is to find the sum of elements of an array. So, lets code that as well

int sumFinder(int *input, int terms)
{
    int sum = 0;
    for(int i = 0 ; i < terms ; i++)
         sum += input[i];
    return sum;
}
So, our base function is ready which takes the input of an array and the number of terms in the array, finds sum and returns the sum obtained.
We still don't have a function which passes test cases to our base function. Let's code that as well.

void testCases()
{
    int result;
    for(int i = 0 ; i < 4 ; i++)      // for passing 4 test cases
    {
         result = sumFinder(testVals[i].input,testVals[i].terms);  // sending the values
         if(result == testVals[i].output)    // checking the obtained result
             printf("PASSED\n");
         else
             printf("FAILED\n");
    }
}
so our testCases() is pretty powerful which passes all the test cases 1 by 1 and even checks whether we have arrived to a correct solution or not, hence all we need to do is to fill in the structure with as many test cases you like and remaining processing is done by the code.
Yeah, we are missing our main function. Lets see the complete code together,

#include "stdio.h"

struct test
{
    int input[10];    // involves your test case arrays
    int terms;         // the number of term in your array
    int output;        // the output which you are expecting
} testVals[4] = {   // these are your test cases you can add as many you like (4 here)
                            {{1,2,3,4,5,6,7,8,9,10} , 10, 55},  // initializing input, terms, expected output
                            {{2,4,6,8} , 4, 20},
                            {{3,6,9} , 3,  18},
                            {{1,2,3,4,5} , 5, 15}
                       };

int sumFinder(int *input, int terms)
{
    int sum = 0;
    for(int i = 0 ; i < terms ; i++)
         sum += input[i];
    return sum;
}

void testCases()
{
    int result;
    for(int i = 0 ; i < 4 ; i++)      // for passing 4 test cases
    {
         result = sumFinder(testVals[i].input,testVals[i].terms);  // sending the values
         if(result == testVals[i].output)    // checking the obtained result
             printf("PASSED\n");
         else
             printf("FAILED\n");
    }
}

int main()
{
   testCases();
   return 0;
}
So that's the complete code which looks huge but as I said its very good practice as you just need to add more test specs and every other thing is dealt. The same practice can be used for other codes as well, you just need to change the things you pass from structure, your result checker. (you can use a separate function for checking as well) that's all for now! If you have any questions, add comments 😀
thankksss these are very help ful

Share this content on your social channels -