youtube-dl (Command Based Youtube Downloader)

Downloading youtube.com videos to local machine is always a challenge as the streaming sites keep on updating their policies in blocking the videos.
But there is a tool that is available in the command line (Terminal based) on Linux Operating Systems.
That is youtube-dl, this is a python based code and can be executed in linux OS without any hassles.

youtube-dl in windows or Mac OS can be achieved by installing python interpreter and try it.

for installing in linux, the command is
$prompt] sudo yum install youtube-dl (in redhat or centos or fedora)
$prompt] sudo apt-get install youtube-dl (ubuntu or linux mint)
See the image for downloading in Fedora 20
fedora20
Youtube-dl in Fedora 20

In ubuntu, you can update the sudo package before installing the youtube-dl.
sudo apt-get update

To download videos 
$prompt] youtube-dl http://www.youtube.com/watch?v=D980jXvyKUY

the above command will download the video in the best possible format. See the image below.
The video downloaded is of the format webm (Its a Web Movie format from Google for optimized view in web browsers)
youtube
Youtube-dl
To view all formats, use the following command,
$prompt] youtube-dl -F http://www.youtube.com/watch?v=D980jXvyKUY
[youtube] Setting language
[youtube] D980jXvyKUY: Downloading webpage
[youtube] D980jXvyKUY: Downloading video info webpage
[youtube] D980jXvyKUY: Extracting video information
[info] Available formats for D980jXvyKUY:
format code extension resolution  note
139         m4a       audio only  DASH audio , audio@ 48k (worst)
140         m4a       audio only  DASH audio , audio@128k
160         mp4       192p        DASH video
133         mp4       240p        DASH video
17          3gp       176x144  
36          3gp       320x240  
5           flv       400x240  
18          mp4       640x360     

43          webm      640x360     (best)

The above is output and to download the corresponding video format, then here is the command
$prompt] youtube-dl -f 18 http://www.youtube.com/watch?v=D980jXvyKUY
The above command will download the file in the mp4 format as specified in the option obtained in the previous command.

if you need any help on the commands, you can use the following command 
$prompt] youtube-dl --help

Often, youtube-dl is updated, it can be easily updated as given below,
$prompt] sudo youtube-dl -U

Also now youtube-dl supports various other video streaming sites also, to name a few, vimeo.com, dailymotion.com, etc.

If you are behind the proxy, type the command in the terminal  
export http_proxy=172.16.1.1:8080/ 
or copy the above line in /etc/profile.d/proxy.sh (this will be set for all the users of the computer, also need root password)

Download and Enjoy!!!

 T S Pradeep Kumar

Blogging and Google Adsense get me a DSLR Camera

By blogging and Google Adsense, my long time wish have come true that I got an DSLR (Nikon D5100). 
d5100
Nikon D5100

Blogging is a word that seems to be a "No man's Land" when I started this blog in 2006. Yes I started this blog mainly for providing lecture notes to my students. Initially I started this with blogger.com and a year later, I purchased www.pradeepkumar.org (this website) and shared contents. 
Initially I was not bothered about the ranking, search engine optimisation (SEO), page rank, etc. My main motive was to create content for the student community. Slowly, I improvise my contents to satisfy the global readers too. The topics that covered in my domains play a vital role in the provide information to open source research community. 
The topics of interest are 
  • Network simulator 2
  • Linux
  • Open Source Technologies
  • MOODLE
  • Wordpress
  • PHP, MySQL
  • Real TIme Systems
  • Embedded systems,
  • Java and etc.
This website was hacked twice and contents gets deleted. So I moved to Blogger for sometime.
Google updates the search engine algorithms many a times during these years, my website never get punished by the google search algorithms as the contents are original and the contents are for the readers and not for the search engines. Also I spend much of time in creating the contents, lecture notes, video tutorials, etc.
I started another blog www.nsnam.com in the year 2011 (Pageviews so far 651,449)  to cater the needs of the networking research community. nsnam.com (#nsnamcom) hosts mainly contents related to 
  • C,C++
  • Linux
  • NS2
  • NS3
  • tracegraph
  • xgraph
  • and other open source tools
It got huge visitors and pageviews. In the initial days, I paid the hosting charges on my own, later through Google Adsense, I enrolled in their program and they pay me now for running my websites for the hosting and domain charges.

Those who want to do blogging,
  • identify your niche areas (Photography, fashion, cooking, technology, gadgets, cinema, making money, blogging stuffs, research, etc)
  • learn the stuff
  • create contents.
  • And be original, dont copy content from anywhere
  • Enrol yourself in any of the advertising platforms like (adsense, infolinks, admob, etc)
  • Dont make your website idle, Write post atleast once a day or week (Its like a shop, if you dont open for a week, the customers may go somewhere else)
  • And Write for the readers and not for the search engines.
Happy blogging!!!!
T S Pradeep Kumar

nohup command in Linux

Often you come across a situation where you try to open a machine remotely using ssh and try to start a server or a run a command indefinitely.

But once you close the ssh session, your session also terminates and the background process also terminates. So here is a solution.

To open ssh remotely,

prompt $] ssh username@machinename
Ex: ssh root@172.16.1.1
Ex: ssh root@example.com 
prompt $] ssh -X username @machinename 
Ex. ssh -X root@172.16.1.1 

(this -X indicates the remote session can be opened in X window (GUI) mode)

Assume we need to start a httpd server in the remote machine.
we can issue the command like this

usage:
prompt$] nohup command 
if any error or log information may be stored in the nohup.out file. if you want to redirect to a file use the redirected symbol (1>  indicates standard output and 2> indicates standard Error). Specify the filenames for the output. Here is the typical nohup command to start the httpd server.

prompt $] nohup  /etc/init.d/httpd start  1> file.out 2> file.err & 
nohup is the command simply tells "no hangup". This will send the output to non-tty.
The above command will start the httpd server and any error or output will be written on to the files file.err and file.out respectively (The & indicates the background process that closes the current terminal and prompts for further inputs).
nohup
nohup in Linux


This command I learnt when i try to deploy Sage math libraries in a IBM Blade Server. We were really struggling to run the notebook in sagemath library. But finally accomplished using the nohup command.

The alternative to nohup is crontab or cronjob can be used.



 T S Pradeep Kumar

How to display Product name and Vendor name in Linux

This post will help you to find out the

  • Product Name
  • System Vendor Name 
This will help you to find the suitable device drivers if any.

The following is the command to find the System Vendor (in my case it is Hewlett Packard)
prompt $] cat /sys/class/dmi/id/sys_vendor

Here is the command to find the product name

prompt $] cat /sys/class/dmi/id/product_name


Printing the System Vendor and Product Name
cat is the command to concatenate the files and print it to the standard output

 T S Pradeep Kumar

C Programming Examples - Part 2

Here is the list of sample programs using C, This is list number 2. There are 21 more programs at this post.
http://www.nsnam.com/2014/10/simple-c-programs-for-beginners.html
C Program 1 – To find the reversal of a given number
Assume the number 1234, after reversal the number becomes 4321.
Input: One number, Ex 1234, declared to num
Output : One number, Ex 4321, rev is the variable
Logic:
  1. separate each digit using modulo operator from the right and bring that number to front
  2. divide the given number by 10, so the right most digit will be discarded.
  3. run till the number becomes <=0
