UseTorrent Hackers for You

Saturday 18 January 2014

Basic C Concepts

Filled under:



Array

C Array is a collection of variables belongings to the same data type. You can store group of data of same data type in an array.

·         Array might be belonging to any of the data types
·         Array size must be a constant value.
·         Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
·         It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array.

Example for C Arrays:

        int a[10];       // integer array
        char b[10];   // character array   i.e. string

Types of C arrays:
There are 2 types of C arrays. They are,

1.       One dimensional array
2.       Multi dimensional array
·                     Two dimensional array
·                     Three dimensional array, four dimensional array etc… 

1. One dimensional array in C: 

        Syntax:
data-type arr_name[array_size];

Example:
#include<stdio.h>                                   
int main()
{
    int i;
    int arr[5] = {10,20,30,40,50}; 
    // declaring and Initializing array in C
    //To initialize all array elements to 0, use int arr[5]={0};
    /* Above array can be initialized as below also
       arr[0] = 10;
       arr[1] = 20;
       arr[2] = 30;
       arr[3] = 40;
       arr[4] = 50;
    */

    for (i=0;i<5;i++)
    {
        // Accessing each variable
        printf("value of arr[%d] is %d \n", i, arr[i]);
    }
}

Output                                            
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
 

2. Two dimensional array in C: 

        Two dimensional array is nothing but array of array.
        syntax :
data_type array_name[num_of_rows][num_of_column]           

Example:
#include<stdio.h>
int main()
{
    int i,j;
    // declaring and Initializing array

    int arr[2][2] = {10,20,30,40};
    /* Above array can be initialized as below also
       arr[0][0] = 10;   // Initializing array
       arr[0][1] = 20;
       arr[1][0] = 30;
       arr[1][1] = 40;
    */

    for (i=0;i<2;i++)
    {
       for (j=0;j<2;j++)
       {
          // Accessing variables
          printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
       }
    }
}

Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

String

·         C Strings are nothing but array of characters ended with null character (‘\0’).
·         This null character indicates the end of the string.
·         Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

Example for C string: 

·         char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘\0’}; (or)
·         char string[20] = “bcagroup”; (or)
·         char string []    = “bcagroup”; 

Ø  Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of memory space is allocated for holding the string value.
Ø  When we declare char as “string[]“, memory space will be allocated as per the requirement during execution of the program.

Example:
#include <stdio.h>
int main ()
{
   char string[20] = "bcagroup";
   printf("The string is : %s \n", string );
   return 0;
}

Output:
The string is : bcagroup

C String functions: 

Ø  String.h header file supports all the string functions in C language. All the string functions are given below.

Sr.           String Functions               Descriptions

1              strcat ( )                               Concatenates str2 at the end of str1.
2              strncat ( )                             appends a portion of string to another
3              strcpy ( )                              Copies str2 into str1
4              strncpy ( )                            Copies given number of characters of one string to another
5              strlen ( )                               gives the length of str1.

6              strcmp ( )                             Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2.
7              strcmpi_(.)                          Same as strcmp() function. But, this function negotiates case.  “A” and “a” are treated as same.
8              strchr ( )                               Returns pointer to first occurrence of char in str1.
9              strrchr ( )                             last occurrence of given character in a string is found
10           strstr ( )                                Returns pointer to first occurrence of str2 in str1.
11           strrstr ( )                              Returns pointer to last occurrence of str2 in str1.
12           strdup ( )                             duplicates the string
13           strlwr ( )                               converts string to lowercase
14           strupr ( )                              converts string to uppercase
15           strrev ( )                               reverses the given string

16           strset ( )                               sets all character in a string to given character
17           strnset ( )                            It sets the portion of characters in a string to given character
18           strtok ( )                               tokenizing given string using delimiter


Pointer


·         C Pointer is a variable that stores/points the address of the another variable.
·         C Pointer is used to allocate memory dynamically i.e. at run time.
·         The variable might be any of the data type such as int, float, char, double, short etc. 

Syntax : data_type *var_name;
Example : int *p;  char *p; 

·         Where, * is used to denote that “p” is pointer variable and not a normal variable.

Key points to remember about pointers in C:

·         Normal variable stores the value whereas pointer variable stores the address of the variable.
·         The content of the C pointer always be a whole number i.e. address.
·         Always C pointer is initialized to null, i.e. int *p = null.
·         The value of null pointer is 0.

