Sunday, April 8, 2012

C tutorial

Introduction of C
C is programming language developed in the at AT and Tee Bell Laboratories of USA in 1972's. It was designed and developed by man named is Dennis Richte. C is so popular because it reliable and simple and easy to use, with the help of C language new languages are born known as C++, Java, C# and many other languages.
Learning in C--( Alphabets, symbols ,digits)--(constant, variables, keywords)--(Instructions)--(Progams)
Alphabets are : A,B,C.. Z.
Symbols: ~,@,#,$,%,^,&,*,(),_, etc. these are also called special symbols.
Digits: 1,2,3,4,5,6,7,8,9,0.
History Of C
Before using C we use language which is known as B, now what is B: it was on Interpreter based and had performance drawbacks.
So Dennis Ritchie was developed languages known as C in 1972’s. And it was famous as Mother Language of the computer system. It was based on compiler based
Strong Point as compare to B : In C language Compiler (Translator) compiles the whole source code to Machine code where as interpreter read the source code line by line or step by step.

Features of C
1. C language is the structured programming language because it has some standards.
2. Code reusability means we can use the code from environment to other environment.
3. Built in type float, int etc expressions, operators.
4. Syntax for decision control.
5. It has some libraries which pre is defined.(preprocessors).
6. File organization (.c, .cpp etc)


A sample of C Program
#include // Preprocessor
main () // main function
{ // opening the brackets
Printf(“Hello”);
} // close the brackets.
Advantages Of C
1. C is a small , efficient ,powerful and flexible language
2. C is close to computer H/W (architecture).
3. C is standardized, making it more portable compare to other languages.
4. It contains libraries.
5. Many other languages borrow from Csyntax for ex: Java, java script, perl.
6. UNIX was written in C.

Disadvantages of C

1. C is designed for professional users.
2. C was not able to automatic checking compare other languages.
3. C does not support modern concept like OOP’s and multithreading.
Data Types In C
Mainly there are two types of data types:
1. Simple or primivitive.
2. Compound or structured or derived.
An primitive data is fundamental unit of information which cannot be broken down further.
Simple: integers, floats, characters, pointers.
Derived data is made up of one or more simple data items.
Compound : arrays, structures, unions


Integers in C
Integers stores numeric value without a decimal point in the system memory.
Types Bytes required
Short int 2
Int 4
Long int 4
Floats in C
It stores numeric values with decimal point in the system memory.
Types Bytes required
Float 4
Double 8
Long double 8
Characters in C
Characters is data type which stores an element of machine character set.
The character set is used is usually ASCII set, it is denoted by char. It takes only one byte. Also singed and unsigned both occupy one byte but having different ranges.
The primary data type themselves could be of several types. for example Character char could be Unsigned char. or Signed char.The values stores in the given integer varaibles will always be bepositive. for example we can declare a variables to be unsigned.
unsigned int num_student,
The range of integer values is -32768 to +32767 value s for a 16 bit OS to range 0 to 65535.char ch =A; where ASCII value of A is 65.


Characters Types, Size in Bytes and Range
Type Name Bytes Range
------------- 16 bit system -------------
char 1 -128 to 127
signed char 1 -128 to 127
unsigned char 1 0 to 255
short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
int 2 -32,768 to 32,767
unsigned int 2 0 to 65,535
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
float 4 3.4E+/-38 (7 digits)
double 8 1.7E+/-308 (15 digits)
long double 10 1.2E+/-4932 (19 digits)

------------- 32 bit system -------------
char 1 -128 to 127
signed char 1 - 128 to 127
unsigned char 1 0 to 255
short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
float 4 3.4E+/-38 (7 digits)
double 8 1.7E+/-308 (15 digits)
long double 10 1.2E+/-4932 (19 digits)