output the result
#include <stdio.h>
#include <conio.h>

int main()
{
    int num,rev=0;
    printf("enter the number to be reversed");
    scanf("%d", &num);

    while(num>0) //till the number is positive, perform the process
    {
    rev=rev*10 + (num%10);
//separate each digit and bring it to the first
    num=num/10;
    }
    printf("The reversal is %d ",rev);
    getch();
    return 0;
}
C Program 2 – Electricity Bill calculation

This program is to display the electricity bill calculation based on the number of units consumed every month
Input : the number of units – variable name – unit
Output – Amount of rupee – variable name – amount
Logic:
Units Rupees
1-50 units 0.75/unit
51-100 0.85/unit
101-200 1.50/unit
201-300 2.20/unit
>300 3.00/unit
In all the cases, there will be service charge of Rs.20 will be collected.
#include <stdio.h>
#include <conio.h>
int main()
{
    float amount=0,units;;
    printf("Enter the number of units");
    scanf("%f", &units);
    if(units <=50)
    {
     amount = units * 0.75;       
    }   
    else if(units >50 && units <=100)
    {
         amount=0.75 * 50 + 0.85*(units-50);
    }
    else if(units >100 && units <200)
    {
         amount=(0.75*50) + (0.85*50 )+ (1.5 *(units-100));
    }
    else if(units >200 && units <300)
    {
         amount=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 *(units-200));
    }
    else
    {
         amount=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 * 100) +(3.0*(units-300));
    }
    amount=amount+(0.2*amount);
    printf("The total electricity bill is %f", amount);
    getch();
    return 0;
}
C Program 3 – To check whether a number is Armstrong Number
The armstrong number is of the form 153= 13 + 53 + 33
The input is : 153 or any other number
output: The number is armstrong or not.
Processing: take 153 as an example, remove 3, 5 and 1 in the reverse order (using % operator) and take the power of 3 and add to the sum variable.
if the total sum and the original number, both are same, then that is the arm strong number.
if else, the number is not an armstrong number
#include <stdio.h>
#include <conio.h>

int main()
{
    int original_num, check, temp, sum=0;
    printf("Enter the number to check for armstrong number");
    scanf("%d", &original_num);
// Get the original number
    temp=original_num;
    while(original_num>0)
//run the loop till the number becomes 0
    {
     check=original_num%10; 
//remove the last digit using modulo operator
     sum=sum+check*check*check; //the last digit is taken power to 3 and added to sum
     original_num=original_num/10; //truncate the last digit and run the loop again
     }
     if(sum==temp)
     printf("This is an armstrong number\n");
     else
     printf("This is not an armstrong number \n");
     getch();
     return 0;
}