·         & symbol is used to get the address of the variable.
·         symbol is used to get the value of the variable that the pointer is pointing to.
·         If pointer is assigned to NULL, it means it is pointing to nothing.
·         Two pointers can be subtracted to know how many elements are available between these two pointers.
·         But, Pointer addition, multiplication, division are not allowed.
·         The size of any pointer is 2 byte (for 16 bit compiler).                            

Example:
#include <stdio.h>
int main()
{
        int *ptr, q;
        q = 50; 
        /* address of q is assigned to ptr       */
        ptr = &q;    
        /* display q's value using ptr variable */     

        printf("%d", *ptr);
        return 0;
}

Output:
50

Function

C functions are basic building blocks in a program. All C programs are written using functions to improve re-usability, understandability and to keep track on them. You can learn below concepts of C functions in this section in detail.
1.       What is C function?
2.       Uses of C functions ?
3.       C function declaration, function call and definition with example program
4.       How to call C functions in a program?
·         Call by reference

·         Call by value


1. What is C function?
     A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed by “{  }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program.
2. Uses of C functions:
·         C functions are used to avoid rewriting same logic/code again and again in a program.
·         There is no limit in calling C functions to make use of same functionality wherever required.
·         We can call functions any number of times in a program and from any place in a program.
·         A large C program can easily be tracked when it is divided into functions.
·         The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.
3. C function declaration, function call and function definition:
There are 3 aspects in each C function. They are,
·         Function declaration or prototype  - This informs compiler about the function name, function parameters and  return value’s data type.
·         Function call – This calls the actual function
·         Function definition – This contains all the statements to be executed.
Simple example program for C function:
·         As you know, functions should be declared and defined before calling in a C program.
·         In the below program, function “square” is called from main function.
·         The value of “m” is passed as argument to the function “square”. This value is multiplied by itself in this function and multiplied value “p” is returned to main function from function “square”.
Example:
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );                               
// main function, program starts from here
int main( )              
{
        float m, n ;
        printf ( "\nEnter some number for finding square \n");
        scanf ( "%f", &m ) ;
        // function call
        n = square ( m ) ;                 
        printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x )   // function definition
{
        float p ;
        p = x * x ;
        return ( p ) ;
}
Output
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000
 
4. How to call C functions in a program?
There are two ways that a C function can be called from a program. They are,
1.       Call by value
2.       Call by reference
1. Call by value:
·         In call by value method, the value of the variable is passed to the function as parameter.
·         The value of the actual parameter can not be modified by formal parameter.
·         Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
Note:
·         Actual parameter – This is the argument which is used in function call.
·         Formal parameter – This is the argument which is used in function definition
Example program for C function (using call by value):
·         In this program, the values of the variables “m” and “n” are passed to the function “swap”.
·         These values are copied to formal parameters “a” and “b” in swap function and used.
Example:
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);          
int main()
{
    int m = 22, n = 44;
    // calling swap function by value
    printf(" values before swap  m = %d \nand n = %d", m, n);
    swap(m, n);                        
}
void swap(int a, int b)
{
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
    printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
Output:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
2. Call by reference:
·         In call by reference method, the address of the variable is passed to the function as parameter.
·         The value of the actual parameter can be modified by formal parameter.
·         Same memory is used for both actual and formal parameters since only address is used by both parameters.
Example program for C function (using call by reference):
·         In this program, the address of the variables “m” and “n” are passed to the function “swap”.
·         These values are not copied to formal parameters “a” and “b” in swap function.
·         Because, they are just holding the address of those variables.
·         This address is used to access and change the values of the variables.
Example:
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b); 
int main()
{
    int m = 22, n = 44;
    //  calling swap function by reference
    printf("values before swap m = %d \n and n = %d",m,n);
    swap(&m, &n);         
}
 
void swap(int *a, int *b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
    printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
Output:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22

UDF - User-defined functions
 
Example of user-defined function
Write a C program to add two integers. Make a function add to add integers and display sum in main() function.
/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b);           //function prototype(declaration)
int main(){
     int num1,num2,sum;
     printf("Enters two number to add\n");
     scanf("%d %d",&num1,&num2);
     sum=add(num1,num2);         //function call
     printf("sum=%d",sum);
     return 0;
}
int add(int a,int b)            //function declarator
{            
/* Start of function definition. */
     int add;
     add=a+b;
     return add;                  //return statement of function
/* End of function definition. */  
}                                  
Function prototype(declaration):



