FoodForFutureGeeks

Wednesday, 4 April 2012

Structures, Structure pointers

A structure  is a user defined datatype, it is a collection of heterogeneous data types that are supported by default. It is defined by using the keyword struct, the definition has to be terminated by a semi colon.
ex:

struct student
{
char name[15];
int age;
};
structure variables/members cannot be initialized or assigned values during structure definition.

Declaring and accessing structure variables:

structure variables can be declared just like normal integer or float variables,by mentioning the structure name followed by variable name.


#include<stdio.h>
#include<conio.h>
#include<string.h>
//structure definition

struct student
{

char name[15];
int age;
};

void main()
{
//declaring a structure variable
student s;
//accessing the structure members using . operator
strcpy(s.name,"harish");
s.age=15;
printf("student name:%s",s.name);
printf("\n student age is:%d",s.age);
_getch();

}
Structure members can be accessed by using the dot operator as shown in the sample program.

Pointer to a structure:

whenever we are working with structure variables it may be required to pass the structure variables by reference to other functions for performing operations, in such cases we need pointers to structures.Structure pointers can be declared just like ordinary pointers by using * symbol after the structure name or before variable name.
ex: student* s;

Accessing structure members from pointer:

The arrow operator(->) is used to access the structure memebers from a structure pointer, in case of ordinary structure variables we have to use the dot(.) operator to access the structure members but for structure pointer arrow operator has to be used.
ex: s->name;

Sample program to illustrate structure pointers:


#include<stdio.h>
#include<conio.h>

//structure declaration
struct student
{
char name[15];
float marks_sub1;
float marks_sub2;
float marks_sub3;
float average;
float percentile;
};

//user defined function declaration

void setData(student* temp);
void calcAvg(student* temp);
void printData(student* temp);

//main function

void main()
{

int i;

//declare an array of student type variables
student s[5];

for( i=0;i<5;i++ )
{
printf("\nenter the student %d details",i);
//set data collects the student information
setData(&s[i]);

//calculates the average
calcAvg(&s[i]);

}

for( i=0;i<5;i++ )
{

printf("\nstudent %d details",i);
//call print data to print the student details
printData(&s[i]);
}

getch();

}

//function to print data
void printData(student* temp)
{
printf("\n\n***************************************");
printf("\nname:%s",temp->name);
printf("\nsubject1 marks:%f",temp->marks_sub1);
printf("\nsubject2 marks:%f",temp->marks_sub2);
printf("\nsubject3 marks:%f",temp->marks_sub3);
printf("\nAverage marks:%f",temp->average);
printf("\n**************************************");
}

//this function calculates the average
void calcAvg(student* temp)
{
temp->average=(temp->marks_sub1+temp->marks_sub2+temp->marks_sub3)/3;
}

//this function collects the input data
void setData(student* temp)
{

printf("\nenter the name:");
scanf("%s",temp->name);
printf("\n enter the subject1 marks:");
scanf("%f",&temp->marks_sub1);
printf("\n enter the subject2 marks:");
scanf("%f",&temp->marks_sub2);
printf("\n enter the subject3 marks:");
scanf("%f",&temp->marks_sub3);
}


C program using Structures to read and display Student details


#include<stdio.h>
#include<conio.h>

//structure declaration
struct student
{
char name[15];
float marks_sub1;
float marks_sub2;
float marks_sub3;
float average;
};

//user defined function declaration

void setData(student* temp);
void calcAvg(student* temp);
void printData(student* temp);

//main function

void main()
{

int i;

//declare an array of student type variables
student s[5];

for( i=0;i<5;i++ )
{
printf("\nenter the student %d details",i);
//set data collects the student information
setData(&s[i]);

//calculates the average
calcAvg(&s[i]);

}

for( i=0;i<5;i++ )
{

printf("\nstudent %d details",i);
//call print data to print the student details
printData(&s[i]);
}

getch();

}