C Program 4 – To check whether a given number is prime or not
A prime number can be divided by 1 and itself, there are no other divisors,
Examples are : 2 3, 5, 7, 11, …..
To find out whether a given number is prime or not, here is the logic
1. Get the number
2. divide the given number from 2 to n-1 (Example if 6 is the number divided by 2,3,4,5 will get the remainder respectively 0,0,2,3)
3. increment a counter to 1 if the remainder is 0
4. if there counter variable is 0, then the given number is prime (because we didn’t get any remainder) else non prime
Here is the program
#include <stdio.h>
#include <conio.h>
int main()
{
    int a,i,count=0;
    printf("enter a"); //Let the given number is a
    scanf("%d",&a); //get the number     for(i=2;i<a;i++) //divide the number a from 2 to a-1
    {
    if(a%i==0) 
    count++; //increment a counter if the divisibility is 0     }
    if(count !=0) //if the counter is not zero, then prime
    printf("a is not a prime number");
    else
    printf("a is a prime number");
getch();
return 0;
}

C Program 5 – Arrays with Functions (passing Array elements to function)

/*
Program to demonstrate arrays with function in which the array elements are passed as function parameters
*/
#include <stdio.h>
#include <conio.h>
void display(int); //function prototype
int main()
{
    int a[10],i;
    for(i=0;i<10;i++) //getting the array elements
    {
    scanf("%d",&a[i]);
    }
    for(i=0;i<10;i++)
        display(a[i]); //call the function inside the loop, this function called for 10 times     getch();
    return 0;
}
void display(int a) //function implementation to print the elements, here the parameter is an integer only(means we are passing the array elements)
{
     printf("%d",a);
}
C Program 6 – Passing an entire array to a function
/*
This program is to pass the entire array to a function
*/
#include <stdio.h>
#include <conio.h>
int maximum(int[],int); //function prototype, 1st parameter is array and the second is integer
int main()
{
    int a[100],i,n,max=0;
    printf("Enter the numbers"); 
    scanf("%d",&n); //get the index number
    for(i=0;i<n;i++) //get the array elements
    {
    scanf("%d",&a[i]);
    }
    max=maximum(a,n); //function call
    printf("Maximum number is %d",max);
    getch();
    return 0;
}
int maximum(int b[],int a) //function implementation
{
    int i,max=b[0];
    for(i=0;i<a;i++)
    if(b[i]>max)
    max=b[i];
    return max;
}
In the function call ie
max=maximum(a,n) where a is the array and n is the number of array elements
the above line can be written as
max = maximum(&a[0],n)
since the array is just a memory address, it is enough to mention the base address (address of the first element) of the array
so the array name is just equivalent to the base address
in the above example
a means &a[0]

C Program 7 – To sort a Given set of numbers in ascending order (BubbleSort)
/* Program to sort the given set of numbers in
ascending order, this sorting is called as bubble sort algorithm
*/
#include <stdio.h>
#include <conio.h>
int main()
{
    int a[10],i,j,temp=0;
    printf("Enter all the 10 numbers");
    for(i=0;i<10;i++)
    scanf("%d",&a[i]);
    for(i=0;i<10;i++)  //This loop is for total array elements (n)
    {
    for(j=0;j<9;j++) //this loop is for total combinations (n-1)
    {
                    if(a[j]>a[j+1]) //if the first number is bigger then swap the two numbers
                    {
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                    }
    }
    }
printf("The ordered array is");
for(j=0;j<10;j++) //Finally print the ordered array
printf("%d \t",a[j]);
getch();
return 0;
}


C Program 8 – To search a number in a given array
//This program is to search a given number in an array
#include <stdio.h>
#include <conio.h>
int main()
{
    int a[10],i,num;
    printf("enter the array elements");
    for(i=0;i<10;i++) //get all the numbers
    scanf("%d",&a[i]);
    printf("Enter the number to search");
    scanf("%d",&num);
    for(i=0;i<10;i++)
    {
                     if(a[i]==num) //given num is matched in the array
                     {
                     printf("The number is found in the %d position",i+1);
                     getch();
                     exit(0); //to go the end of the program
                     }
    }
printf("The number is not found"); //if num not found, this will be displayed
getch();
return 0;
}

C Program 9 – Adding two matrices
/* Program to add two matrices */
#include <stdio.h>
#include <conio.h>
int main()
{
    int a[10][10], b[10][10],c[10][10],i,j;
    printf("Enter a");
    for(i=0;i<2;i++)  //get the matrix A
        for(j=0;j<2;j++)
    scanf("%d",&a[i][j]);
    printf("Enter b");
    for(i=0;i<2;i++) //get the matrix B
        for(j=0;j<2;j++)
    scanf("%d",&b[i][j]);
   
    for(i=0;i<2;i++)
    {
        for(j=0;j<2;j++)
        {
        c[i][j] = a[i][j] +b[i][j];    //adding two matrices
        }
    }
    printf("Added Matrix is \n");
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
    printf("%d ",c[i][j]);
        getch();
        return 0;
}


C Program–Multiplying two matrices
/* Program to multiply two matrices */
#include <stdio.h>
#include <conio.h>
int main()
{
    int a[2][3],b[3][2],c[2][2],k,j,i;
    printf("enter a");
    for(i=0;i<2;i++)   //Get array A
    {
    for(j=0;j<3;j++)
    {
    scanf("%d",&a[i][j]); 
    }
    }
    printf("enter b");
    for(i=0;i<3;i++) //Get array B
    {
    for(j=0;j<2;j++)
    {
    scanf("%d",&b[i][j]);
    }
    }

    for(i=0;i<2;i++) 
    {
    for(j=0;j<2;j++)
    {
    c[i][j]=0;  //to Hold a temporary multiplication
    for(k=0;k<3;k++)
    {
    c[i][j]=c[i][j]+a[i][k]*b[k][j];   //Multiplication algorithm
    }
    }
    }
    printf("C is ");
    for(i=0;i<2;i++)
    for(j=0;j<2;j++)
    printf(" c[%d][%d] - %d \n",i,j,c[i][j]); 
 
getch();  
    return 0;
}

 T S Pradeep Kumar

Passing a Structure to a Function

  1. A function can accept a structure as a parameter and even it returns a parameter too.
  2. Either the individual structure elements can be passed or the entire structure can be passed.
Here is the example, for passing the entire structure to a function
#include <stdio.h>
#include <conio.h>
//Structure declaration
struct student
{
char name[10];
int no;
};
//Function prototypes
void read(struct student);
struct student display(struct student); //function which takes the entire structure as a parameter and it returns a structure also
int main()
{
    struct student s1,s;
     printf("Enter the details");
    scanf("%s %d",s1.name,&s1.no);
    s=display(s1);  //function call
printf("Name is %s and number is %d",s.name,s.no);
    getch();
}
//Function definition
struct student display(struct student s)
{
return s;
}
Nested Structures
A structure can be declared within another structure.
Example include: for a student structure maintaining the date of birth is tougher within the structure,
to avoid the complexity, dateofbirth can be a separate structure as defined below
struct dateofbirth
{
int date;
int month;
int year;
};
struct student
{
char name[50];
int no;
struct dateofbirth dob;
};
so the structure can be accessed using the following:
s.dob.date, s.dob.month, s.dob.year, and s.name, s.no
Example of Nested Structures

#include <stdio.h>
#include <conio.h>
//declare the structure dateofbirth which holds date,month and year
struct dateofbirth
{
int date;
int month;
int year;
};
//declare another structure student which also includes dateofbirth as a datatype
struct student
{
char name[50];
int no;
struct dateofbirth dob; //from another structure
};
int main()
{
struct student s;
printf("Enter the name number and date of birth (dd/mm/yyyy)");
scanf("%s %d %d/%d/%d",s.name,&s.no,&s.dob.date,&s.dob.month,&s.dob.year);
printf("%s %d %d/%d/%d",s.name,s.no,s.dob.date,s.dob.month,s.dob.year);
getch();
return 0;
}
It is always nice to include nested structures in applications as good readability is provided
for Example: building.concrete.cement.quality

 T S Pradeep Kumar

Structures and Unions in C Program


  1. Structure in C groups different data type under a common name
  2. struct is a keyword to declare a structure
  3. The size of the structure depends on the size of the different data types
  4. Structure declaration always ends with a semicolon
Example:
struct employee
{
char name[50];
int empid;
float salary;
};
The total size occupied by the above structure is 50 + 2 + 4 = 56 bytes (on TC compiler) and 50 + 4 + 4= 58 (on other compilers like GCC, etc). Again the size depends on the compiler.
GCC compiler always increase the size of structure which is divisible by 4 for faster code generation, so the above structure takes 60 bytes of memory
  1. Declaring a structure does not consume any memory, only when the structure object is created memory occupies
  2. Variables initialization will not be done during the structure declaration
The above syntax declaration does not consume memory, but the following do
int main()
{
struct employee e1;
}
Now e1 consumes memory of 60 bytes.
Simple Structure to get some details and print them to the screen
// GCC Compiler under windows 64bit
#include <stdio.h>
#include <conio.h>
/*  structures are declared outside any functions,
so that all the functions in the program can have access to it
*/
struct employee
{
       char name[50];
       int empid;
       float salary;
};
int main()
{
    struct employee e1;
    printf("enter the name, id and salary");
    scanf("%s %d %f",e1.name, &e1.empid, &e1.salary); 
    printf("The details entered are \n");
    printf("%s %d %f",e1.name, e1.empid, e1.salary);
    getch();
    return 0;
}
In the above program name, empid and salary are part of employee, so it should be associated with the member of structure, that’s why e1.name, e1.empid and e1.salary.

Array of Structures
//the following program gets the inputs of 3 employees like name, id and salary and compute the total salary taken by all the employees
#include <stdio.h>
#include <conio.h>
/*  structures are declared outside any functions,
so that all the functions in the program can have access to it
*/
struct employee
{
       char name[50];
       int empid;
       float salary;
};
int main()
{
    struct employee e[3];
    int i;
    float sum=0;
    printf("enter the name, id and salary");
    for(i=0;i<3;i++)
    {
    scanf("%s %d %f",e[i].name, &e[i].empid, &e[i].salary);
    sum=sum+e[i].salary;
    }
   
   
    printf("The details entered are \n");
    for(i=0;i<3;i++)
    printf("%s %d %f",e[i].name, e[i].empid, e[i].salary);
    printf("Total Salary of all 3 employees is %f",sum);
    getch();
    return 0;
}
Sample Output
Clipboard02

Arrays within Structures
//The following program gets the 2 student inputs like 3 subject marks and compute the total of all three subject marks
#include <stdio.h>
#include <conio.h>
/*  structures are declared outside any functions,
so that all the functions in the program can have access to it
*/
struct student
{
       int subjects[3];
       float total;
};
int main()
{
    struct student s[2];
    int i,j;
    printf("enter the 3 subject marks");
    for(i=0;i<2;i++)
    {
    s[i].total=0;
    for(j=0;j<3;j++)
    {
    scanf("%d",&s[i].subjects[j]);
    s[i].total += s[i].subjects[j];
    }
    printf("The total marks scored by student%d is %f",i+1,s[i].total);
    }
   
    getch();
    return 0;
}
Sample Output
clip2
 T S Pradeep Kumar

String Functions in C


Like numbered arrays, C handles character arrays (strings).
  1. Each string is identified as a character array and ends with a ‘\0’(null) character (the compiler automatically adds the null character). So the end of string is identified as a null character.
  2. Being an array, all the elements of the string array stored in continuous memory locations
following is the declaration of character array
char name[50];
or
char name[]=”Pradeep Kumar”;
or
char name[20]=”Hello Pradeep”;
Strings can be handled or manipulated through loops or library functions. There are some library functions to handle strings are available at string.h
Some of them are
strlen(string)
  • This is to find the length of the string and returns an integer
  • For example, if “Hello” is the string, the length will be 5 and “Hello “, the length is 6 (there is a blank space after o in hello)
strcat(String1, string2)
  • to concatenate two strings
  • One string will be appended to another string (the concatenation happens by inserting the new string at the null character ‘\0’ of the first string)
  • Example, if String1 is “Hello” and String2 is “Pradeep”, then strcat(string1, string2) will be “HelloPradeep”
  • Similarly,  if String1 is “Hello ” and String2 is “Pradeep”, then strcat(string1, string2) will be “Hello Pradeep”
strcpy(Destination, source)
  • This function is to copy one string to other
  • usually the copying string will be the 2nd parameter and copied string will be the first parameter
  • Example, if string1 is “Bad” and string2 is “Good” the strcpy(string1,string2) will give Good for string1
strcmp(Destination, source)
  • This function is to compare two strings whether they are equal or not
  • like numbers, two strings should not be compared directly like if(a==b)
  • If both the strings are equal, the function returns 0, else it will return the difference of ASCII value of the first non matching characters
  • Example, strcmp(“Their”, “There”) will return ASCII(i) – ASCII(r) (an integer will be returned)
Example Program
//program to demonstrate string handling functions
#include <stdio.h>
#include <conio.h>
int main()
{
    char a[50];
    char b[50];
    printf("Please the two strings one by one\n");
    gets(a);
    gets(b);
    printf("Length of String a is %d \n",strlen(a));
    printf("Length of String b is %d \n",strlen(b));
    if(!strcmp(a,b))  //Comparing two string will return 0, ! before strcmp() is needed
    printf("Both the strings are Equal");
    else
    printf("Both the strings are not equal");
    strcat(a,b);  //Concatenation function
    printf("the concatenated String is:");
    puts(a);
    strrev(a);
    printf("The reverse string is\n");
    puts(a);
    getch();
    return 0;
}
   
   
In the above program , instead of gets() function, scanf() can be used, but the disadvantage of scanf() being it truncates the blank space, new line, form feed, tab.
So for example, if the input give is “Hello pradeep”, then Hello only will be accepted, the string after the blank space will be omitted by the compiler, so gets() can be used.
Similarly, puts() or printf() can be used to display strings.
 T S Pradeep Kumar

Arrays of C Program

Arrays in C programming starts with memory addresses. Yes the compiler handles arrays as memory addresses.
  • Similar elements group together with a single name is called array
  • the indexing always starts with 0 and ends at n-1 (if the size of the array is n)
  • Array elements stores in consecutive memory location.
The array elements usually stores in consecutive memory location. For example,
int a[10];  //Array with size 10
the above example is an integer array with size 10 or this array can hold 10 variables.
The elements starts from a[0], a[1], a[2]…..a[9], so totally there are 10 elements.
Array elements values memory address location
a[0] 32 600AH  (This address is called as the base address)
a[1] 34 600EH
a[2] 23 6012H
a[3] 35 6016H
a[4] 45 601AH
a[5] 67 601EH
a[6] 56 6022H
a[7] 1 6026H
a[8] 34 602AH
a[9] 25 602EH
The memory addresses shown above are in hexadecimal, that’s why each address suffixed with a letter H. The memory addresses in each machine will be different.
The base address is the address where the first element of the array is stored. Usually it is represented as &a[0] or simply a.
The entire array is represented as an address by specifying the base address alone to various other elements of C programming like passing array to functions involves sending the base address only.
For the above table, here is the declaration syntax
int a[10]={32,34,23,35,45,67,56,1,34,25};
or
int a[]={32,34,23,35,45,67,56,1,34,25};
A simple program to get some numbers and print them on the screen
int main()
{
int a[10], j; //declaration of array “a” and its index j
printf(“Enter all the 10 numbers”);
for(j=0;j<10;j++) //get the numbers using a for loop which executes for 10 times (0 to 9)
{
scanf(“%d”, &a[j]);
}
for(j=0;j<10;j++) //print the numbers using a for loop which executes for 10 times (0 to 9)
{
printf(“%d”,a[j]);
}
return 0;
}
In the above example, j varies from 0 to 9 which means the loop will execute 10 times for the array a like this
a[j] when j=0 then a[0]
a[j] when j=1 then a[1]
a[j] when j=2 then a[2]…. and so on
like this the input is entered through the keyboard and same for printing the output.

 T S Pradeep Kumar

User Defined Functions in C

Almost all the programming languages uses functions. Functions are the entities which are grouping a set of statements which do a specific job or set of jobs.
Example: sum of integers, sum of float number, complex number addition.
All the above three can be implemented as a single function or three separate functions.
When someone wants to use that, a function can be simply called.
So function implementation happens as
  • Function prototype or Function declaration
  • Function definition or function implementation
  • Function call
Function prototype
  • It is necessary to specify the name of the function, the parameters and the return type to the compiler that the function is being defined in this program.
  • The prototype ends with a semicolon
syntax:
int sum(int, int); //function prototype
Function Definition
This is the actual function definition which shows the function implementation.
for the above syntax here is the function
int sum(int a, int b)
{
int c;
c=a+b;
return c;
}
The above function is returning an integer, hence int is specified. If a function is not returning any thing, a void can be used.
Function call
The last is the function call, which when being needed a simple call will make the function to work. Here is the example
int main()
{
int x,y,z;
scanf(“%d %d”,&x,&y);
z=sum(x,y); //function call
printf(“The sum is %d”, z);
return 0;
}
Once the function is called, the control goes to the actual implementation and execute the statements inside the function and the value is returned to the main function.
Components of a function
  1. Name of the function
  2. Return type
  3. Parameters or arguments
In the above example
name of the function is : sum()
return type is : int
parameters are: int, int

 T S Pradeep Kumar

Decision Making and Looping

C supports Decision Making and Looping (Interations)
In decision Making,
if, if-else, if- else if – else, switch – case is used.
if(condition)
{
//These statements are executed only if the condition is true or 1
}
if – else
if(condition)
{
//These statements are executed only if the condition is true or 1
}
else
{
//these statement are executed only if the condition is false or 0
}
(in the above example, there is no else part means that for some situation, there may not be a need for else part)
if – else if – else
if(condition 1)
{
//These statements are executed if the condition 1 is true or 1
}
else if (condition 2)
{
//These statements are executed if the condition 2 is true or 1
}
else
{
//These statements are executed neither condition 1 nor condition 2 are true
// if all the conditions fails, then this statement will execute
}
Switch Case
switch (expression)
{
case 1: statement 1;
break;
case 2: statement 2;
break;
case 3: statement 3;
break;
default: statement d;
break;
}
//Statement n;
The switch case works similar like a multiple if else if statement.
Assume if the expression takes 3 as the value and the statement 3 will be executed and next there is a break statement, so the control comes to statement n and it ill be printed.
so when case 3: is success, then
statement 3;
statement n;
will be printed
Looping
  • while()
  • do .. while();
  • for()
while ()
while(condition)
{
//statement 1
}
statement 1 will keep on execution till the condition becomes false
so this loop is called as entry controlled loop
do while()
do
{
//Statement 1
}while(condition);
in this, whether the condition is true or false, first time the loop will execute and only then it will check for validity of the condition.
so this loop is called as exit controlled loop
for loop
for (initialization: condition; increment/decrement)
{
//Statement
}
More details about the looping will be in subsequent posts.

 T S Pradeep Kumar

Data Types in C Programming

Declaration of variable names does two things
  • it tells the compiler what the variable name is
  • specifies what type of data the variable will hold
So it is mandatory that each variable should belong to a particular data type. C supports different data types like integer, character, float, double, etc.
Data type Size on a 16 bit machine Range
char 1 byte or 8 bits -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
short int or short 1 byte -128 to 127
int 2 bytes -32768 to 32767
unsigned int 2 bytes 0 to 65535
long int or long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295
float 4 bytes 3.4E-38 to 3.4 E+38
double 8 bytes 1.7E-308 to 1.7E+308
long double 10 bytes 3.4E-4932 to 1.1E+4932
Example of declaring variables
int a=20,b=20,c;
int a=10;
int b=9;
int c=20;
float c=3.5;
char a =’A’;
long int al or long a;
short int b or short b;
double c;
long double c;

 T S Pradeep Kumar

C Tokens

Tokens are classified as
  • Keywords
  • Identifiers
  • Operators
  • Constants
  • Special Symbols
Keywords
Keywords are reserved by the compilers and keywords will not be redefined (means the keywords are not been declared as variable names, etc). There are standard 32 keywords in C compiler, and some compilers uses more keywords based on their specification. Here is the list of 32 keywords
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while

Identifiers
  1. Identifiers are variable names declared inside the program.
  2. They use alphabets, number, symbols like _ and $
  3. They must begin with  alphabet or _
  4. They are case sensitive i.e Var_name is different from var_name
Some valid identifiers are
john Value r_sie x1
x2 Chennai Sum1 abcd
invalid identifiers
123 % (super) 25th
1st ab-d sum of total

Operators
operators are further classified into different categories like
  • Arithmetic operators
+  - for addition   1+3 = 4
-   for subtraction      3 – 2 = 1        
*  for multiplication 4* 2 = 8
/   for Division      4 / 2    = 2
% for modulo  4 % 3 = 1 (when 4 is divided by 3, the remainder is 1)
  • Increment/ Decrement operators
++  increment Ex: a++ or ++a
--  decrement Ex: a—or –a
  • relational Operators
< – less than
> – greater than
<= less than or equal to
>= greater than or equal to
== is equal to
  • logical operators
&&  - Logical AND
||   - Logical OR
!  - Logical NOT
  • bitwise operators
& Bitwise AND
| bitwise OR
^ bitwise XOR
~ one’s complement
<< shift left
>> shift right
  • Conditional Operators
? : Conditional operator
f =(a>b) ?a : b;
if the condition a> b is true then
a is assigned to f and if false then b is assigned to f
the statement can be rewritten as
if(a>b>
{
f=a;
}
else
{
f=b;
}
  • Other Operators
= assignment operator (this is not equality operator, it just assigns the value to some other variable from right to left assignment)
Example: a=b means b is assigned to a
, comma operator (This is to separate the array variables, etc)
sizeof() operator (to find out the various sizes of the entities like int, char, array size, etc)
  • Special symbols
{} This to begin and end any statement, loop in C program
[] This is for specifying the array index (Ex: int a[10];)
()  This is used for functions in C and helpful for grouping arithmetical operations
Constants
  • Constants is an entity will never changes it value during the execution of the program
  • They are different from variables

  • Integer constant
Examples are 2, –1, 0, 345, 324, etc
  • float Constant
Examples are 3.0, –2.345, 32.56, 4.65
  • String Constant
“abc”, “Pradeep Kumar”
  • Character constant
‘A’, ‘b’, ‘1’
There are two ways to declare a constant
1st way is to define at the preprocessing level
Example is
#define PI 31.4
2nd way is declare inside the program
const int a=3.14;
const is the keyword to define a constant.

 T S Pradeep Kumar

IO Functions - printf and scanf

Printf() is a function to print strings to the display unit and
scanf() is to scan the input through the keyboard
the f in the printf and scanf are called as format. That is, printf() and scanf() will print and scan in some particular format, it is the duty of the developer to provide that formats.
For example
printf(“a=%d, b=%d”, a,b); //This function will print a=10, b=20 if the values of a and b are 10 and 20
scanf(“%f”, &a); //this will accept a float number as the specifier is %f which is for float, See the Ampersand symbol which to tell the compiler to store the variable into the address.
Here is the list of format codes or format specifiers
scanf() format codes
Code Meaning
%c read a single character
%d read a decimal integer
%f read a floating point value
%e read a floating point value (even in exponential format)
%g read a floating point value
%h read a decimal, heaxadecimal or octal integer
%o read an octal integer
%s read a string
%u read an unsigned integer
%x read a hexadecimal integer
h for short integers like %hd
l for long integers like "%ld
L for long double like %Lf
printf() format codes
Code Meaning
%c prints a single character
%d print a decimal integer
%e print a floating point value in exponential form
%f print a float point value
%g print a float point value either in f type or e type depending on the value
%i print a signed decimal integer
%o prints an octal integer
%s prints a string
%u print an unsigned integer
%x print a hexadecimal number

Backslash Character constants or Escape Characters
There are some characters inside the double quotes for printf() and scanf() which are escaped by the compiler and hence it will the next character after the escape characters
Character What it will do
\n go to the new line
\t horizontal tab
\a alert bell
\f form feed
\r carriage return
\” will print “
\’ will print ‘
\? will print ?
\\ will print \
\v vertical tab
\b backspace

 T S Pradeep Kumar

Simple C Program

/* This program is written by T S Pradeep Kumar on 28th Sep 2010
This is to display Hello World to the display unit
*/
#include <stdio.h> //including the standard IO functions like printf(), scanf()
int main()
{
printf(“Hello World \n”);
return 0;
}
  1. stdio.h is the library which contains the printf(), scanf() and other standard IO functions, so before we use any function we need to include in our C program. Most of the compilers will take stdio.h automatically, even if we dont include in our program
  2. int main() {} is the main function
  3. printf(“Hello World\n”); printf() is the function which is printing to the display unit and it is displaying Hello World. Whatever is there inside the double quotes will displayed as it is in the monitor except the format specifiers or format codes (%d, %f, %c)
  4. return 0; is the final statement which returns the integer value 0 (this is just to make the compiler happy)
Here in the above program, you can see there are semi colons ;
Every C statement must end with a semicolon. If a statement is not completed, then there need not be a semicolon.

 T S Pradeep Kumar

C Programming - Introduction

This post and the subsequent posts will help you in understanding the intricacies of C programming. These posts just shows you the basics of C programming and some worked examples for that. 
C
C Program with Linux

Features of C Programming
  • C is a small language having lesser number of keywords than Java or pascal.
  • C is a native language of Unix, Linux. Not only that many of the windows packages, database programs, graphics libraries are written in C program
  • C is portable – it provides standard set of libraries that work on the same way with all machines
  • C is modular, as it supports functions to divide the program in to sub program
  • C is efficient on most machines, because certain constructs are machine dependant.
Structure of a C program
  • Comments
    • the comments are usually ignored by the compiler
    • so this part informs about the author of the program
    • what is the usefulness of this program
    • updation or creation of the program
    • Example: //  - Single line comment
    • /* ----- multi line comments    ….*/
  • Preprocessor Directives
    • before the compiler runs, the preprocessing takes place.
    • the preprocessors are prefix with a symbol #
    • Examples: #include, #define, #ifdef, #pragma, etc.
  • Function prototypes
    • This is to inform the compiler that the following functions are defined in this program.
    • it specifies the name of the function, arguments or parameters and return type and it ends with a semicolon
    • Ex: int sum(int,int);
  • Global Variables
    • Global variables which are declared above all the functions
    • As the name says, they are available to all the functions of that program
    • They are usually stored in the RAM
  • Main Function
    • main is the function which is main to the entire program
    • Every C program should have a main function
    • syntax: int main() { }
    • Earlier, the main program will return nothing, ie void, but now the compilers are instructing us to provide a return type for the main() function
  • User defined functions
    • After the main() function, the user defined functions are defined, as per the function prototype declared in the program
    • The function can be defined above the main function also, in that case there is not need for function prototype
    • Syntax:
int sum(int a, int b)
{
int f;
f=a+b;
return f;
}

 T S Pradeep Kumar

Simple C Programs for Beginners

This post has no relation with networks, however these C programs help anyone who started learning C programming. It covers from basics of C to Arrays and Functions.
The readers are requested to get their outputs, as the output screenshots were lost. Also most of these programs were solved by my student friends. If you encounter any errors in the programs, kindly comment below to get it rectified through other readers.

To compile these programs in
Windows : Use Dev-C++ for compilation (It GUI Based), Also you may remove #include <conio.h> if you encounter any error during compilation

In Linux: 
You may try the gcc or g++ compiler
Delete the #include <conio.h>
delete the line that contains getch(); 
Here is the command 
$] gcc -o first file.c 
$] ./first
(The file.c is compiled and linked to the binary file first and the output is executing in the second line using ./first)
See the following screenshot for the Question 1.
c program
Output of a C Program