Every function in C programming should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
In the above example,int add(int a, int b); is a function prototype which provides following information to the compiler:
1.       name of the function is add()
2.       return type of the function is int.
3.       two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main() function.    

Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked).
Syntax of function call
function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); from main(). This make the control of program jump from that statement to function definition and executes the codes inside that function.

Function definition
Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
                //body of function
}
1. Function declarator
Function declarator is the first line of function definition. When a function is invoked from calling function, control of the program is transferred to function declarator or called function.
Syntax of function declarator
return_type function_name(type(1) argument(1),....,type(n) argument(n)) 
Syntax of function declaration and declarator are almost same except, there is no semicolon at the end of declarator and function declarator is followed by function body.
In above example, int add(int a,int b) in line 12 is a function declarator.
2. Function body
Function declarator is followed by body of function which is composed of statements.
Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or  variable) passed from a program to the function.
In above example two variable, num1 and num2 are passed to function during function call and these arguments are accepted by arguments a and b in function definition.
Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int and b should be of type float,i.e., type of argument during function call and function definition should be same.
A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement

return (expression);
          OR
     return;    
For example:
return;
return a;
return (a+b);


In above example, value of variable add in add() function is returned and that value is stored in variable sum in main() function. The data type of expression in return statement should also match the return type of function.

Types of User-defined Functions in C Programming
For better understanding of arguments and return in functions, user-defined functions can be categorised as:
1.       Function with no arguments and no return value
2.       Function with no arguments and return value
3.       Function with arguments but no return value
4.       Function with arguments and return value.
Let's take an example to find whether a number is prime or not using above 4 cateogories of user defined functions.
Function with no arguments and no return value.
/*C program to check whether a number entered by user is prime or not using function with no arguments and no return value*/
#include <stdio.h>
void prime();
int main()
{
    prime();      //No argument is passed to prime().
    return 0;
}
void prime()
{ 
/* There is no return value to calling function main(). Hence, return type of prime() is void */
    int num,i,flag=0;
    printf("Enter positive integer enter to check:\n");
    scanf("%d",&num);
    for(i=2;i<=num/2;++i)
{
        if(num%i==0)
{
             flag=1;
         }
    }
    if (flag==1)
        printf("%d is not prime",num);
    else
       printf("%d is prime",num); 
    }
Function prime() is used for asking user a input, check for whether it is prime of not and display it accordingly. No argument is passed and returned form prime() function.
Function with no arguments but return value
/*C program to check whether a number entered by user is prime or not using function with no arguments but having return value */
#include <stdio.h>
int input();
int main()
{
    int num,i,flag;
    num=input();     /* No argument is passed to input() */
    for(i=2,flag=i;i<=num/2;++i,flag=i)
{
    if(num%i==0)
{
        printf("%d is not prime",num);
        ++flag;
        break;
    }
    }
    if(flag==i)
        printf("%d is prime",num);
    return 0;
}
int input(){   /* Integer value is returned from input() to calling function */
    int n;
    printf("Enter positive enter to check:\n");
    scanf("%d",&n);
    return n;
}
There is no argument passed to input() function But, the value of n is returned from input() to main() function.
Function with arguments and no return value
/*Program to check whether a number entered by user is prime or not using function with arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main()
{
    int num;
    printf("Enter positive enter to check:\n");
    scanf("%d",&num);
    check_display(num);  /* Argument num is passed to function. */
    return 0;
}
void check_display(int n)
{    
/* There is no return value to calling function. Hence, return type of function is void. */
    int i,flag;
    for(i=2,flag=i;i<=n/2;++i,flag=i)
{
    if(n%i==0)
{
        printf("%d is not prime",n);
        ++flag;
        break;
    }
    }
    if(flag==i)
        printf("%d is prime",n);
}
Here, check_display() function is used for check whether it is prime or not and display it accordingly. Here, argument is passed to user-defined function but, value is not returned from it to calling function.
Function with argument and a return value
/* Program to check whether a number entered by user is prime or not using function with argument and return value */
#include <stdio.h>
int check(int n);
int main()
{
    int num,num_check=0;
    printf("Enter positive enter to check:\n");
    scanf("%d",&num);
    num_check=check(num); /* Argument num is passed to check() function. */
    if(num_check==1)
       printf("%d in not prime",num);
    else
       printf("%d is prime",num);
    return 0;
}
int check(int n)
{  
/* Integer value is returned from function check() */
    int i;
    for(i=2;i<=n/2;++i)
{
    if(n%i==0)
        return 1;
}
   return 0;
}
Here, check() function is used for checking whether a number is prime or not. In this program, input from user is passed to function check() and integer value is returned from it. If input the number is prime, 0 is returned and if number is not prime, 1 is returned.