//function to print data
void printData(student* temp)
{
printf("\n\n***************************************");
printf("\nname:%s",temp->name);
printf("\nsubject1 marks:%f",temp->marks_sub1);
printf("\nsubject2 marks:%f",temp->marks_sub2);
printf("\nsubject3 marks:%f",temp->marks_sub3);
printf("\nAverage marks:%f",temp->average);
printf("\n**************************************");
}

//this function calculates the average
void calcAvg(student* temp)
{
temp->average=(temp->marks_sub1+temp->marks_sub2+temp->marks_sub3)/3;
}

//this function collects the input data
void setData(student* temp)
{

printf("\nenter the name:");
scanf("%s",temp->name);
printf("\n enter the subject1 marks:");
scanf("%f",&temp->marks_sub1);
printf("\n enter the subject2 marks:");
scanf("%f",&temp->marks_sub2);
printf("\n enter the subject3 marks:");
scanf("%f",&temp->marks_sub3);
}

Monday, 2 April 2012

Programming approaches in C,C++

Basically there are two programming approaches in C, C++:
  1. Top Down Approach.
  2. Bottom Up Approach.

Top Down Approach:

This approach is known as top down as the main function is defined at the top, other user defined functions are defined below it.
ex:
//top down approach
#include
//function declaration
int add(int,int);
int sub(int,int);
//main function definition
void main()
{
int sum=0,difference=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);
//call to sub function
difference=sub(var1,var2);
printf("sum is:%d",sum);
printf("difference is:%d",difference);
}
//user defined functions are defined below main
int add(int value1,int value2)
{
return value1+value2;
}
int sub(int value1,int value2)
{
return value1-value2;
}

so when a function is called, control goes from top to bottom and returns to top again, ie from main function to the user defined function and back to main function again.


Bottom up approach:

This approach is known as bottom up as the main function is at the bottom and user defined function definitions are at the top.
ex:
//bottom up approach
#include
//user defined functions are defined above main
int add(int value1,int value2)
{
return value1+value2;
}
int sub(int value1,int value2)
{
return value1-value2;
}
//main function definition
void main()
{
int sum=0,difference=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);
//call to sub function
difference=sub(var1,var2);
printf("sum is:%d",sum);
printf("difference is:%d",difference);
}

so when a function is called, the control goes from bottom to top and returns to bottom again ie from main function to the user defined function and back to main function again.

Functions

function is an independent block of code, that is designed to carry out a specific task, it can accept certain values as input or it can have no input, it may return the results after completion or it may not.

General format of a  C function:

Returntype function name(formal arguments list)
ex: void add(int var1,int var2), void print(void);
sample program:
#include 
int add(int,int);
void main()
{
int sum=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);//var1 var2 are the actual parameters
printf("sum is:%d",sum);
}
int add(int value1,int value2)//value1,value2 are called as formal parameters
{
return value1+value2;
}//returns the sum

Return Type:

The return type indicates datatype of the value returned by the function on completion of its execution, if a function doesn't return any value then its return type will be void.
ex:
void add(int var1,int var2) ; this function does not return anything.
int add(int var1,int vbar2);  this function returns an integer value.
similarly a function can have return types as float,char etc.

Formal arguments/parameters:

formal arguments are the variables in called function,that accepts the value passed from the calling function.
ex: void add(int var1,int var2 ) here var1,var2 are the formal parameters.

Actual arguments/parameters:

actual arguments are the variables passed from the calling function like main in the sample program.

Function declaration/prototyping a function:

function declaration  is used to inform the compiler about the existence of a function body after the main, this is done by just defining the function signature ie the return type, function name, formal argument types/formal arguments.Since C is a top down programming language(read article on programming approaches c,c++), this should be the ideal approach ie all functions should be declared before main(), definition should be after the main().
ex:
//top down approach
#include 
//function declaration or prototype
int add(int,int);
void main()
{
int sum=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);//var1 var2 are the actual parameters
printf("sum is:%d",sum);
}
//function definition
int add(int value1,int value2)//value1,value2 are called as formal parameters
{
return value1+value2;
}//returns the sum