Question 1 
The straight line method of computing the yearly depreciation of the value of an item is given by
Depreciation = (Purchase Price – Salvage Value) / years of service.
Write a program to determine the salvage value of an item when the purchase price, years of service and the annual depreciation are given.
Program
#include<stdio.h>
#include<conio.h>
int main()
{
int yr;
float price,dep,salvalue;
printf("enter the purchase price,years of service, annual depreciation");
scanf(" %f %d %f", &price,&yr,&dep);
salvalue = price-(dep*yr);
printf("The salvage value of the item is %f",salvalue);
getch();
return 0;
}
Output:
enter the purchase price, years of service, annual depreciation
5000 8 5.25
The salvage value of the item is 4958.000000
Question 2
Write a function exchange to interchange the values of two variables, say x and y. Illustrate the use of this function, in a calling function. Make x and y as global variables.
Program:
#include<stdio.h>
#include<conio.h>
void exchange(int a,int b);
void exchange(int a,int b)
{int c;
c=a;
a=b;
b=c;
printf("the I no is .......%d \n the second no. is.......%d",a,b);
}
int main()
{int x,y;
printf("enter two no's.....\n first no is...\n");
scanf("%d",&x);
printf("enter second number.....");
scanf("%d",&y);
exchange(x,y);
getch();
return 0;
}