Structure
Structure is the collection of variables of different types under a single name for better handling. For example: You want to store the information about person about his/her name, citizenship number and salary. You can create these information separately but, better approach will be collection of these information under single name because all these information are related to person.

Structure Definition in C
Keyword struct is used for creating a structure.                 
Syntax of structure
struct structure_name
{
    data_type member1;
    data_type member2;
    .
    .
    data_type memeber;
};
We can create the structure for a person as mentioned above as:
struct person
{
    char name[50];
    int cit_no;
    float salary;
};
This declaration above creates the derived data type struct person.        
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of person, variable can be declared as:
struct person
{
    char name[50];
    int cit_no;
    float salary;
};
Inside main function:
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
    char name[50];
    int cit_no;
    float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person are created.
Accessing members of a structure
There are two types of operators used for accessing members of a structure.
1.       Member operator(.)
2.       Structure pointer operator(->) (will be discussed in structure and pointers chapter)
Any member of a structure can be accessed as:
structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should be in inch and feet.(Note: 12 inches = 1 foot)
#include <stdio.h>
struct Distance
{
    int feet;
    float inch;
}d1,d2,sum;
int main()
{
    printf("1st distance\n");
    printf("Enter feet: ");
    scanf("%d",&d1.feet);  /* input of feet for structure variable d1 */
    printf("Enter inch: ");
    scanf("%f",&d1.inch);  /* input of inch for structure variable d1 */
    printf("2nd distance\n");
    printf("Enter feet: ");
    scanf("%d",&d2.feet);  /* input of feet for structure variable d2 */
    printf("Enter inch: ");
    scanf("%f",&d2.inch);  /* input of inch for structure variable d2 */
    sum.feet=d1.feet+d2.feet;
    sum.inch=d1.inch+d2.inch;
    if (sum.inch>12){  //If inch is greater than 12, changing it to feet.
        ++sum.feet;
        sum.inch=sum.inch-12;
    }
    printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
/* printing sum of distance d1 and d2 */
    return 0;
}
Output
1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances= 15'-5.7"
Keyword typedef while using structure
Programmer generally use typedef while using structure in C language. For example:
typedef struct complex
{
  int imag;
  float real;
}comp;
Inside main:
comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex). Then, two structure variables c1 and c2 are created by this comp type.
Structures within structures
Structures can be nested within other structures in C programming.
struct complex
{
 int imag_value;
 float real_value;
};
struct number
{
   struct complex c1;
   int real;
}n1,n2;
Suppose you want to access imag_value for n2 structure variable then, structure member n1.c1.imag_value is used.

Structure and Pointer
Pointers can be accessed along with structures. A pointer variable of structure can be created as below:
struct name {
    member1;
    member2;
    .
    .
};
-------- Inside function -------
struct name *ptr;
Here, the pointer variable of type struct name is created.
Structure's member through pointer can be used in two ways:
1.       Referencing pointer to another address to access memory
2.       Using dynamic memory allocation
Consider an example to access structure's member through pointer.
#include <stdio.h>
struct name{
   int a;
   float b;
};
int main(){
    struct name *ptr,p;
    ptr=&p;            /* Referencing pointer to memory address of p */
    printf("Enter integer: ");
    scanf("%d",&(*ptr).a);
    printf("Enter number: ");
    scanf("%f",&(*ptr).b);
    printf("Displaying: ");
    printf("%d%f",(*ptr).a,(*ptr).b);
    return 0;
}
In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed.
Structure pointer member can also be accessed using -> operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b
Accessing structure member through pointer using dynamic memory allocation
To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file.
Syntax to use malloc()
ptr=(cast-type*)malloc(byte-size)
Example to use structure's member through pointer using malloc() function.
#include <stdio.h>
#include<stdlib.h>
struct name {
   int a;
   float b;
   char c[30];
};
int main(){
   struct name *ptr;
   int i,n;
   printf("Enter n: ");
   scanf("%d",&n);
   ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */
   for(i=0;i<n;++i){
       printf("Enter string, integer and floating number  respectively:\n");
       scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
   }
   printf("Displaying Infromation:\n");
   for(i=0;i<n;++i)
       printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
   return 0;
}
Output
Enter n: 2
Enter string, integer and floating number  respectively:
Programming
2
3.2
Enter string, integer and floating number  respectively:
Structure
6
2.3
Displaying Information
Programming      2      3.20
Structure      6      2.30