Calling a function:

A function can be called by using its name and by passing the arguments required in parenthesis.
ex:
    sum=add(10,20);
    sub(5,10); etc
the values passed should be of same datatype as mentioned in the declaration or definition.
if the function returns some value then we can accept the returned value by using a variable of same type.

Function definition:

a function definition has the actual code/instructions that enables the function to perform a specific task.ex: performing addition ,subtraction,calculate the simple interest etc.

Bottom up programming:

ex :read article programming approaches c,c++ in general programming
//bottom up approach
#include 
//function definition
int add(int value1,int value2)//value1,value2 are called as formal parameters
{
return value1+value2;
}//returns the sum
void main()
{
int sum=0,var1=0,var2=0;
printf("enter two variables to calculate the sum:\n");
scanf("%d%d",&var1,&var2);
//call to add function, main function is the calling function
sum=add(var1,var2);//var1 var2 are the actual parameters
printf("sum is:%d",sum);
}








Sunday, 1 April 2012

Common Terminologies of C

Token:

A token is the smallest divisible unit of a c program, while processing a C program, the compiler divides the program into numerous meaningful tokens.Token may be a keyword, variable or operator.

ex:
int a; here there are three tokens int,a,;

Keyword:

keywords are those words which have a pre defined meaning, this meaning cannot be changed by the programmer.
ex:
int means an integer datatype, the programmer cannot change this meaning.
void this means the return type is null etc.

Variable:

a variable is the name given to a programmer defined value, the value can be used with this name, as the name suggests the value of a variable can change during the process of execution of a program.
ex:
int value=10;
printf("%d",value);

Operators:

operators are the are used to perform certain operations on variables, there are two types of operators:
  1. Unary operators.
  2. Binary operators.

Unary operators:

unary operators act upon a single variable/operand.
ex:


increment operators:
pre increment ++i; increases the value of i by 1
post increment i++; increments the value of i by 1 fter the execution of instruction.

Decrement operators:

pre decrement --i; decreases the value of i by 1
post decrement decreases the value of i by 1 after the execution of instruction.

Note: evaluate expressions like a+(++b); a+b++; ,a-k++;a-++k and see results in the below program:void main(){int a=0,k=10;printf("%d",a-k++);}

Binary Operators:

binary operators are those which can work on two operands/variables:ex:a+b, a-b

+,-,*,/ are the commonly used binary operators.
+:perform addition.
-:perform subtraction.
*:perform multiplication.
/:perform divison.


Intersting binary operators:

(<<) left shift:

shifts the given variable by given no places to left.shifts the given variable by given no places to left.ex:5<<2 =20 ie it is multiplied by 2power2.10<<2=40 ie 10 is multiplied by 4.
(>>)Right Shift:

shifts the given variable by given no of places to right.ex:4>>2=1 ie 4 is divide by 2square8>>3=1 ie 8 is divided by 2 cube.

Logical Operators:

bitwise and: &

performs the and operation after converting the variables to binary:ex:int k=1&0 result k=0if used on boolean variables it acts as logical and.

bitwise or: | pipe symbol, above enter key usually:

performs or operation after converting to binary
ex:int k=1|0; result k=1;if used on boolean variables it acts as logical or.
Logical And &:

should be used on boolean values or expressions,returns true if both right hand side and left hand side of the expression are true else it return false.ex:if(k>0 && i=10){{}}if will be executed if both k>0 and i=10.if used on variables acts as bitwise and.
Logical OR || :

should be used on boolean values or expressions,returns true if either right hand side orleft hand side of the expression are true, if both are false it returns false.ex:if(k>0 || i=10){}if will be executed if either k>0 or i=10.if used on variables acts as bitwise or.

Special Bitwise Operator( ?:) :
(<<) left shift:

var=(condition)?exp1:exp2
ex:evaluates the condition if condition is true, var is assigned the value mentioned in exp1, if condition is false var is assigned value mentioned in exp2.

k=(a>1)?0:10;

var=(condition)?exp1:exp2


ex:evaluates the condition if condition is true, var is assigned the value mentioned in exp1, if condition is false var is assigned value mentioned in exp2.
k=(a>1)?0:10;




sample program:

#include<stdio.h>
void main()
{
int a=1,k=0;
k=(a&gt;0)?10:0;
printf("%d",k);
}
here if a is greater than 0, k is assigned 10 else k is assigned value 0 as per expression.













 



Structure Of a C Program

A typical c program has the following structure:
  1. Pre Processor Directives
  2. Declaration Of Global Variables
  3. Function Prototype
  4. Main Function
  5. User Defined Function definition.
Example:
//pre processor directive
#include<stdio.h>
//declaration of global variables
int k=0;
//function prototype void add(int,int); //main function void main() { int a=10; add(a,k); } //User defined Function definition void add(int value1,int value2) { printf("sum:%d",value1+value2); }

Pre Processor Directives:


These are the directives to the compiler, they are followed while compiling the code.
ex:

1.#include<****.h>:directive to include the header file during 
compilation

2.#define PI 3.1419  directive defining the value of constant PI,
wherever PI is used it will be replaced by 3.1419


Function Prototype:

A function prototype is nothing but signature of function.(for more info read article on functions) 
ex:
int add(int,int);
It informs the compiler about the existence of a function add in the program.(whose body may be defined after the main function.)

Declaration Of Global Variables:

Global variables are those variables which can be used/ whose scope is throughout the program, ie these variables are common to main function and user defined functions.These variables have to be declared before the main function.

Main Function:

Every C program should have a main function, the execution of a program starts from main function.
However the we can call all other functions from a main function.(Read article on functions for more info on calling a function.).

User Defined Function Definition:

user defined function definition contains the logic for user defined functions.
ex:
void add(int var1,int var2)
{
printf("Sum:%d",var1+var2);
}
this function adds the two variables passed and prints the results on the computer screen.
similarly we can define custom functions to perform tasks desired by us.


Introduction to C


C language is one of the earliest & most used, high level programming languages, it was invented by Dennis Ritchie in AT&T Bell labarotaries USA in between 1969&1973.Originally it was designed to create system software on Unix platform, but today apart from being widely used in system software programming, C is also used to build portable applications.
DennisRitchie inventor of C


Dennis Ritchie Supervising coding on old Unix Systems

Sailient Features of C:

  •  Structured Programming language:
The program is compiled by the compiler from top to bottom, the program should be well structured(read article structure of a C program for more details).

  •  High level programming language:
Programming languages are of three types:
  1. Machine level programming, here programming is done in terms of only 0's and 1's.
  2. Assembly level programming,here programming is done by using short instructions 
ex:  add r0,r1,r2
  1. High Level Programming, here the program consists of instructions almost similar to english language.
ex: printf("hello");

  •  Procedure based programming language:
It supports divison of the complex program into individual procedures or modules, each procedure is responsible for carrying out its own task.

  • It is static:
The variables are assigned memory during the time of compilation, the procedure calls are resolved during compile time only.

  • Has well defined Keywords:
Keywords are those words which have a pre defined meaning, this cannot be changed by the programmer.
ex:
printf, scanf, if etc they cannot be used as variable names by programmers.

  • Supports looping, conditional checks:
Loops are used to repeat an instruction or a given set of instructions for a fixed no of times, C supports the for loop, while loop, do while loop.(read article on looping for more details.)
ex.....
for(int i=0;i<5;i++)
printf("this loop prints the statement 5 times");

Conditional checks are used to verify the validity of a particular condition.(read the article on conditional instructions for more details.
ex:
if(x>0)  
.....do something.......