Output:
enter two no's.....
first no is...
5
enter second number.....9
the I no is .......9
the second no. is.......5
Question 3
Write a function space(x) that can be used to provide a space of x positions between two output numbers.
Program:
#include<stdio.h>
#include<conio.h>
/ /The two output numbers here are 0 and 1
void space(int);
int main()
{ int x;
printf("Enter the number of spaces between the two numbers: ");
scanf("%d", &x);
space(x);
getch();
return 0;
}
void space(int x)
{ int i;
printf("0");
for(i=0;i<x;i++)
printf(" ");
printf("1");
}
Output:
Question 4
Write a function prime that returns 1 if its argument is a prime number and returns zero otherwise.
Program:
#include<stdio.h>
#include<conio.h>
int prime(int);
int main()
{ int res,num;
printf("Enter a number to check if it is prime or not: ");
scanf("%d", &num);
res=prime(num);
if(res==1)
printf("\nThe number %d is prime\n", num);
if(res==0)
printf("\nThe number %d is not prime\n", num);
getch();
return 0;
}
int prime(int n)
{ int i;
for(i=2;i<=n/2;i++)
{if(n%i==0)
return 0;}
return 1;
}

Output:
Question 5
Where u is the initial velocity (m/s), a the acceleration due to gravity (m/s2). Write a program to evaluate the distance travelled at regular intervals of time, given the values of u and a. the program should provide the flexibility to the user to select his own time intervals and repeat the calculations of different values of u and a
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int s=0,d,u,a,t;
while (1)
{
printf("\nenter initial velocity");
scanf("%d",&u);
printf("\nenter the value of accceleration ");
scanf("%d",&a);
printf("\nenter time duration");
scanf("%d",&t);
d = (a*t*t)/2;
s=u+d;
printf("\nthe distance covered is %d\n",d);
}
getch();
}