if, if..else and Nested if...else Statement
if statement syntax
if (test expression){
       statement/s to be executed if test expression is true;
}
Example of if statement
Write a C program to print the number entered by user only if the number entered is negative.
#include <stdio.h>
      int main(){
      int num;
      printf("Enter a number to check.\n");
      scanf("%d",&num);
      if(num<0)       /* checking whether number is less than 0 or not. */
            printf("Number=%d\n",num);  
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
      printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number=-2
The if statement in C programming is easy.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
if...else statement
The if...else statement is used, if the programmer wants to execute some code, if the test expression is true and execute some other code if the test expression is false.
Syntax of if...else
if (test expression)
     statements to be executed if test expression is true;
else
     statements to be executed if test expression is false;
Example of if...else statement
Write a C program to check whether a number entered by user is even or odd
#include <stdio.h>
int main(){
      int num;
      printf("Enter a number you want to check.\n");
      scanf("%d",&num);
      if((num%2)==0)          //checking whether remainder is 0 or not.
           printf("%d is even.",num);
      else
           printf("%d is odd.",num);
      return 0;
}
Output 1
Enter a number you want to check.
25
25 is odd.
Output 2
Enter a number you want to check.
2
2 is even.
Nested if...else statement (if...elseif....else Statement)
The if...else statement can be used in nested form when a serious decision are involved.
Syntax of nested if...else statement.
if (test expression)
     statements to be executed if test expression is true;
else
     if(test expression 1)
          statements to be executed if test expressions 1 is true;
       else
          if (test expression 2)
           .
           .
           .
            else
              statements to be executed if all test expressions are false;
Example of nested if else statement
Write a C program to relate two integers entered by user using = or > or < sign.
#include <stdio.h>
int main(){
     int numb1, numb2;
     printf("Enter two integers to check".\n);
     scanf("%d %d",&numb1,&numb2);
     if(numb1==numb2) //checking whether two integers are equal.
          printf("Result: %d=%d",numb1,numb2);
     else
        if(numb1>numb2) //checking whether numb1 is greater than numb2.
          printf("Result: %d>%d",numb1,numb2);
        else
          printf("Result: %d>%d",numb2,numb1);
return 0;
}
Output 1
Enter two integers to check.
5
3
Result: 5>3
Output 2
Enter two integers to check.
-4
-4
Result: -4=-4

Loops in C

How for loop works in C programming?
The initial expression is initialized only once at the beginning of the for loop. Then, the test expression is checked by the program. If the test expression is false, for loop is terminated. But, if test expression is true then, the codes are executed and update expression is updated. Again, the test expression is checked. If it is false, loop is terminated and if it is true, the same process repeats until test expression is false.
This flowchart describes the working of for loop in C programming.
for Loop Syntax
for(initial expression; test expression; update expression)
{
       code/s to be executed;
}
Example:
Write a program to find the sum of first n natural numbers where n is entered by user. Note: 1,2,3... are called natural numbers.
#include <stdio.h>
int main(){
    int n, count, sum=0;
    printf("Enter the value of n.\n");
    scanf("%d",&n);
    for(count=1;count<=n;++count)  //for loop terminates if count>n
    {
        sum+=count;    /* this statement is equivalent to sum=sum+count */
    }
    printf("Sum=%d",sum);
    return 0;
}
Output
Enter the value of n.
19
Sum=190
Syntax of while loop
while (test expression)
{
     statements to be executed. 
}
Example:
Write a C program to find the factorial of a number, where the number is entered by user. (Hints: factorial of n = 1*2*3*...*n
/*C program to demonstrate the working of while loop*/
#include <stdio.h>
     int main(){
     int number,factorial;
     printf("Enter a number.\n");
     scanf("%d",&number);
     factorial=1;
     while (number>0){      /* while loop continues util test condition number>0 is true */
           factorial=factorial*number;
           --number;
}
printf("Factorial=%d",factorial);
return 0;
}
Output
Enter a number.
5
Factorial=120
do...while loop
Syntax of do...while loops
do {
   some code/s;
}
while (test expression);
Example:
Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
   int sum=0,num;
   do             /* Codes inside the body of do...while loops are at least executed once. */
   {                                   
        printf("Enter a number\n");
        scanf("%d",&num);
        sum+=num;     
   }
   while(num!=0);
   printf("sum=%d",sum);
return 0;
}
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1





                     

Posted By New09:10