=============
What is Variables?
A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer.
For ex: int a =10; // initialization
int a // declaration
Operators in C Operators are:
1. Arithmetical operators
2. Logical operators
3. Relational operators
4. Bitwise operator
5. Shift operators
Arithmetic operators: These operators are used for the for mathematical expression like (Addition ‘+’, Subtraction ’-’ , Multiplication ‘*’ , Division ’/’, Modulus ‘%’) addtion is used to two or more than two expression, same as subtraction is used to find the diffrence,etc. But there is diffrence between division and modulo i.e, modulo always gives the remainder.
for example: 7%2 then it gives modulo 1 because remainder is1.

Logical Operator:
&&-------------Logical And (a>b&& x==10)
||-------------logical OR (a=y)Not exp.evaluates values of x neither greater than or equal to y)
Assignment operator: (x=a+b;) means value of (a+b) is stores in x.
Bitwise operator: (a: 100101 ~a: 011010)
Shift operator: These are of two types –
a) Right shift(a>>L)
b) Left shift (a<
main()
{
int num1 ,num2;
printf(“enter two integers”);
scanf(“%d%d,&num1&num2”);
if (num1 ==num2)
printf(“%d is equalto %d”,num1,num2);
if (!num1 ==num2)
printf (“%d is not equals to %d”,num1,num2);
if(num1>num2)
printf(“”%d is greater than %d,num1,num2);
if (num1=num2)
printf(“”%d is greater than equal to %d,num1,num2);
Return 0;
}


===============

Different loops
1. for loop(int i=4;i<,=4;i++) 2. while loop 3. do while loop a) all loops use same logical(true /false) b) stop While loop: while(something is true) { (body of program) } If the loop condition is not true then at the beginning loop never executed do while loop: do while loop is always executed once.do while loop statement allows you to execute code block in loop body at least one. syntax: 1. do { 2. // statements 3. } while (expression); do{loop body} While loop(loop condition) Void main { do{ printf(“hello world”); } while (4<1); } for example using do while loop statement 1. #include
2. void main(){
3. int x = 5;
4. int i = 0;
5. // using do while loop statement
6. do{
7. i++;
8. printf("%d\n",i);
9. }while(i < x); 10. 11. } The program output 1 2 3 4 5 For Loop Example Using C For example: Void main() { int p,n,count; float r, si; for (count =3;count <=3;count=count ++ ) { printf (“enter the value of p,n,r”); scanf(“%d%d%f”,&p,&n,&r); si =(p*n*r)/100; printf(“simple interest =%f”,si); } getch(); } nesting for loop: void main() { int r ,c,sum; for(r =1;r<=3;r++) { for (c=1;c=2;c++) { sum =r+c; printf(“r=%d,c=%d,sum=%d\n”,r,c,sum); } } } Continue Statement continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions. Void main () { int r ,c; for(r=1;r<=10;r++) { if (r==5) Continue; else printf(“r=%d,\n”,r); } getch(); } Break statement: break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately. Void main() { int a; for (a=1;a<=10;a++) { if (j==5) Break; else printf(“%d\n”,a); } Printf(“hello”) // control pas here getch(); } Switch statement The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. Switch statement is used to switch the multiple 1. switch(expression){ 2. case value1: /* execute unit of code 1 */ 3. break; 4. case value2: /* execute unit of code 2 */ 5. break; 6. ... 7. default: /* execute default action */ 8. break; 9. } Syntax: switch (integer expression) case 1: do this; case2: do this; //default :do this; } For ex: Write a program for calculator using do while loop #include// these are header files
#include// these are header files
void main() // main function compiler read from main
{
int a,b,C,R; // take a variables int type
char rep='y';
do{
printf("\nCalculator\n"); // printf is a function ,using for display a message
printf("1.addition\n");
printf("2.sutraction\n");
printf("3.multiplication\n");
printf("4.division\n");
printf("enter the value of a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
printf("enter your choice");
scanf("%d",&C);
switch(C){
case 1:R=a+b;
printf("\nresult is%d",R);
break;
case 2:R=a-b;
printf("\nresult is%d",R);
break;
case 3:R=a*b;
printf("\nresult is%d",R);
break;
case 4:R=a/b;
printf("\nresult is%d",R);
break; // if valid then then break
default:
printf("\ncondition is invalid");
}
printf("\ndo you want to continue(y/n):");
scanf("%c",&rep);
}while(rep!='n'); //printf("do you want to continue");
getch(); } // scanf("%c",&rep);


Arrays Array by definition is a variable that hold multiple elements which has the same data type.Array is variables that hold multiple elements which has same data type.
An array is a multi element box, uses an indexing system
Declaring the array: We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name.
Name;
Type of array
Number of element "data type array name[size];"
There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer.We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].
Initializing the array: It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name.
int list[5]={2,3,4,5,6} OR int list[5] = {2,1,3,7,8};
Character arrays: char string1[]=”first”;, "Here ,we using char string and its array size is six."
char string[]={‘f’,’g’,’t’,’y’,’u’,’I’,’\0’}; // \0 null character terminating the string.
Passing the array To pass an array argument in a function specifies the name of array to pass without any bracket.
int myarray[24];
myfunction(my array,24).
• array usually pass to the function
• array using call by refrence
• function knows where the array stored
passing array element:
• using call by value
• pass subscripted name (ex: myarray[5]) to function.

Function prototype: void modify array (int b[],int array size);
Parameter name may be optional.
int b[] may be int[]
int array size may be int


Multidimensional Array: An array with more than one index value is called a multidimensional array. All the array above is called single-dimensional array. To declare a multidimensional array you can do follow syntax
data_type array_name[][][];
The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows:
1. int matrix[3][3];
Initializing Multidimensional Arrays
You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array:

1. int matrix[3][3] =
2. {
3. {11,12,13},
4. {21,22,23},
5. {32,31,33},
6. };
Two dimensional arrays
Multidimensional array have two or more than indexs values which specify the element in the array. i.e., multi[i][j].
Where [i] specify row and [j] specify column
Declaration and calculation:
int a[10][10];
int b[2][2]; // int b [2][2]={{0,1},{2,3}}
Sum = a[10][10]+b[2][2]


#include
void main()
{
const int size = 5;
int list[size] = {2,1,3,7,8};
int* plist = list;
// print memory address of array elements
for(int i = 0; i < size;i++) { printf("list[%d] is in %d\n",i,&list[i]); } // accessing array elements using pointer for(i = 0; i < size;i++) { printf("list[%d] = %d\n",i,*plist); /* increase memory address of pointer so it go to the next element of the array */ plist++; . } } Here is the output list[0] is in 1310568 list[1] is in 1310572 list[2] is in 1310576 list[3] is in 1310580 list[4] is in 1310584 list[0] = 2 list[1] = 1 list[2] = 3 list[3] = 7 list[4] = 8 You can store pointers in an array and in this case we have an array of pointers. " int *ap[10];" What is function? A fuction is a self contained block of statement that perform a coherent taskof some kind. main() { message(); printf(“hi”) } message() { printf(“smile ”) } Write Any C program at least one function If a program contain only one function , it must be main() If a program contain more than one function then these can be contain in main(). There is no limit on number that might be present in a C program Each function in a program is called sequence specified by the function calls in main(). A function can be called from other function but can not be defined in the other function. There are two types of function : a) library function(printf() ,scanf()). b) User defined (my() ). Passing the values between the function : main() { int a ,b,c,sum; printf(“enter the values ”); scanlf(“%d%d%d”,%a,%b,%c); sum=calsum(a,b,c);// actual argu./calling function printf(“\nsum=%d”,sum); } Callsum(x,y,z)// called function int x,y,z; { Int d; D=x+y+z; return(d); } // a function can be return only one value at a time WHAT IS A REGISTER VARIABLE? A computer can keep data in a register or in memory. A register is much faster in operation than memory but there are very few registers available for the programmer to use. variables are to be stored in a register in order to speed up the execution of the program.compiler probably allows you to use one or more register variables and will ignore additional requests if you request more than are available. WHAT IS PROTOTYPING? A prototype is a model of a real thing and when programming in ANSI-C,ability to define a model of each function for the compiler. The compiler can then use the model to check each of your calls to the function and determine if you have used the correct number of arguments in the function call and if they are of the correct type. By using prototypes, the compiler do some additional error checking. The ANSI standard for C contains prototyping as part of its recommended standard. Every ANSI-C compiler will have prototyping available. What is pre-processor? The pre-processor is executed just prior to the execution of the compiler. It's operation is transparent to you but it does a very important job. It removes all comments from the source and performs a lot of textual substitution based on your code, passing the result to the compiler for the actual compilation of your code. How to use the function Before using a function we should declare the function so the compiler has information of function to check and use it correctly. The function implementation has to match the function declaration for all part return data type, function name and parameter list. When you pass the parameter to function, they have to match data type, the order of parameter. Here is an example of using function. #include
/* functions declaration */
void swap(int *x, int *y);
void main()
{
int x = 10;
int y = 20;
printf("x,y before swapping\n");
printf("x = %d\n",x);
printf("y = %d\n",y);
// using function swap
swap(&x,&y);
printf("x,y after swapping\n");
printf("x = %d\n",x);
printf("y = %d\n",y);
}
/* functions implementation */
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
Here is the output
x,y before swapping
x = 10
y = 20
x,y after swapping
x = 20
y = 10

Benefit of using function
• C programming language supports function to provide modularity to the software.
• One of major advantage of function is it can be executed as many time as necessary from different points in your program so it helps you avoid duplication of work.
• By using function, you can divide complex tasks into smaller manageable tasks and test them independently before using them together.
• In software development, function allows sharing responsibility between team members in software development team. The whole team can define a set of standard function interface and implement it effectively.

Pointer in C C pointer is a memory address. for example:
1. int x = 10;
You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator & before it.
printf("memory address of x is %d\n",&x);
and in my PC the output is
memory address of x is 1310588
To access memory address of variable x you have to use pointer. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows:

1. int *px;
Now pointer px to points to memory address of variable x, you can use address-of operator (&)
1. int *px = &x;
you can change the content of variable x for example you can increase, decrease x value :
1. *px += 10;
2. printf("value of x is %d\n",x);
3. *px -= 5;
4. printf("value of x is %d\n",x);
the output indicates that x variable has been change via pointer px.
value of x is 20
value of x is 15
It is noted that the operator (*) is used to dereference and return content of memory address.
In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address. In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows:

int c = 10;
int c2 = 20; .
/* define a pointer and points to an constant integer.
pc can point to another integer but you cannot change the
content of it */
const int *pc = &c;
/* pc++; */ /* cause error */
printf("value of pc is %d\n",pc);
pc = &c2;
printf("value of pc is %d\n",pc);
/* define a constant pointer and points to an integer.
py only can point to y and its memory address cannot be changed
you can change its content */
int y = 10;
int y2 = 20;
int const *py = &y;
*py++;/* it is ok */
printf("value of y is %d\n",y);
/* py = &y2; */ /* cause error */
output
value of pc is 1310580
value of pc is 1310576
value of y is 10

Introducing to C structure
In some programming contexts, you need to access multiple data types under asingle name for easy manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member.
Defining structure
To define a structure, you can use struct keyword.struct struct_name{ structure_member };
The name of structure is followed the rule of variable name.
For example
1. struct address{
2. unsigned int house_number;
3. char street_name[50];
4. int zip_code;
5. char country[50];
6. };
It contains house number as an positive integer, street name as a string, zip code as an integer and
country as a string.
Declaring structure
The above example only defines an address structure without create any instance of it.
To create or declare a structure you have two ways:
The first way is declare a structure follows by structure definition like this :
1. struct struct_name {
2. structure_member;
3. ...
4. } instance_1,instance_2 instance_n;
In the second way you can declare your structure instance at a different location in your source code after
structure definition.
Here is structure declaration syntax :
struct struct_name instance_1,instance_2 instance_n;
Complex structure Structure can contains arrays or other structures so it is sometimes called complex structure.
For example address structure is a complex structure. We can define a complex structure which contains
address structure as follows:
1. struct customer{
2. char name[50];
3. structure address billing_addr;
4. structure address shipping_addr;
5. };


Accessing structure member
To access structure members we can use dot operator (.) between structure name and structure member name as follows: structure_name.structure_member For example to access street name of structure address we do as follows: 1. struct address billing_addr; 2. billing_addr.country = "US"; If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure. 1. struct customer jack; 2. jack.billing_addr.country = "US";
Initializing structure
C programming langauge treats a structure as a custom data type therefore you can initialize a structure like a variable.
1. struct product{
2. char name[50];
3. double price;
4. } book = { "C programming language",40.5};
In above example, we define product structure, then we declare and initialize book structure with its name and price.
Structure and pointer
A structure can contain pointers as structure members and we can create a pointer to a structure as follows:
1. struct invoice{
2. char* code;
3. char date[20];
4. };
5.
6. struct address billing_addr;
7. struct address *pa = &billing_addr;

Shorthand structure with typedef keyword
To make your source code more concise, you can use typedef keyword to create a synonym for a structure. This is an example of using typedef keyword to define address structure so when you want to create an instance of it you can omit the keyword struct 1. typedef struct{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. } address; 7. 8. address billing_addr; 9. address shipping_addr;
Copy a structure into another structure
One of major advantage of structure is you can copy it with = operator. The syntax as follows
1. struct_intance1 = struct_intance2
be noted that some old C compilers may not supports structure assignment so you have to assign each member variables one by one.
Structure and sizeof function
sizeof is used to get the size of any data types even with any structures. For example
1. #include


2.



3. typedef struct __address{



4. int house_number;// 4 bytes



5. char street[50]; // 50 bytes



6. int zip_code; // 4 bytes



7. char country[20];// 20 bytes



8.



9. } address;//78 bytes in total



10.



11. void main()




12. {



13. // it returns 80 bytes



14. printf("size of address is %d bytes\n",sizeof(address));



15. }


Example Of Structure
You will never get the size of a structure exactly as you think it must be. The sizeof function returns the size of structure larger than it is because the compiler pads struct members so that each one can be accessed faster without delays. So you should be careful when you read the whole structure from file which were written from other programs.
example of using C structure
#include
typedef struct _student{
char name[50];
unsigned int mark;
} student;
void print_list(student list[], int size);
void read_list(student list[], int size);
void main(){
const int size = 3;
student list[size];
read_list(list,size);
print_list(list,size); }
void read_list(student list[], int size)
{
printf("Please enter the student information:\n");
for(int i = 0; i < size;i++){ printf("\nname:"); scanf("%S",&list[i].name); printf("\nmark:"); scanf("%U",&list[i].mark); } } void print_list(student list[], int size){ printf("Students' information:\n"); for(int i = 0; i < size;i++){ printf("\nname: %s, mark: %u",list[i].name,list[i].mark); } } Here is program's output Please enter the student information: name:Jack mark:5 name:Anna mark:7 name:Harry mark:8 Students' information: name: J, mark: 5 name: A, mark: 7 name: H, mark: 8 Dynamic Memory Allocation Introduce to dynamic memory allocation In some programming contexts, you want to process data but dont know what size of it is. For example, you read a list of students from file but dont know how many students record there. specify the enough maximum size for the the array but it is not efficient in memory management. C provides you a powerful and flexible way to manage memory allocation at runtime. It is called dynamic memory allocation. Dynamic means you can specify the size of data at runtime. C programming language provides a set of standard functions prototype to allow you to handle memory effectively. With dynamic memory allocation you can allocate and free memory as needed.Getting to know the size of data Before allocating memory, we need to know the way to identify the size of each data so we can allocate memory correctly. We can get the size of data by using sizeof() function. sizeof() function returns a size_t an unsigned constant integer. For example: 1. sizeof(int); It returns 4 bytes in typical 32 bit machines. . #include
typedef struct __address{
int house_number;
char street[50];
int zip_code;
char country[20];
} address;
void main()
{
printf("size of int is %d byte(s)\n",sizeof(int));
printf("size of unsigned int is %d byte(s)\n",sizeof(unsigned int));
printf("size of short is %d byte(s)\n",sizeof(short));
printf("size of unsigned short is %d byte(s)\n",sizeof(unsigned short));
printf("size of long is %d byte(s)\n",sizeof(long));
printf("size of char is %d byte(s)\n",sizeof(char));
printf("size of float is %d byte(s)\n",sizeof(float));
printf("size of double is %d byte(s)\n",sizeof(double));
printf("size of address is %d byte(s)\n",sizeof(address));
}
output:
size of int is 4 byte(s)
size of unsigned int is 4 byte(s)
size of short is 2 byte(s)
size of unsigned short is 2 byte(s)
size of long is 4 byte(s)
size of char is 1 byte(s)
size of float is 4 byte(s)
size of double is 8 byte(s)
size of address is 80 byte(s)

str1.shtml str1.shtml


Allocating memory

We use malloc() function to allocate memory. void * malloc(size_t size);
malloc function takes size_t as its argument and returns a void pointer. The void pointer is used because it can allocate memory for any type. The malloc function will return NULL if requested memory couldnt be allocated or size argument is equal 0. Here is an example of using malloc function to allocate memory:
1. int* pi;
2. int size = 5;
3. pi = (int*)malloc(size * sizeof(int));
sizeof(int) return size of integer (4 bytes) and multiply with size which equals 5 so pi pointer now points to the first byte of 5 * 4 = 20 bytes memory block. We can check whether the malloc function allocate memory space is successful or not by checking the return value.
1. if(pi == NULL)
2. {
3. fprintf(stderr,"error occurred: out of memory");
4. exit(EXIT_FAILURE);
5. }
Beside malloc function, C also provides two other functions which make convenient ways to allocate memory:
1. void *calloc(size_t num, size_t size);
2. void *realloc(void *ptr, size_t size);
calloc function not only allocates memory like malloc but also allocates memory for a group of objects which is specified by num argument.
realloc function takes in the pointer to the original area of memory to extend and how much the total size of memory should be.
Freeing memory
When you use malloc to allocate memory you implicitly get the memory from a dynamic memory pool which is called heap. The heap is limited so you have to deallocate or free the memory you requested when you dont use it in any more. C provides free function to free memory. Here is the function prototype:
1. void free(void *ptr);
You should always use malloc and free as a pair in your program to a void memory leak.
String Definition
C does not have a string type as other modern programming languages. C only has character type so a C string is defined as an array of characters or a pointer to characters.
Null-terminated String
String is terminated by a special character which is called as null terminator or null parameter (/0). So when you define a string you should be sure to have sufficient space for the null terminator. In ASCII table, the null terminator has value 0.
Declaring String
As in string definition, we have two ways to declare a string. The first way is, we declare an array of characters as follows:
1. char s[] = "string";
And in the second way, we declare a string as a pointer point to characters:
1. char* s = "string";
Declaring a string in two ways
looks similar but they are actually different. In the first way, you declare a string as an array of character, the size of string is 7 bytes including a null terminator. But in the second way, the compiler will allocate memory space for the string and the base address of the string is assigned to the pointer variables.
Looping Through a String
loop through a string by using a subscript.
1. // loop through a string using a subscript
2. char s[] = "C string";
3. int i;
4. for(i = 0; i < sizeof(s);i++)
5. {
6. printf("%c",s[i]);
7. }
You can also use a pointer to loop through a string. You use a char pointer and point it to the first location of the string, then you iterate it until the null terminator reached.
1. // loop through a string using a pointer
2. char* ps = s;
3. while(*ps != '\0'){
4. printf("%c",*ps);
5. ps++;
6. }
Passing a String to Function
A formal way to pass a string to a function is passing it as a normal array.