Output:
Question 6
Write a program using for loops to produce a triangle using the asterisk (*) symbol. The program should prompt the user for the height of the triangle and check to see that the user entered a number greater than or equal to 3 and less than or equal to 40. If the user enters an invalid number, the program will print an error message and exit. If the user enters a valid number the program will print an equilateral triangle of height n, where n is the number the user entered at the console. The program should be written using no more than three printf() statements.
#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, h;
printf("Enter the height of the triangle : ");
scanf("%d",&h);
if((h>=3)&&(h<=40))
{
for(i=1; i<=h; i++)
{
printf("\n");
for(j=1; j<=i; j++)
{
printf("* ");
}
}
}
else
printf("\n\n\n\nError.....!!!!\n\n\n\nPress any key to exit...");
getch();
return 0;
}

OUTPUT SCREEN


Question 7
For an certain electrical circuit with an inductance L and resistance R, the damped natural frequency is given by
√(1/LC – R2/4C2). It is desired to study the variation of this frequency with C (capacitance). Write a program to calculate the frequency for different values of C starting from 0.01 to 0.1 in steps of 0.01.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float C[10] = { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10 };
float R, L, f[10];
int i;
printf("Enter the value of R : ");
scanf("%f",&R);
printf("\n\nEnter the value of L : ");
scanf("%f",&L);
for(i=0; i<10; i++)
{
f[i] = sqrt(1/(L*C[i])-(R*R)/(4*C[i]*C[i]));
}
printf("\n\n\nValue of C\tValue of f\n\n");
for(i=0; i<10; i++)
{
printf("%f\t%f\n",C[i],f[i]);
}
getch();
return 0;
}

OUTPUT SCREEN

Question 8
Write a program to determine and print the sum of the following harmonic series for a given value of n:
1 + ½ + 1/3 + ¼ +….. +1/n
The value of n should be given interactively through the terminal
Program:
#include <stdio.h>
int main()
{
int n;
float a,i;
printf("Input \t\t: ");
scanf("%d", &n);
while (!(n>0))
{
printf("\n\nEnter a POSITIVE Number : ");
scanf("%d", &n);
}

for (i=1; i<=n; i++)
{
a += (1.0/i);
}
printf("\nRequired Output : %f\n", a);
return 1;
}
Output:
Question 9
Write a program that prompts the user for the number of Fibonacci numbers to generate and then prints the Fibonacci numbers to the screen. The user will enter some number, which we'll call n. Your program should use a for loop to generate the Fibonacci numbers up to n, and then use a while loop to generate the numbers from back down to zero.
#include<conio.h>
#include<stdio.h>
int main()
{
int i, n , fb[100];
fb[0]=0;
fb[1]=1;
printf("Enter a number till which you wish to print the series : ");
scanf("%d",&n);
printf("\n\n");
for(i=2; i<n; i++)
{
fb[i]=fb[i-1]+fb[i-2];
}
for(i=0; i<n; i++)
{
printf("%d\t",fb[i]);
}
printf("\n\n\n\nReverse Order....\n\n");
i=n-1;
while(i>=0)
{
printf("%d\t",fb[i]);
i--;
}
getch();
return 0;
}


OUTPUT SCREEN
Question 10
Write a program to read the price of an item in decimal form (Eg 18.75) and print the output in paise like (1875).
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
printf("\t\t\t\t Program No. 10\n");
float rs,pais;
printf("Enter the price of an item in rupees\n");
scanf("%f",&rs);
pais = rs*100;
printf("The price in paise is : %7.0f",pais);
getch();
return 0;
}
Output:
Program No. 10
Enter the price of item in rupees
187.5
The price in paise in : 18750
Question 11
A cloth showroom has announced the following seasonal discounts on purchase of items
Purchase AmountDiscount
Mill ClothHandloom Items
0-100-5%
101-2005%7.5%
201-3007.5%10.0%
301 and above10%15.0%
Write a program using switch and if statement to compute the net amount paid by a customer.
Program:
#include<conio.h>
#include<stdio.h>

int main()
{
int choice;
float price,total;
printf("enter the choice of cloth and the price \n 1.mill cloth or \n 2. for handloom items");
scanf("%d %f",&choice,&price);
switch(choice)
{
case 1:if (price>=0 && price<=100)
total=price;
else
if (price>=101 && price<=200)
total=price-(0.05*price);
else
if (price>=201 && price<=300)
total=price-(0.075*price);
else
if (price>=301)
total=price-(0.10*price);
break;
case 2:if (price>=0 && price<=100)
total=price-(0.05*price);
else
if (price>=101 && price<=200)
total=price-(0.075*price);
else
if (price>=201 && price<=300)
total=price-(0.1*price);
else
if (price>=301)
total=price-(0.15*price);
break;}
printf("the total is %f",total);
getch();
return 0;
}
Output:

Question 12
Write a program that will read the value of x and evaluate the following function.
Y=1 for x >0
Y=0 for x=0
Y=-1 for x< 0
Using (a) nested if statements (b) else if statements (c) conditional Operator
Program:
#include <stdio.h>
#include <conio.h>
int main()
{
float x,y;
printf("Enter thhe value of X=");
scanf("%f",&x);
if (x>0)
printf("Y=1");
else if (x==0)
printf("Y=0");
else if(x<0)
printf("Y=-1");
getch();
return 0;
}
Output:
Enter the value of X=6
Y=1
Question 13
A number is special if it is divisible by 15. A number is big if it is greater than 999. A number is weird if it is divisible by 5 and 6 but not 18. A number is scary if it is big or weird. Declare four variables called special, big, weird and scary and make suitable assignments to these variables as a number is tested.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int n,special,big,weird,scary;
printf("enter a no.");
scanf("%d",&n);
if(n%15==0)
{
special=n;
printf("%d is a special no\n",special);
}

if (n>999)
{
big=n;
printf("%d is a big no\n",big);
}
if(n%5==0 && n%6==0 && n%18!=0)
{
weird=n;
printf("%d is a weird no.\n",weird);
}
if(n==big || n==weird)
{
scary=n;
printf("%d is a scary no\n",scary);
}
getch();
return 0;
}

Output:
Enter a no.
1500
1500 is a special no
1500 is a big no
1500 is a weird no
1500 is a scary no

Question 14
Declare two arrays A and B, find A n B and A u B.
Program:
#include<stdio.h>
#include<conio.h>
int main()
{int n;
printf("enter the size of the array");
scanf("%d",&n);
int a[n],b[n];
printf("enter elements of I array");
for(int i=0;i<n;i++)
{scanf("%d",&a[i]);}
printf("enter elements of II array");
for(int j=0;j<n;j++)
{scanf("%d",&b[j]);}
printf("the intersection of two arrays are");
for(int i=0;i<n;i++)
{for(int j=0;j<n;j++)
{if(a[i]==b[j]){printf("%d",b[j]);
}}}
printf("\n");
printf("the union of two arrays is\n");
for(int i=0;i<n;i++)
{
printf("%d",a[i]);
}

for(int j=0;j<n;j++)

{int var=0;

for(int i=0;i<n;i++)
{
if(b[j]==a[i])
{var=var+1;}
}
if(var==0)
{printf("%d",b[j]);}
}

getch();
return 0;
}

Output:
enter the size of the arrays
5
enter elements of I array
7 8 9 5 4
enter elements of II array
8 9 2 3 6
the intersection of two arrays are89
the union of two arrays is
78954236
Question 15
Write a program to, reverse a given array
Program:
#include <stdio.h>
#include <conio.h>
int main()
{
int n,p;
printf("Enter size of array \n");
scanf("%d", &n);
int a[n],i,t;
printf("Enter elements of array \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
i=0;
p=n;
while(i<=n/2)
{
t=a[i];
a[i]=a[n-1];
a[n-1]=t;
i++;
n--;
}
printf("Reversed array \n");
for(i=0;i<p;i++)
printf("%d ",a[i]);
getch();
return 0;
}
Output:
Enter the size of array4
Enter elements of array1 3 7 4
Reversed array 4 7 3 1
Question 16
Search an element in an array and display the index position of all the elements of that value.
Program:-
#include<conio.h>
#include<stdio.h>
int main()
{
int i,n=0,ans=0,s=0;
double a[100],ele;
char t;
while(n<=0||n>100)
{
printf("enter the number of elements(max 100)\n");
scanf("%d",&n);
}
for(i=0;i<n;i++)
{
printf("enter the value of element");
printf(" %d\n",i+1);
scanf("%lf",&a[i]);
}
do
{
printf("enter the element you want to search\n");
scanf("%lf",&ele);
s=0;
for(i=0;i<n;i++)
{
if(a[i]==ele)
{printf("the element is found at position %d\n",i+1);
s+=1;}
}
if(s==0)
{
printf("the element is not found\n");
}
printf("enter 1 to search more or any key to exit\n");
t=getch();
ans = t-48;
}while(ans==1);
return 0;
}

Output:

Question 17
Perform the matrix multiplication using two dimensional array by sending entire array to a function mmultiply()
#include<stdio.h>
#include<conio.h>
void multiply(int a[][],int b[][]);
int main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;

printf("matrix a:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++}
scanf("%d",&a[i][j]);
}
printf("matrix b:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++}
scanf("%d",&b[i][j]);
}
multiply(a[][],b[][]);
getch();
return 0;
}

void multiply(int a[][],int b[][])
{
int i,j,k;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("resultant matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++}
scanf("%d",&c[i][j]);
}
}

OUTPUT:-
Matrix a:0
1
2
2
3
4
3
4
5
Matrix b:0
1
2
2
3
4
3
4
5
Resultant matrix:6
13
16
18
31
40
23
40
52
Question 18
Write a program to calculate the standard deviation of an array of values. The array elements are read from the terminal. Use functions to calculate standard deviation and mean.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int n;
printf("Enter how many numbers you want to enter?");
scanf("%d",&n);
int a[n];
printf("enter the numbers");
double x=0.0,x1=0.0;
int i;
double z;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
x=x+a[i];
}
x=x/n;
for(i=0;i<n;i++)
{
x1=x1+pow((x-a[i]),2);
}
z=sqrt(x1/n);
printf("standard deviation is %f",z);
getch();
return 0;
}
Question 19
An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the ballot should be considered as a spoilt ballot and the program should also count the number of spoilt ballots.
#include<conio.h>
#include<stdio.h>
int main()
{
int i, vote[100], c1=0, c2=0, c3=0, c4=0, c5=0, c_spoilt=0, n;
printf("Enter the number of voters : ");
scanf("%d",&n);
printf("\n\n\n\n\nEnter votes ( between 1 to 5 )....\n\n\n\n");
for(i=0; i<n; i++)
{
printf("\nVoter %d : ",i+1);
scanf("%d", &vote[i]);
if((vote[i]<=5)&&(vote[i]>=1))
{
switch(vote[i])
{
case 1 : c1++;
break;
case 2 : c2++;
break;
case 3 : c3++;
break;
case 4 : c4++;
break;
case 5 : c5++;
break;
default : printf("Error...!!!");
}
}
else
{
vote[i]=0;
c_spoilt++;
}
}
printf("\n\n\n\nNumber of votes for candidate 1 : %d", c1);
printf("\n\nNumber of votes for candidate 2 : %d",c2);
printf("\n\nNumber of votes for candidate 3 : %d",c3);
printf("\n\nNumber of votes for candidate 4 : %d",c4);
printf("\n\nNumber of votes for candidate 5 : %d",c5);
printf("\n\nNumber of votes spoilt : %d",c_spoilt);
getch();
return 0;
}

OUTPUT SCREEN
Question 20
Define a structure called cricket that will describe the following information:
Player name, team name, batting average.
Using cricket, declare an array player with 10 elements and write a program to read the information about all the 50 players and print a team wise list containing names of players with their batting average.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>

struct cricket
{
char playername[50];
char teamname[50];
float battingavg;
};
int main()
{
struct cricket player[100];
int i,n,m,j;
char name[10][10];
printf("Enter the no. of teams:- ");
scanf("%d",&n);
for(j=0;j<n;j++)
{
printf("Enter the name of the teams:- ");
scanf("%s",&name[j]);
}
printf("\nEnter the no. of players:- ");
scanf("%d",&m);
for(i=0;i<m;i++)
{
printf("Enter the %d player name, team name & batting avg:- ",i+1);
scanf("%s%s%f",&player[i].playername,&player[i].teamname,&player[i].battingavg);
}
printf("\n\nListing according to team names::\n");
for(j=0;j<n;j++)
{
printf("\n%s-\n",name[j]);
for(i=0;i<m;i++)
{
if(strcmp(player[i].teamname,name[j])==0)
{
printf("\t%s\t%f\n",player[i].playername,player[i].battingavg);
}
}
}
getch();
return 0;
}

Output:
Enter the no. of teams:- 2
Enter the name of the teams:- TEAM1
Enter the name of the teams:- TEAM2

Enter the no. of players:- 4
Enter the 1 player name, team name & batting avg:- A TEAM1 41
Enter the 2 player name, team name & batting avg:- B TEAM2 23
Enter the 3 player name, team name & batting avg:- C TEAM1 15
Enter the 4 player name, team name & batting avg:- D TEAM2 45


Listing according to team names::

TEAM1-
A 41.000000
C 15.000000

TEAM2-
B 23.000000
D 45.000000
Question 21
A bookshop uses a personal computer to maintain the inventory of books that are being sold at the shop. The list includes details such as author, title, isbn number, price, author, stock position. Whenever a customer wants a book, the shopkeeper inputs the title or isbn number and the system replies whether the book is available or not. If it is not, an appropriate message is displayed. If book is in the list, then the system displays the book details and asks for number of copies. If the requested copies are available, the total cost of the books is displayed, otherwise the message “Requested copies are not in stock” is displayed. Implement using structures.
#include<conio.h>
#include<stdio.h>
#include<string.h>
struct book
{
char author[50];
char title[50];
int isbn_num, stock, price;
};
int main()
{
char search[20];
char t1[50];
int i, n, n1, copies, bill;
struct book b1[100];
printf("Enter the number of book records you want to enter : ");
scanf("%d", &n);
printf("\n\n\nEnter the records...\n\n\n");
for(i=0; i<n; i++)
{
printf("\nEnter the record number %d...\n",i+1);
printf("\nName of the author : ");
gets(b1[i].author);
printf("\nTitle of the book : ");
gets(b1[i].title);
printf("\nIsbn number : ");
scanf("%d", &b1[i].isbn_num);
printf("\nStock : ");
scanf("%d", &b1[i].stock);
printf("\nPrice : ");
scanf("%d", &b1[i].price);
}
printf("\n\n\n\nWhat do you want to enter for search ( Title / Isbn ) ?\n\n");
scanf("%s",search);
if(strcmpi("title",search)==0)
{
printf("\n\nTitle of the book you wish to search : ");
gets(t1);
for(i=0; i<n; i++)
{
if(strcmpi(b1[i].title,t1)==0)
{
printf("\nTitle : ");
puts(b1[i].title);
printf("\nAuthor : ");
puts(b1[i].author);
printf("\nIsbn Number : %d",b1[i].isbn_num);
printf("\nStock : %d",b1[i].stock);
printf("\nPrice : %d",b1[i].price);
printf("\n\nNumber of copies you want of the book : ");
scanf("%d",&copies);
if(copies<=b1[i].stock)
{
bill = copies*b1[i].price;
printf("\nTotal price : Rs. %d", bill);
}
else
printf("\n\nRequested copies are not in stock...!!!");
}
else
printf("\n\nRequested book not available...!!!");
}
}
else
if(strcmpi("isbn",search)==0)
{
printf("\n\nIsbn Number of the book you wish to search : ");
scanf("%d",&n1);
for(i=0; i<n; i++)
{
if(b1[i].isbn_num==n1)
{
printf("\nTitle : %s", b1[i].title);
printf("\nAuthor : %s", b1[i].author);
printf("\nIsbn Number : %d",b1[i].isbn_num);
printf("\nStock : %d",b1[i].stock);
printf("\nPrice : %d",b1[i].price);
printf("\n\nNumber of copies you want of the book : ");
scanf("%d",&copies);
if(copies<=b1[i].stock)
{
bill = copies*b1[i].price;
printf("\nTotal price : Rs. %d", bill);
}
else
printf("\n\nRequested copies are not in stock...!!!");
}
else
printf("\n\nRequested book not available...!!!");
}
}
getch();
return 0;
}
OUTPUT SCREEN

T S Pradeep Kumar