INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year...

80
INTRODUCTION TO PROGRAMMING Exercise 1: /* program to print hello world*/ 1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation. 2. The next line int main() is the main function where program execution begins. 3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program. 4. The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen. 5. The next line return 0; terminates main()function and returns the value 0. /* program to print hello world*/ #include <stdio.h> /* standard input output header file*/ int main() /* where the program starts execution*/ { printf("Hello, World! \n"); /* print the output*/ return 0; } Compile & Execute C Program 1. Open a text editor and add the above-mentioned code. 2. Save the file as hello.c 3. Open a command prompt and go to the directory where you saved the file. 4. Type gcc hello.c and press enter to compile your code. 5. If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file. 6. Now, type a.out to execute your program. 7. You will be able to see "Hello World" printed on the screen $ gcc hello.c $ ./a.out Hello, World!

Transcript of INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year...

Page 1: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

INTRODUCTION TO PROGRAMMING

Exercise 1: /* program to print hello world*/

1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C

compiler to include stdio.h file before going to actual compilation.

2. The next line int main() is the main function where program execution begins.

3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional

comments in the program. So such lines are called comments in the program.

4. The next line printf(...) is another function available in C which causes the message "Hello,

World!" to be displayed on the screen.

5. The next line return 0; terminates main()function and returns the value 0.

/* program to print hello world*/

#include <stdio.h> /* standard input output header file*/

int main() /* where the program starts execution*/

{

printf("Hello, World! \n"); /* print the output*/

return 0;

}

Compile & Execute C Program

1. Open a text editor and add the above-mentioned code.

2. Save the file as hello.c

3. Open a command prompt and go to the directory where you saved the file.

4. Type gcc hello.c and press enter to compile your code.

5. If there are no errors in your code, the command prompt will take you to the next line and

would generate a.out executable file.

6. Now, type a.out to execute your program.

7. You will be able to see "Hello World" printed on the screen

$ gcc hello.c

$ ./a.out

Hello, World!

Page 2: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 2: /* Program to add two numbers */

Data types refer to an extensive system used for declaring variables or functions of different

types. The type of a variable determines how much space it occupies in storage and how the bit

pattern stored is interpreted. Here we have to declare three variables a, b, sum to store values.

The variable ‘a’ stores the first number, ‘b’ stores the second number and ’sum’ stores the

summation of a & b. scanf() function is used to read character, string, numeric data from

keyboard.

1. The first line of the program #include <stdio.h> is a preprocessor command,which tells a C compiler to include stdio.h file before going to actual compilation.

2. The next line main() is the main function where program execution begins.

3. Declare the variables a, b, sum as integers. ‘int’ keyword is used to declare thevariables as integer

4. ‘printf()’ is used to display the out put.

5. The format specifier %d is used in scanf() statement. So that, the value entered isreceived as an integer and %s for string.

6. Add a and b and store the anser in ‘sum’.

7. The format specifier %d is used in printf() statement. So that, the value is receivedas an integer.

/* Program to add two numbers */#include<stdio.h>

main()

{

int a, b, sum; /* variables declared as integers */

printf("Enter the numbers\n");

scanf("%d%d", &a, &b); /* to read two values in a and b*/

sum=a+b; /* to find sum*/

printf("Sum=%d" ,sum); /* output sum*/

}

Page 3: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 3: /* Program to calculate the area of a circle */

Float data type allows a variable to store decimal values. ’float’ keyword is used to declare the variables as floating point numbers.

1. The format specifier %f is used in scanf() statement. So that, the value entered is received

as an floating point number.

2. Calculate area using the mathematical equation ‘pi*radius*radius’ and stores the value in

area.

3. Display the calculated area

/* Program to calculate the area of a circle */

#include<stdio.h> /*Library file access*/

main() /* function heading*/

{

float radius, area; /* variable declarations*/

printf("Radius= \n") ; /* output statement*/

scanf("%f", &radius); /* input statement*/

area= 3.14159*radius*radius; /* assignment statement*/

printf("Area=%f\n" ,area); /* output the area*/

}

Exercise 4: /* Add, subtract, multiply and divide*/

1. Accept two numbers in variables ‘first’ and ‘second’.

2. Accept two integers and find their sum, difference, product and their division

3. Print the out put

4. Type casting is a way to convert a variable from one data type to another data type

/* Add, subtract, multiply and divide */

#include <stdio.h>

int main()

{

int first, second, add, subtract, multiply;

float divide;

Page 4: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("Enter two integers\n");

scanf("%d%d", &first, &second);

add = first + second;

subtract = first - second;

multiply = first * second;

divide = first / (float)second; //typecasting

printf("Sum = %d\n",add);

printf("Difference = %d\n",subtract);

printf("Multiplication = %d\n",multiply);

printf("Division = %f\n",divide);

return 0;

}

Exercise 5: /*Program to check whether the year is leap year or not */

1. A year is called leap year if it is divisible by 400. If year is not divisible by 400 as well as

100 but it is divisible by 4 then that year is also leap year.

2. Check whether the entered year is divisible by 400

/*Program to check whether the year is leap year or not */

#include <stdio.h>

int main()

{

int year;

printf("Enter a year to check if it is a leap year\n");

scanf("%d", &year);

if ( year%400 == 0)

printf("%d is a leap year.\n", year);

else if ( year%100 == 0)

printf("%d is not a leap year.\n", year);

else if ( year%4 == 0 )

printf("%d is a leap year.\n", year);

else

Page 5: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("%d is not a leap year.\n", year);

return 0;

}

Exercise 6: /* program to find hcf and lcm*/

1. The variable gcd stores the greatest common divisor of entered number

2. a%b calculates the remainder and store it in b. Repeat the while loop until b=0.

3. The variable lcm stores the lowest common multiple of entered numbers.

/* program to find hcf and lcm*/

#include <stdio.h>

int main()

{

int a, b, x, y, t, gcd, lcm;

printf("Enter two integers\n");

scanf("%d%d", &x, &y);

a = x; //Copy the value of x and y to a, b respectively

b = y;

while (b != 0) {

t = b;

b = a % b; // b stores the remainder

a = t;

}

gcd = a;

lcm = (x*y)/gcd;

printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);

printf("Least common multiple of %d and %d = %d\n", x, y, lcm);

return 0;

}

For Loop

The “for loop” loops from one number to another number and increases by a specified value each

time. The “for loop” uses the following structure:

Page 6: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

for (Start value; continue or end condition; increase value) {

statements; }

Exercise 7: /* Program to add n numbers */

1. Here the variable 'n' is used to store th enumber of numbers.

2. 'c' is used for count. Fr example, for first number c=1, second number c=2 etc..

3. loop continues until c<=n

/* Program to add n numbers */

#include <stdio.h>

int main()

{

int n, sum = 0, c, value;

printf("Enter the number of integers you want to add\n");

scanf("%d", &n);

printf("Enter %d integers\n",n);

for (c = 1; c <= n; c++)

{

scanf("%d",&value);

sum = sum + value;

}

printf("Sum of entered integers = %d\n",sum);

return 0;

}

Exercise 8: /* program to print patterns of stars*/

1. \n prints a new line character

/* program to print patterns of stars*/

Page 7: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

*

***

*****

*******

*********

#include <stdio.h>int main(){ int row, c, n, temp; printf("Enter the number of rows in pyramid of stars you wish to see "); scanf("%d",&n); temp = n; for ( row = 1 ; row <= n ; row++ ) { for ( c = 1 ; c < temp ; c++ ) printf(" "); temp--; for ( c = 1 ; c <= 2*row - 1 ; c++ ) printf("*"); printf("\n"); } return 0;}Exercise 9: /* Program to find factorial of a number */

Suppose, n = 5. So our for loop will run for the value of c = 1,2, 3, 4 and 5

c = 1, fact = 1 - This is the first iteration. Inside the loop the value of fact is updated as -

fact = fact * c. So fact = 1 * 1 = 1. c = 2, fact = 2

c = 3, fact = 6

c = 4, fact = 24.

/* Program to find factorial of a number */

#include <stdio.h>

main()

Page 8: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

int c, n, fact = 1; /* f is initialized to 1 */

printf("Enter a number to calculate it's factorial\n");

scanf("%d", &n);

for (c = 1; c <= n; c++) /* for loop for iteration*/

fact = fact * c; /* factorial calculation*/

printf("Factorial of %d = %d\n", n, fact);

}

Exercise 10: /* Program to find fibnacci series */

What is Fibonacci Series- By definition, the first two numbers in the Fibonacci sequence are 0

and 1, and each subsequent number is the sum of the previous two numbers

/* Program to find fibnacci series */

/* fibnacci series- 0 1 1 2 3 5.....etc */

#include<stdio.h>

main()

{

int k, r;

int i=0,j=1,f;

printf("Enter the number range:"); //Taking maximum numbers from user

scanf("%d",&r);

printf("FIBONACCI SERIES: ");

printf("%d %d",i,j); //printing first two values.

for(k=2;k<r;k++)

{

f=i+j; /* adding previous numbers */

i=j; /*assignment*/

j=f;

printf(" %d",j);

}

}

Page 9: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 11: /* Linear search c program*/

1. Declare the array of 100 elements starting from 0 ie, array[100]

2. Accept the value to be searched

3. Linear search is carried out from first element to last element, until the search item is found.

/* Linear search program*/

#include <stdio.h>int main(){ int array[100], search, c, n; printf("Enter the number of elements in array\n"); scanf("%d",&n); printf("Enter %d integer(s)\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); printf("Enter the number to search\n"); scanf("%d", &search); for (c = 0; c < n; c++) { if (array[c] == search) /* if required element found */ { printf("%d is present at location %d\n", search, c+1); break; } } if (c == n) printf("%d is not present in array.\n", search); return 0;}

Exercise 12: /* binary search*/

The code below assumes that the input numbers are in ascending order. It finds the position of

the search value within the sorted list. At each stage, the program compares the search value with

the middle value of the list. If the keys match, then a matching value has been found so its

position is returned. Otherwise, if the search value is less than the middle value, then the

program repeats its action on the sub-list to the left of the middle value or, if the input key is

Page 10: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

greater, on the sub-list to the right. If the remaining list to be searched is reduced to zero, then the

value cannot be found in the list and a special “Not found” indication is returned.

/* binary search*/

#include<stdio.h>int main() {int n, a[30], item, i, j, mid, top, bottom;printf("Enter how many elements you want:\n");scanf("%d", &n);printf("Enter the %d elements in ascending order\n", n);for (i = 0; i < n; i++) {scanf("%d", &a[i]);}printf("\nEnter the item to search\n");scanf("%d", &item);bottom = 1;top = n;do {mid = (bottom + top) / 2;if (item < a[mid])top = mid - 1;else if (item > a[mid])bottom = mid + 1;} while (item != a[mid] && bottom <= top);if (item == a[mid]) {printf("Binary search successfull!!\n");printf("\n %d found in position: %d\n", item, mid + 1);} else {printf("\n Search failed\n %d not found\n", item);}return 0;}If else condition

if ( TRUE ) {

/* Execute these statements if TRUE */}

Page 11: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

else { /* Execute these statements if FALSE */}

Exercise 13: program to checks whether an input alphabet is a vowel or not

1. The format specifier %c is used in scanf() statement. So that, the value is received as an

character

2. if condition checks the value received is A,E.I,OU or a,e,i,o,u. If it is true, print the out

put, else print as not a vowel.

/* program to checks whether an input alphabet is a vowel or not */

#include <stdio.h>

int main(){

char c;

printf("Enter an alphabet: ");

scanf("%c",&c);

if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U')

printf("%c is a vowel.",c);

else

printf("%c is a consonant.",c);

return 0;

}

While loop

while (test expression)

{

statements to be executed.

}

In the beginning of while loop, test expression is checked. If it is true, codes inside the body of

while loop, i.e, code/s inside parentheses are executed and again the test expression is checked

and process continues until the test expression becomes false.

Exercise 14: /* Program to reverse a number */

1. Initialize the variable reverse as zero

Page 12: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

2. first you multiply the value of reverse *10.

3. then add the value of reverse to n%10 (which gives the remainder)

4. divide the entered number by 10.

/* Program to reverse a number */

#include <stdio.h>

int main()

{

int n, reverse = 0;

printf("Enter a number to reverse\n");

scanf("%d",&n);

while (n != 0)

{

reverse = reverse * 10;

reverse = reverse + n%10;

n = n/10;

}

printf("Reverse of entered number is = %d\n", reverse);

return 0;

}

Exercise 15: //program to check whether a given number is palindrome or not

This program takes an integer from user and that integer is reversed. If the reversed

integer is equal to the integer entered by user then, that number is a palindrome if

not that number is not a palindrome.

//program to check whether a given number is palindrome or not

#include<stdio.h>

void main()

{

int rem, sum=0, temp, num;

printf("enter the number\n");

scanf("%d", &num);

Page 13: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

temp=num;

while(num>0)

{

rem=num%10;

sum=sum*10+rem;

num=num/10;

}

if(temp==sum)

printf("The given number is palindrome\n");

else

printf("The given number is not palindrome\n");

}

Exercise 16: //program to check given number is armstrong or not

A number is armstrong if the sum of cubes of individual digits of a number is equal to the

number itself. For example 371 is an armstrong number as 33 + 7

3 + 1

3 = 371

//program to check given number is armstrong or not

#include<stdio.h>

main()

{

int rem, sum=0, temp,num;

printf("Enter a number\n");

scanf("%d",&num);

temp=num;

while(num>0)

{

rem=num%10;

sum=sum+rem*rem*rem;

num=num/10;

}

if(temp==sum)

printf("The given number is armstrong\n");

Page 14: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

else

printf("The given number is not armstrong\n");

}

do while loop

The syntax of a do...while loop in C programming language is:

do

{

statement(s);

}

while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the

loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop

execute again. This process repeats until the given condition becomes false.

Exercise 17: //program to print even number up to limit n

1. first print the value of i

2. Increment the value of i by 2

3. then checks the condition i<=n

//program to print even number up to limit n

#include<stdio.h>

main()

{

int i=2,n;

printf("Enter the limit\n");

scanf("%d",&n);

do

{

printf("%d\n",i);

i =i+2;

Page 15: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

}

while(i<=n);

}

Switch statement

switch statement allows a variable to be tested for equality against a list of values. Each value is

called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C programming language is as follows:

switch(expression){

case constant-expression :

statement(s);

break; /* optional */

case constant-expression :

statement(s);

break; /* optional */

/* you can have any number of case statements */

default : /* Optional */

statement(s);

}

Exercise 18: /* Program using switch*/

#include <stdio.h>

int main ()

{

char grade = 'B'; /* local variable definition */

switch(grade)

{

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

case 'C' :

Page 16: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("Well done\n" );

break;

case 'D' :

printf("You passed\n" );

break;

case 'F' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

}

printf("Your grade is %c\n", grade);

return 0;

}

Functions

Each function behaves the same way as C language standard function main(). So a function will

have its own local variables defined. When a function is defined at any place in the program then

it is called function definition. A function declaration does not have any body and they just have

their interfaces. A function declaration is usually declared at the top of a C source file, or in a

separate header file. Generally a function will process information that is passed to it from the

calling portion of the program and return a single value.

Syntax: Return type function name (type1 arg1,type2 arg2....etc);

for example : int demo(int n1, int n2);

This is the declaration of function. The arguments are called formal arguments.

Accessing a function

A function can be accessed(i.e, Called) by specifying its name, followed by a list of arguments

enclosed in parentheses and separated by commas. If the function call does not require any

arguments, an empty pair of parentheses must follow the name of the function. The arguments

appear in the function call are referred to as actual arguments, in contrast to the formal

arguments that appear in the first line of the function definition.

Page 17: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Rewrite the above programs using functions.

Exercise 19: /* determine the largest of three integer quantities */

Here the function name is 'maximum'. And the formal arguments are x and y they are of integer

types. The function maximum is called at main program. d=maximum(a,b) Here a, b are the

actual arguments. When the function is called the value of actual arguments are copied into

formal arguments.

/* determine the largest of three integer quantities */

#include<stdio.h>

int maximum(int x,int y) // determine the largest of two integer quantities

{

int z;

z=(x>=y)?x:y; //ternary operator- if x>=y, x is assigned to z or y is assigned to z

return(z); // return the value to the main program

}

main()

{

int a,b,c,d;

/* read the integer quantities */

printf("\na=");

scanf("%d",&a);

printf("\nb=");

scanf("%d",&b);

printf("\nc=");

scanf("%d",&c);

/* calculate and display the maximum value*/

d=maximum(a,b); // function call or accessing a function

printf("\n\nmaximum=%d",maximum(c,d));

}

Exercise 20: /* Program to find the square of a number*/

Here 'square' is the function name, to find the square of an entered number

Page 18: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

/* Program to find the square of a number*/

#include<stdio.h>

// function prototype, also called function declaration

float square ( float x );

int main( ) // main function, program starts from here

{

float m, n ;

printf ( "\nEnter some number for finding square \n");

scanf ( "%f", &m ) ;

n = square ( m ) ; // function call

printf ( "\nSquare of the given number %f is %f",m,n );

}

float square ( float x ) // function definition

{

float p ;

p = x * x ;

return ( p ) ;

}

Exercise 21: /* Program to swap two numbers (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.

/* Program to swap two numbers (using call by value)*/

#include<stdio.h>

void swap(int a, int b); // function prototype, also called function declaration

int main()

{

int m = 22, n = 44;

printf(" values before swap m = %d \nand n = %d", m, n);

Page 19: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

swap(m, n); // calling swap function by value

}

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);

}

Arrays

C programming language provides a data structure called the array, which can store a fixed-size

sequential collection of elements of the same type. Instead of declaring individual variables, such

as number0, number1, ..., and number99, you declare one array variable such as numbers and use

numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific

element in an array is accessed by an index.

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements and the number of

elements required by an array as follows:

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than

zero and type can be any valid C data type. For example, to declare a 10-element array called

balance of type double, use this statement:

double balance[10];

Initializing Arrays

You can initialize array in C either one by one or using a single statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the

element within square brackets after the name of the array. For example:

Page 20: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary

variable. Following is an example which will use all the above mentioned three concepts viz.

declaration, assignment and accessing arrays:

Exercise 22: Example Program using array

#include <stdio.h>

int main ()

{

int n[ 10 ]; //n is an array of 10 integers

int i,j;

/* initialize elements of array n*/

for ( i = 0; i < 10; i++ )

{

n[ i ] = i + 100; /* set element at location i to i + 100 */

}

for (j = 0; j < 10; j++ ) /* output each array element's value */

{

printf("Element[%d] = %d\n", j, n[j] );

}

return 0;

}

Exercise 23: //program to find sum and average using array

The numbers are stored in the array 0 to n. a[0] stores the first value, a[1] stores the second etc.

Each value entered is added to the variable 's'. Finally the variable 's' contains the sum of entered

elements. Then find the average.

//program to find sum and average using array

#include<stdio.h>

main()

{

int i,a[50],n,s=0;

float avg, sum=0;

Page 21: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("enter the limit\n");

scanf("%d",&n);

printf("Enter the elements\n");

for(i=0;i<n;i++)

{

scanf("%d",&a[i]);

s=s+a[i];

}

avg=s/n;

printf("Sum=%d",s);

printf("Average=%f",avg);

}

Exercise 24:

//program to accept n numbers of array elements and find the largest

#include <stdio.h>

int main(){

int i,n;

float arr[100];

printf("Enter total number of elements(1 to 100): ");

scanf("%d",&n);

printf("\n");

for(i=0;i<n;++i) /* Stores number entered by user. */

{

printf("Enter Number %d: ",i+1);

scanf("%f",&arr[i]);

}

for(i=1;i<n;++i) /* Loop to store largest number to arr[0] */

{

if(arr[0]<arr[i]) /* Change < to > if you want to find smallest element*/

arr[0]=arr[i];

}

Page 22: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("Largest element = %.2f",arr[0]);

return 0;

}

Exercise 25:

//Ascending order sorting

#include<stdio.h>

main()

{

int i,j,n,x[10],temp;

printf(“Enter the number of elements in the array\n”);

scanf(“%d”,&n);

printf(“Enter %d elements\n”,n);

for(i=0;i<n;i++)

scanf(“%d”, &x[i]);

for(i=0;i<n-1;i++)

for(j=i+1;j<n;j++)

{

if(x[i]>x[j])

{

temp=x[i];

x[i]=x[j];

x[j]=temp;

}

}

printf(“The sorted array is \n”);

for(i=0;i<n;i++)

printf(“%d\t”, x[i]);

}

Exercise 26: /* Bubble sort */

Page 23: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Sort numbers in ascending order. Comparing each pair of adjacent items and swapping them if

they are in the wrong order.

/* Bubble sort */

#include <stdio.h>

int main(){ int array[100], n, c, d, swap;

printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]);

for (c = 0 ; c < ( n - 1 ); c++) { for (d = 0 ; d < n - c - 1; d++) { if (array[d] > array[d+1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } }

printf("Sorted list in ascending order:\n");

for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]);

return 0;}

Structures

A structure is a collection of variables under a single name. A structure type is usually defined

near to the start of a file using a typedef statement. typedef defines and names a new type,

allowing its use throughout the program.

typedef struct {

char name[64];

Page 24: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

char course[128]; int age; int year; } student;

This defines a new type student variables of type student can be declared as follows.

student st_rec;

Exercise 27: /* Program using structures */1. struct keyword is used to declare the structure. To access the members of the structure

telephone, you must use a dot between the structure name and the variablename(variables:name or number.)

2. TELEPHONE is the structure variable. Members of the structure can access by using thisvariable

/* Program using structures */ #include <stdio.h> #include <string.h>

typedef struct telephone { char *name; int number; }TELEPHONE;

int main() { TELEPHONE index;

index.name = "Jane Doe"; index.number = 12345; printf("Name: %s\n", index.name); printf("Telephone number: %d\n", index.number);

return 0; }

Strings

Strings in C are represented by arrays of characters. The end of the string is marked with a

Page 25: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

special character, the null character, which is simply the character with the value 0. #include

<string.h>, it must be included when handling with string functions.

char string[] = "Hello, world!";

In this case, we can leave out the dimension of the array, since the compiler can compute it for usbased on the size of the initializer (14, including the terminating \0).

Exercise28: //Array of Characters

1. The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.

#define token [value]

For example #define max 5 , it replaces the the variable 'max' with value 5

2. strlen() is used to get the length of string

//Array of Characters

#include<stdio.h>#include<string.h>

#define MAX_STRING_LEN 80

int main() { /* strings are array of characters * terminated by the NULL character * which is different from '0' */ char S[MAX_STRING_LEN]; int l, i; S[0] = 'a'; S[1] = 'b'; S[2] = 'c'; S[3] = 'd'; S[4] = 'e'; S[5] = 'g'; S[6] = '0'; S[7] = 0;

Page 26: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

l = strlen(S);

printf("S:\t%s\n",S); printf("length:\t%d\n",l); /* print characters in S */ printf("forward\n"); for (i = 0; i < l; ++i) printf("A[%d] = %c\n",i,S[i]); /* print characters in S backwards */ printf("\nbackward\n"); for (i = l-1; i >= 0; --i) printf("A[%d] = %c\n",i,S[i]);}

Exercise 29: //String IO

strings can be read using scanf with %s. strcmp for string comparisons, strcpy to copy strings

//String IO

#include<stdio.h>#include<string.h>

#define MAX_STRING_LEN 80

int main() {

char S1[MAX_STRING_LEN]; char S2[MAX_STRING_LEN]; int i, l;

printf("String:\t"); scanf("%s",S1);

/* we need to copy all the characters, and * the final NULL character! */

l = strlen(S1); for (i = 0; i < l+1; ++i) S2[i] = S1[i];

Page 27: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

S1[0] = S1[1] = S1[2] = '*'; /* change original S1 */ S1[3] = 0; printf("S1:\t%s\n",S1); /* print both strings */ printf("S2:\t%s\n",S2);

}

Exercise 30: //String Comparison

The strcmp function compares the contents of string1 and string2 and returns a value indicating their relationship.

if Return value < 0 then it indicates string1 is less than string2

if Return value > 0 then it indicates string2 is less than string1

if Return value = 0 then it indicates string1 is equal to string2

//String Comparison #include<stdio.h>#include<string.h>

#define MAX_STRING_LEN 80

int main() { char S1[MAX_STRING_LEN]; char S2[MAX_STRING_LEN]; int i, l, res;

printf("String1:\t"); scanf("%s",S1);

printf("String2:\t"); scanf("%s",S2);

res = strcmp(S1,S2);

printf("strcmp(%sS1,%sS2) = %d\n",S1,S2,res);

}

Exercise 31: //Copying Strings

Page 28: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

strcpy() is used for copying two strings//Copying Strings

#include<stdio.h>#include<string.h>

main(){ char source[] = "C program"; char destination[50]; strcpy(destination, source); printf("Source string: %s\n", source); printf("Destination string: %s\n", destination); return 0;}

Exercise 32: // Strcat

strcat() appends a copy of a second string

//Strcat

#include<string.h>#include<stdio.h>

#define MAX_STRING_LENGTH 80

int main() { /* strcat is another useful command: * */

char S1[MAX_STRING_LENGTH]; char S2[MAX_STRING_LENGTH];

strcat(S1,S2);

printf("S1:\t"); scanf("%s",S1);

printf("S2:\t"); scanf("%s",S2);

strcat(S1,S2);

printf("\nafter strcat(S1,S2)\n"); printf("S1:\t%s\n",S1);

Page 29: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("S2:\t%s\n",S2);

}

Pointers

A pointer is a variable whose value is the address of another variable, i.e., direct address of the

memory location. Like any variable or constant, you must declare a pointer before you can use it

to store any variable address. The general form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of

the pointer variable.

A Pointer variable stores the address of a memory location that stores the type to which it points

int *ptr; //stores the address of an int, ptr “points” to an int

char *cptr; //stores the address of a char,

//cptr “points to” a char

cptr’s type is a pointer to a char it can point to a memory location that stores a char value through

cptr we can indirectly access a char value.

int i; // Integer i

int *p; // Pointer to integer

int **m; // Pointer to int pointer

p = &i; // p now points to i

printf("%p", p); // Prints the address of i (in p)

m = &p; // m now points to p

printf("%p", m); // Prints the address of p (in m)

Page 30: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 33: Example program for pointers

Program to implement pointer. Here the variable ip(pointer variable) stores the address of 'var'.

The format specifier %x is used for displaying the address.

#include <stdio.h>

int main ()

{

int var = 20; /* actual variable declaration */

int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

printf("Address stored in ip variable: %x\n", ip ); /* address stored in pointer variable */

printf("Value of *ip variable: %d\n", *ip ); // access the value using the pointer

return 0;

}

Exercise 34: /*C program to add two numbers using pointers*/

Here the pointer vaiable s are p and q. p and q stores the address of entered numbers respectively.

*, the dereference operator, *p represents the value of p and *q represents the value of q.

/*C program to add two numbers using pointers*/

#include <stdio.h>int main(){ int first,second,*p,*q,sum=0;printf("Enter two integers to add\n");

scanf("%d%d",&first,&second);p=&first;q=&second;sum=*p+*q; //The values of p and q are added to sumprintf("Sum of entered numbers = %d\n",sum);return 0;}

Page 31: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 35:

Write a c program for finding factorial of a given number using pointers.

#include<stdio.h>void main(){int num,i,fac,*p1,*p2;//clrscr();p1=&num;p2=&fac;printf("Enter any number ");scanf("%d",p1);fac=1;for(i=1;i<=*p1;i++){ *p2=*p2*i;}printf("\nFactorial of %d is = %d",*p1,*p2);}

Exercise 36: //Pointers as Structure Objects

Here *stobj is declared as pointer and it stores the address of the vaiable 'obj'.

#include<stdio.h>

struct st{ int a; char ch; };

int main(void) { struct st obj; struct st *stobj = &obj;

stobj->a = 5; stobj->ch = 'a';

printf("\n [%d] [%c]\n", stobj->a, stobj->ch); return 0;

Page 32: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

}

Exercise 37: Example to use structure's member through pointer using malloc() function.

1. The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand

2. The function malloc is used to allocate a certain amount of memory during the execution of a program. The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.

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");

Page 33: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

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;

}

Page 34: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 1. * write a c program to input an integer as an integer* /

1. print out the number, one digit per line

i.e. input 1234

output 4

3

2

1

void main( )

{

int i;

int outnum;

printf("Input number please \n");

scanf("%i" ,&i);

while (i > 0)

{

outnum = i % 10;

printf("%i\n" ,outnum);

i = i / 10;

}

}

Exercise2. Programe to print the grade

#include<stdio.h>

void main ( )

{

int score;

printf("Enter the score\n");

scanf("%i",&score);

printf("You entered %i\n",score);

if (score < 0 || score> 100 )

printf("Impossible score\n");

else

{

Page 35: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

if (score >= 0 && score < 50 )

printf("F\n");

else

{

if (score >= 50 && score < 70)

printf("D\n");

else

{

if (score >= 70 && score < 80)

printf("C\n");

else if (score >= 80 && score < 90)

printf("B\n");

else if (score >= 90 && score <= 100)

printf("A\n");

else

printf("no way to get here \n");

} } }

}

Exercise3. write a program to solve for the real roots of the quadratic equation ax^2 + bx + c

#include <math.h>

void main ( )

{

float a, b, c;

float discriminant;

float xl, x2;

printf("\n\ninput a b and c separated by spaces \n");

scanf("%f %f %f',&a,&b,&c); /* input a , b , c * /

printf("you entered %f %f %f\n\n\n",a,b,c);

discriminant = ( b * b) - ( 4 * a * c);

if ( discriminant> 0 ) /* check for real or imaginary roots * /

{

if (a == 0)

{

Page 36: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

if ( b == 0 ) /* make sure not to divide by zero */

{

printf("x = 0 \n");

else

{

xl = (-c)/b;

printf("Single real root is %f\n",xl);

}

}

else

{

xl = ( -b + sqrt(b*b - 4*a*c)) / (2 * a);

x2 = ( -b - sqrt(b*b - 4*a*)) / ( 2 * a);

printf("Two real roots are \n");

printf("%f %f\n",xl,x2);

}

else if ( discriminant == 0)

{

printf("one real root \ n");

if (a == 0 )

{

xl = 0;

printf("xl = %f\n",xl);

}

else

{

xl = -b / (2*a);

printf("xl = %f\n",xl);

}

else

{

printf(“Imaginary Roots\n”);

}

Page 37: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf(“\n\n”);

} /* end program */

Exercise 4: write a c program to input an integer print out the number, one digit per line

i.e. input 1234

output 4

3

2

1

1. then print it out in reverse order

2. then print the english word beside each digit

void main ( )

{

int i,safe,outnu m;

int revnum = 0;

char * words[] = { "Zero", "Un", "Deux", "Trois", "Quatre", "Cinq", "Six", "Sept", "Huit", "Neuf”};

printf("Input number \n");

scanf("%i",&i);

while (i > 0)

{

outnum = i % 10; /* strip off last digit */

revnum = revnum * 10 + outnum;

printf("%i \n",outnum); /* print it */

i = i /10; /* divide current number by 10 effectively dropping last digit */

safe = revnum;

printf(''\n\ n'');

while ( revnum > 0 )

{

outnum = revnum % 10; /* strip off last digit */

printf("%i \n",outnum); /* print it */

revnum /= 10;

}

printf(''\n\n'');

Page 38: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

while (safe > 0 ) /* now print digit by digit with english words */

{

outnum = safe % 10; /* strip off last digit */

printf("%i\t",outnum); /* print it*/

printf(" % s\t",words [outnum]);

switch( outnum)

{

case 0:

printf("Zero\ n");

break;

case 1:

printf("One\ n");

break;

case 2:

printf("Two\ n");

break;

case 3:

printf("Three\ n");

break;

case 4:

printf ("Four\n");

break;

case 5:

printf("Five\ n");

break;

case 6:

printf("Six\n");

break;

case 7:

printf("Seven\n);

break;

case 8:

printf("Eight\ n");

Page 39: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

break;

case 9:

printf("Nine\n");

break;

}

safe /= 10; /* divide current number by 10 */

}

}

Exercise 5: program to calculate the average of a set of bowling scores

1. only count scores over 100 for person's average

2. print out the high and low scores, all scores, scores used in average

3. print out average

#define MAX_SCORES 100

#define MAX_SCORE 300

#define MIN_SCORE 0

#define MIN_LEAGUE_SCORE 100

main ( )

{

int scores[MAX_SCORES]; /* scores will be the array of scores entered * /

int numscores, i, score; /* numscores is the count of how many scores they want to enter */

int raw _scores_to_count = 0; /* scores_to_count are used to keep track of how many valid scores

there were */

int league_scores_to_count = 0;

int score_total = 0;

float raw_average; /* the averages are floats */

float league_average;

int high = 0; /* initialize current high and low score */

int low = MAX_SCORE;

printf("How many scores will you be entering?"); /* find out how many scores the person will be

entering */

scanf("%i", &numscores);

printf(''\nYou entered %d scores \n",numscores);

if ( numscores > MAX_SCORES)

Page 40: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

printf("CANNOT TAKE THAT MANY, %i is max\n",MNCSCORES);

exit(-1);

}

}

for (i = 1; i <= numscores; i++ ) /* for each of the scores requested, get the score */

{

printf(,'\nEnter score #%i: ",i);

scanf(" % i" ,&score );

printf("You entered %i\n",score);

if ( ( score < MIN_SCORE ) || ( score> MAX_SCORE)) /* if scores was less than 100 * /

/* don't count in average */

printf("Impossible score \n");

else

{

scores [raw _scores_to_count] = score; /* insert score into array */

score_total = score_total + score; /* update the total of all scores */

raw _scores_to_count++;

if ( score > high)

high = score;

if ( score < low)

low = score;

} /* end for loop */

if ( raw _scores_to_count > 0 )

{

raw _average = score_total/raw _scores_to_count;

printf(''\nRaw average = %.2f\n", raw_average);

printf("High score was %i \n",high);

printf("Low score was %i \n",low);

}

else

printf("No valid scores entered\n");

score_total = 0;

Page 41: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

league_scores_to_count = 0;

printf(''\n\nLIST OF LEAGUE SCORES USED IN AVERAGE\n");

for ( i= 0; i < raw _scores_to_count; i++ )

{

if (scores[i] > MIN_LEAGUE_SCORE )

{

printf(''\t%i\n'' ,scores [i]);

league_scores_to_count++;

score_total += scores[i];

if ( league_scores_to_count > 0 )

{

league_average = score_total / league_scores_to_count;

printf("\nLeague average = %.2f\n",league_average);

else

league_average = 100;

} /*end main */

Exercise 6:Passing arrays to subroutines

1. write functions to find out if a value is in an array

#define FAILURE 2

#define SUCCESS 1

2. function returns an integer

3. function name is determine

4. function accepts array of ten integers

5. what it is really accepting is a pointer to the first element of the array

int determine1 ( int values[5] )

{

int i;

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

{

if ( values[i] == 23 )

Page 42: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

return(SUCCESS);

}

return(FAILU RE);

int determine2 ( int * x)

{

int i;

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

{

if ( x[i] == 50 )

retum(SUCCESS );

}

return(FAILURE);

}

int determine3 ( int* x )

{

int i;

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

{

if ( *(x+i) == 50 )

return(SUCCESS);

}

retum(FAILURE);

}

main ( )

{

/* scores[0] is the zeroeth entry in scores */

/* &scores[0] is the address of the zeroeth entry */

/* scores all by itself, is semantically equivalent to &scores[0] */

int scores[5], i;

int determine 1 ( int values[5] );

int determine2( int * );

printf("Please enter five scores \n");

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

Page 43: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

printf("Score %i: ",i);

scanf("%i",&scores[i]);

printf(''\t %i \n",scores[i])

if ( determine1 (scores) == 1 )

printf("23 was in array \n");

else

printf("23 was not in array \n");

if ( determine2(scores) == 1 )

printf("50 was in array \n");

else

printf("50 was not in array \n");

if ( determine3(scores) == 1)

printf("50 was in array \n");

else

printf("50 was not in array \n");

}

Exercise 7:Sorting an array of integers

1. function to sort an array of integers into ascending order

2. first solution is to pass the size of the array into function

3. function returns nothing

4. its name is sort

5. it expects an integer array, doesn't know how big it will be yet

6. n will be an integer specifying the size of the array

void sort ( int *a, int n)

{

int i,j,temp;

for ( i = 0; i < n -1; i++ )

{

for (j = i + 1; j < n; j++ )

Page 44: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

if ( a[i] > a[j] )

{

temp = a[i];

a[i] = a[j];

a[j] = temp;

} /* end if */

} /* end for j loop */

} /* end for i loop */

} /* end sort function */

#define MAX_ARRAY 100

main ( ) /* main routine to call sort and display results */

{

int i;

int num_elements;

int array[MAX_ARRAY] ; /* don't know how big array needs to be */

void sort( int *, int);

printf("How many elements in array'!\n"); /* get and error check number of elements */

scanf("%i" ,&num_elements);

if (num_elements < 0 || num_elements > MAX_ARRAY)

{

printf("Impossible number of elements\n");

exit(-1);

}

for ( i = 0; i < num_elements; i++ ) /* have a good number of elements, continue */

{

printf("Enter value for element %i \n",i);

scanf(" %i ",&array[i]);

}

printf("The array before the sort is:\n");

for ( i = 0; i < num_elements; i++ )

printf("%i ",array [i]);

printf("\n\n");

Page 45: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

sort(array, num_elements); /* call the subroutine to do the sort

/* pass the address of the array and number of

elements */

printf("The array after the sort is: \n");

for ( i = 0; i < num_elements; i++ )

printf("%i ",array[i]);

printf(''\n\n'') ;

}

Exercise 8 :Row wise and column wise sorting of a matrix

1. function returns nothing

2. its name is sort

3. it expects an integer array, doesn't know how big it will be yet

4. n will be an integer specifying the size of the array

void sort ( int a[ ], int n)

{

int i,j,temp;

for (i = 0; i < n; i+ +)

{

for (j = i + 1; j < n; j++ )

{

if ( a[i] > a[j] )

{

temp = a[i];

a[i] = a[j];

a[j] = temp;

} /* end if */

} /* end for j loop *

} /* end for i loop */

} /* end sort function * /

#define ROWS 3

#define COLS 4

main( )

Page 46: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

int input_array[ROWS][COLS];

int temp_array[ROWS][COLS];

int final_array[ROWS][COLS];

int row[COLS], col[ROWS];

void sort ( int a[ ], int n );

int i,j;

printf(''\n''); /* get and print original array */

for (i = 0; i < ROWS; i++ )

{

for (j = 0; j < COLS; j++)

{

scanf("%i",&input_array[i][j]);

printf("%3i",input_array[i][j));

}

printf(''\n'');

}

for ( i = 0; i < ROWS; i++ ) /* sort by row */

{

for (j = 0; j < COLS; j++)

row[j] = input_array[i][j]:

sort(row,COLS);

for (j = 0; j < COLS; j++ )

temp_array[i][j] = row[j];

}

printf('\n\nAFfER SORTING ROWS\n"); /* print array */

for ( i = 0; i < ROWS; i++ )

{

for (j = 0; j < COLS; j++ )

printf("%3i" ,temp _array[i] u]);

printf('\n");

}

for (j = 0; j < COLS; j++ ) /* sort by column */

Page 47: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

for ( i = 0; i < ROWS; i++ )

col[i] = temp_array[i][j];

sort(col,ROWS);

for ( i = 0; i < ROWS; i++ )

final_array[i][j] = col[i];

}

printf(''\n\nAFTER SORTING COLS\n"); /* print array */

for ( i = 0; i < ROWS; i++ )

{

for (j = 0; j < COLS; j++ )

printf("%3i" ,final_array[i][j]):

printf'(“\n"):

}

printf('\n");

} /* end main */

Exercise 9 : Program to show the scope of variables

int i = 1; /* global variable */

void subr1(void);

void subr2(void);

main ( )

{

int i = 2; /* local i overrides global i * /

printf("AAA i = %i \n",i);

subrl( ); /* call subroutine to test scope */

{

int i = -8032;

printf(''\tBBB i = %i \n",i);

}

subr2( ); /* call subroutine to test scope */

}

void subrl( )

Page 48: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

int i = 23; /* local i overrides global i */

printf(''\tCCC( i = %i \n", i);

{

int i = -98; /* interior i overrides exterior i */

printf(''\t\tDDD i = %i \n",i);

}

}

void subr2( )

{

printf(''\t\t\tEEE i = %i \n",i); /* no local i, refers to global i */

{

printf(''\t\t\t\tFFF i = %i \n",i); /* no local i, refers to global i */

}

}

Exercise 10: write a c program that has a structure to keep track of what time it is now.

1. Structure should be able to store current hour, minutes, seconds

2. Display the current time and what time it would be after one second.

3. Continue to read in times until the time read in is -1 -1 -1

#include<stdio.h>

struct time //Structure declaration

{

int hour;

int minutes;

int seconds;

};

struct time time_update ( struct time ); //object creation for structure

struct time current_time;

struct time next_time;

void main( )

{

Page 49: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("Enter the time (hh:mm:ss): ");

scanf("%i: %i: %i",&current_time.hour,&current_time.minutes,&current_time.seconds);

/* loop until sentinel record is found */

while (current_time.hour != -1 && current_time.minutes !=-1&& current_time. seconds != -1 )

{

printf("You entered %.2i:%.2i:%.2i\n",current_time.hour,current_time.minutes,current_time.seconds);

next_time = time_update( current_time );

printf("Update time is %.2i:%.2i:%.2i\n",next_time.hour,next_time.minutes, next_time.seconds);

printf("Enter the time (hh:mm:ss): ");

scanf("%i:%i:%i", &current_time.hour,&current_time.minutes, &current_time.seconds);

}

}

/* function to update the time by one second */

struct time time_update(struct time now)

{

now.seconds++;

if ( now.seconds = 60 )

{

now.seconds = 0;

now.minutes++;

if ( now.minutes == 60 )

{

now.minutes = 0;

now.hour++;

if ( now.hour == 24 )

{

now.hour = 0;

}

}

}

return(now);

}

Page 50: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

POINTERS EXAMPLES

Example 1: Program increments the variable pointer to access each succeeding element of the array

1. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable.

#include <stdio.h>const int MAX = 3; int main (){ int var[] = {10, 100, 200}; int i, *ptr; ptr = var; /* array address in pointer */ for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr ); ptr++; /* move to the next location */ } return 0;}

Example 2: Array of Pointers

#include <stdio.h> const int MAX = 3; int main (){ int var[] = {1, 12, 23, 44}; int i, *ptr[MAX]; for ( i = 0; i < MAX; i++) { ptr[i] = &var[i]; /* assign the address of integer. */ } for ( i = 0; i < MAX; i++) { printf("Value of var[%d] = %d\n", i, *ptr[i] ); } return 0;}

Page 51: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Example 3: Array of pointers to character to store a list of strings

#include <stdio.h>const int MAX = 4; int main (){ char *names[] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali", }; int i = 0;

for ( i = 0; i < MAX; i++) { printf("Value of names[%d] = %s\n", i, names[i] ); } return 0;}

Example 4: Pointer to Pointer#include <stdio.h> int main (){ int var; int *ptr; int **pptr;

var = 3000; ptr = &var; /* take the address of var */

pptr = &ptr; /* take the address of ptr using address of operator & */

printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); /* take the value using pptr */ printf("Value available at **pptr = %d\n", **pptr);

return 0;}

Example 5: Passing pointers to functions

#include <stdio.h>#include <time.h>

Page 52: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

void getSeconds(unsigned long *par);

int main (){ unsigned long sec;

getSeconds( &sec ); printf("Number of seconds: %ld\n", sec ); /* print the actual value */

return 0;}

void getSeconds(unsigned long *par){ *par = time( NULL ); /* get the current number of seconds */ return;}

Example 6: Return pointer from functions

#include <stdio.h>#include <time.h> int * getRandom( ) /* function to generate and retrun random numbers. */{ static int r[10]; int i; srand( (unsigned)time( NULL ) ); //Initialize random number generator for ( i = 0; i < 10; ++i) { r[i] = rand(); printf("%d\n", r[i] ); } return r;} int main () /* main function to call above defined function */{ int *p; /* a pointer to an int */ int i;

p = getRandom(); for ( i = 0; i < 10; i++ ) {

Page 53: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("*(p + [%d]) : %d\n", i, *(p + i) ); } return 0;}

Exercise 7: Program to illustrate string concatenation

1. uses pointers

2. uses built in functions

#include <string.h>

#define MAX_SIZE 100

/* jtcat concatenates a and b into c, replace c if contains data */

void jtcat( char* a, char* b, char* c)

{

/* copy all of a into c, stop before copy null terminator */

while ( *a != '\0' )

{

*c++ = *a++;

}

/* copy all of b onto end of c * /

while (*b )

{

*c++ = *b++;

}

/* remember to tack null terminator onto end of c */

*c = '\0';

}

main ( )

{

void jtcat( char*, char*, char*);

/* jts concatenation routine */

/* call strcat, send s1 and s2 function sticks s2 onto back of s1, returns s1 */

char s1[] = {"Terrill"};

char s2[] = {"Owens"};

char sa[] = {"Oingo " } ;

Page 54: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

char sb[] = {"Boingo "};

char s3[MAX_SIZE];

char s4[MAX_SlZE];

char stringa[] = {"abcde "};

strcat(s1, s2);

printf("%s\n",s1);

/* call strcat, send s3 and s1 */

/* function sticks s1 onto end of s3, returns s3 */

strcat(s3,stringa);

strcat(s3,stringa);

strcat(s3,stringa);

strcat(s3,stringa);

strcat(s3,stringa);

strcat(s3,stringa);

printf("%s",s3);

printf("\n");

/* now use jtcat routine */

printf("%s\n",sa);

printf("%s\n",sb);

jtcat(sa,sb,s4);

printf("%s\n\n",s4);

}

Exercise 8: String Processing strcmp

#include<stdio.h>

#include <string.h>

int jteq(char *s1,char *s2)

{

while (*s1++==*s2++ )

{

if (*s1 == '\0' && *s2 == '\0')

return(0); /* 0 is code for “equal” in my routine */

}

Page 55: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

return (1); /* 1 is code for “not equal” in my routine */

}

void main()

{

int jteq( char *, char * );

char stra[] = "Terrill Owens";

char strb[] = "Terrill";

int equal_return;

char *strings[] ={"The Same", "Not The Same"};

int cmp_val1, cmp_val2, cmp_val3;

equal_return = jteq(stra,stra);

printf("%s and \n%s are %s \n\n",stra,stra,strings[equal_return]);

equal_return = jteq(stra,strb);

printf("%s and \n%s are %s \n\n",stra,strb,strings[equal_return]);

cmp_val1 = strcmp(stra,stra);

printf("cmp_val1 => %i \n",cmp_val1);

cmp_val2 = strcmp(stra,strb);

printf("cmp_val2 => %i \n",cmp_val2);

cmp_val3 = strcmp(strb,stra);

printf("cmp_val3 => %i \n",cmp_val3);

}

Exercise 9: Use of strcat, strlen, and strcmp functions

1. Write a program that will input a list of words until the word quit is entered.

2. Create one long string from all these words, seperating them in the created string by a dollar sign.

3. Do not allow the word foobar to be entered into your string. (ignore it if it is entered).

4. Print out the final created string.

#include<stdio.h>

#include <string.h>

void main ( )

{

int x;

char s[20];

char d[1000];

Page 56: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("Enter word\n");

scanf("%s",s);

x = strcmp(s,"quit");

while ( x != 0 ) /* strcmp returns FALSE if a match */

{

if ( strcmp(s,"foobar") )

{

strcat(d,s);

strcat(d,"$");

x = strlen(s);

printf("%s length => %i \n",s,x);

}

else

{

printf("Cannot insert that word\n");

}

printf("Enter word\n");

scanf("%s",s);

x = strcmp(s,"quit");

}

printf("Final word is %s\n",d);

}

Character Functions

Most compilers actually implement these as macros not functions.

#include <ctype.h>

0 equates to no, false

1 equates to yes, true

isalnum(c) is character c alphanumeric?

isalpha(c) is character c alphabetic?

iscntrl(c) is character c a control character?

isdigit(c) is character c a digit?

islower(c) is character c lower case?

isprint(c) is character c a printable character

Page 57: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

ispunct(c) is character c a punctuation character

isupper(c) is character c upper case?

isspace(c) is character c a white space character?

tolower(c) convert character c to lower case

toupper(c) convert character c to upper case

Exercise 10: Write a C program to: read in, as character strings, two arbitrarily large numbers

(ie: 37 digits) add them together and display the result

#include <stdio.h>

#include<string.h>

int jconv(char);

char jrev(int);

main()

{

char num1[20], num2[20], num3[21];

int n1 [20], n2 [20];

int n3 [21] ;

int len1, len2, lenmax;

int shuffle_dist, i;

int ans, carry;

for ( i = 0; i < 20; i++ )

{

num1 [ i] = 0x00;

num2 [ i] = 0x00;

num3 [ i] = 0x00;

}

printf("Enter first number\n");

scanf("%s",&num1[0]);

printf("Enter second number\n");

scanf("%s",&num2[0]);

printf("num1 char is %s \n", num1);

printf("num2 char is %s \n ",num2);

len1=strlen(num1); /* find out how long the string is */

len2=strlen(num2);

Page 58: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

if (len1==len2) /* find out which one is longer */

{

printf("Strings are same length\n"); /* you are okay, no shuffling required */

/* just reverse the strings */

lenmax =len1;

}

else

{

if (len1<len2 )

{

printf("len1 < len2\n" );

lenmax=len2;

printf("lenmax is %i \n",lenmax);

shuffle_dist=len2-len1;

printf("shuffle_dist is %i \n",shuffle_dist);

for (i=len1; i >= 0; i--) /* need to shuffle lenl and pad with O's */

num1[i+shuffle_dist] = num1[i];

for (i=0; i<shuffle_dist;i++ )

num1 [i] = '0';

}

else

{

printf("len1 > len2 \n");

lenmax = len1;

printf("lenmax is %i \n",lenmax);

shuffle_dist = len1-len2; /* need to shuffle len2 and pad with 0's */

for (i = len2; i >= 0 ; i--) /* need to shuffle len1 and pad with 0's */

num2[i+shuffle_dist] = num2[i];

for (i = 0; i < shuffle_dist; i++)

num2[i] = '0';

}

}

/*print after padding */

Page 59: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

printf("after padding num1 is %s \n",num1);

printf("after padding num2 is %s \n",num2);

for (i = 0; i < lenmax; i++) /* now convert from character to integer */

{

n1[i] = jconv( num1[i]);

n2[i] = jconv( num2[i]);

}

printf("after converting to array of integers \n");

for (i = 0; i<lenmax;i++ )

{

printf("%1i",n1[i]);

}

printf("\n");

for (i = 0;i<lenmax; i++)

{

printf ("%1i" ,n2[i]);

}

/* now start adding from the back to the front */

carry = 0;

for (i=lenmax-1; i >= 0; i-- )

{

ans = n2[i] + n1[i] + carry;

printf("ans is %i \n",ans);

carry = ans/10;

n3[i+1] = ans % 10;

}

n3[0]=carry;

printf("\n n3 array is \n");

for (i = 0; i <= lenmax; i++)

{

printf ("%1i",n3[i]);

}

/* now convert back to character */

Page 60: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

for(i = 0; i <= lenmax; i++)

num3[i] = jrev( n3[i]);

num3[lenmax + 1] = '\0';

printf("Final string is %s \n",num3);

}

int jconv(char c )

{

switch (c)

{

case '0':

return 0;

break;

case '1':

return 1;

break;

case '2':

return 2;

break;

case '3':

return 3;

break;

case '4':

return 4;

break;

case '5':

return 5;

break;

case '6':

return 6;

break;

case '7':

return 7;

break;

Page 61: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

case '8':

return 8;

break;

case '9':

return 9;

break;

}

}

char jrev(int i)

{

switch(i)

{

case 0:

return'0';

break;

case 1:

return'1';

break;

case 2:

return'2';

break;

case 3:

return'3';

break;

case 4:

return'4';

break;

case 5:

return'5';

break;

case 6:

return'6';

break;

Page 62: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

case 7:

return'7';

break;

case 8:

return'8';

break;

case 9:

return'9';

break;

}

}

Exercise 11: program for debt trade manipulation

1. let's assume that they cannot be traded on certain days, i.e. Christmas

2. let's refer to the structures via pointers

#include<stdio.h>

main ( ) {

int i;

struct debt_trade

{

int day;

int month;

int year;

float price;

float par;

};

struct debt_trade debts[5];

struct debt_trade *dtptr;

dtptr = &debts[0]; /* establish pointer to first element of array */

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

{

scanf("%i %i %i %f %f",&debts[i].day, &debts[i].month,&debts[i].year,&debts[i].price,&debts[i].par);

if (debts[i].day ==25 && debts[i].month==12 ) /* see if date is any good using array notation */

printf("%f %f CANNOT TRADE ON %i/%i/%i\n",debts[i].price,debts[i].par,

Page 63: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

debts[i].day,debts[i].month,debts[i].year);

else

printf("%f %f okay on %i/%i/%i", debts[i].price, debts[i].par,debts[i].day, debts[i].month,

debts[i].year);

if (dtptr->day == 25 && dtptr->month == 12) /* see if date is any good using pointer notation */

printf("%f %f CANNOT TRADE ON %i/%i/%i\n",

debts[i].price,debts[i].par,debts[i].day,debts[i].month,debts[i].year);

if (dtptr->day == 25 && debts[i].month == 12) /* see if date is any good using pointer and array

notation */

printf("%f %f CANNOT TRADE ON %i/%i/%i\n",debts[i].price,debts[i].par,

debts[i].day,debts[i].month, debts[i].year);

/* move the pointer ahead to next entry */

dtptr++;

} /* end for */

} //End of main

Sample output

1 1 1992 1.0 1.0

1 1 1993 123.5 1.07

2 28 1993 34.5 1.098

25 12 1980 1.0 1.98

23 111979 100.532.73

Sample Run

a.out < prog59.dat

1.000000 1.000000 okay on 1/1/1992

123.500000 1.070000 okay on 1/1/1993

34.500000 1.098000 okay on 2/28/1993

1.000000 1.980000 CANNOT TRADE ON 25/12/1980

1.000000 1.980000 CANNOT TRADE ON 25/12/1980

1.000000 1.980000 CANNOT TRADE ON 25/12/1980

100.5299992.730000 okay on 23/11/1979

Page 64: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

Exercise 12:Using Pointers in a Linked List

1. Demonstrates dynamic memory allocation with malloc

2. we need to read in numbers, don't know how many

#include <stdlib.h>

#include <stdio.h>

main ( )

{

struct lle /* a linked list entry structure definition */

{

int value; /* value in list */

int squared_value; /* value in list */

struct lle *next; /* pointer to next entry */

};

struct lle first_element; /* first entry in list */

struct lle *next_element; /* pointer to any entry in list */

int val;

printf("size of lle is %i\n",sizeof(first_element));

printf("Enter value to square and store (-1) to stop\n");

scanf("%i",&val);

next_element = &first_element; /* set up pointer to already established element */

while (val!= -1 ) /* enter value to square and store */

{

next_element->value = val;

next_element->squared_value = val * val;

/* returns a pointer to the memory allocated, pointer will be of type (char *) */

next_element->next = (struct lle*) malloc(sizeof(first_element)); /* allocate memory for another

structure */

printf("Enter value to square and store(-1) to stop\n");

scanf("%i",&val);

if(val !=-1)

next_element = next_element->next;

else

next_element->next = NULL;

Page 65: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

}

next_element =&first_element;

while (next_element != NULL)

{

/* print out values from this linked list element */

printf("value = %i squared %i\n",next_element->value, next_element->squared_value);

printf("\t This record stored at %p\n",next_element);

printf("\t This record points to record at %p\n\n",next_element->next);

/* advance pointer to next element in linked list */

next_element = next_element->next;

}

}

Exercise 13: write a C program to allow

1. User to input elements into a linked list

2.User to print linked list forwards

3. User to add elements to end of linked list

4. User to delete any element from list (if it is present) by searching for the first occurrance of the value

and deleting that item. implement as you deem fit (double linked list)

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <malloc.h>

struct lle

{

char value [10];

struct lle *p;

};

/* functions will be given pointer to head of list */

/* functions will return pointer to head of list */

struct lle *add_item(struct lle *);

struct lle *delete_item(struct lle *);

void print_list(struct lle *); /* function accepts pointer to head of list and returns nothing */

main()

Page 66: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

int choice;

struct lle *hptr = NULL;

for ( ; ; )

{

printf("\nDo you want to \n");

printf("l add an item\n");

printf("2 delete an item\n");

printf("3 print list\n");

printf ("4 quit\n");

scanf("%i",&choice);

switch(choice)

{

case 1:

hptr=add_item(hptr);

break;

case 2:

hptr=delete_item(hptr);

break;

case 3:

print_list (hptr);

break;

case 4:

printf ("Good-bye\n");

exit(1) ;

default:

printf ("Good-bye\n");

exit(-1) ;

}

} /* end forever loop */

} /* end main */

struct lle *add_item(struct lle *ptr)

{

Page 67: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

char word[50];

struct lle *tmp;

struct lle *original_head = ptr;

printf("Enter string to enter\n");

scanf("%s", &word[0]);

while (strlen(word)>20)

{

printf("Word too long, 20 chars max\n");

scanf("%s",&word[0]);

}

if(ptr == NULL) /* is the list currently empty? */

{

/* we are at the head of the list */

/* get more memory */

tmp= (struct lle *) malloc (sizeof(struct lle *));

if (tmp == NULL) /* make sure the malloc worked */

{

printf("malloc failed\n");

exit (- 2);

}

strcpy(tmp->value,word); /* assign value and pointer */

tmp->p = NULL;

return (tmp); /* return new head of list */

}

while ( ptr->p!=NULL) /* traverse the list */

{

ptr =ptr->p;

}

/* at this point in time, ptr is at the end of the list */

/* get more memory */

tmp = (struct lle *) malloc (sizeof(struct lle));

/* make sure the malloc worked */

if (tmp == NULL)

Page 68: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

{

printf("malloc failed\n");

exit(- 2);

}

ptr->p = tmp; /* add newly created tail item to list */

strcpy(tmp->value,word);

tmp->p = NULL;

return (original_head);

}

struct lle * delete_item(struct lle * ptr)

{

char word[50];

struct lle * pl;

struct lle * tmp;

if (ptr==NULL) /* is there anything In the list? */

{

printf("There are no items in list\n");

return (NULL); /* return that list is still empty */

}

printf("Enter string to delete\n");

scanf ("%s", &word [0]);

while (strlen(word) > 20 )

{

printf ("Word too long, 20 chars max\n");

scanf("%s",&word[0]);

}

if(strcmp(ptr->value,word)==0) /* is it at the head of the list? */

{

/* it is at the head of the list */

/* is this a singleton? */

if ( ptr->p == NULL)

{

/* give the memory back */

Page 69: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

free (ptr);

return (NULL); /* list is now empty */

}

else

{

tmp = ptr->p; /* return the pointer field of the head as the new head */

free (ptr);

return (tmp);

/* traverse list to find item */

tmp = ptr; /* save the head of the list */

pl = ptr; /* save the current position */

ptr = ptr->p; /* get the next position */

while (ptr!= NULL )

{

if (strcmp(ptr->value,word) == 0)

{

pl->p = ptr->p; /* delete the item */

free (ptr) ; /* give the memory back */

return (tmp) ; /* return original pointer */

}

ptr = ptr->p;

pl = pl->p;

}

printf("Item not in list \n"); /* if we got here then the word was not in the list */

return(tmp); /* return original head */

}}}

void print_list (struct lle * ptr)

{

if ( ptr == NULL )

{

printf("list is empty\n");

return;

}

Page 70: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

while ( ptr != NULL) /* traverse the list printing things as you go */

{

printf ("%s", ptr->value);

ptr = ptr->p;

}

return;

}

FILE

A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some

kind. The collection of bytes may be interpreted, for example, as characetrs, words, lines, paragraphs

and pages from a textual document; fields and records belonging to a database; or pixels from a

graphical image. The meaning attached to a particular file is determined entirely by the data structures

and operations used by a program to process the file. The file <stdio.h> contains declarations for the

Standard I/O library and should always be included at the very beginning of C programs using files.

Constants such as FILE, EOF and NULL are defined in <stdio.h>.

Typical Operations on file are

1. Open

2. Read

3. Write

4. Close

File is stored as sequence of bytes, logically contiguous (may not be physically contiguous on disk).

The last byte of a text file contains the end-of-file character (EOF), with ASCII code 1A (hex).

Specifying the file you wish to use is referred to as opening the file. When you open a file you must

also specify what you wish to do with it i.e. Read from the file, Write to the file, or both. Because you

may use a number of different files in your program, you must specify when reading or writing which

file you wish to use. This is accomplished by using a variable called a file pointer.

Every file you open has its own file pointer variable. When you wish to write to a file you specify the

file by using its file pointer variable.

You declare these file pointer variables as follows:

Page 71: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

FILE *fopen(), *fp1, *fp2, *fp3;

The variables fp1, fp2, fp3 are file pointers

File Opening

In C we use FILE * to represent a pointer to a file. You can use the fopen( ) function to create a new

file or to open an existing file, this call will initialize an object of the type FILE, which contains all the

information necessary to control the stream. Following is the prototype of this function call

FILE *fopen(const char *filename,const char *mode );

Here filename is string literal ,which you will use to name your file and access mode can have one of

the following values:

Reading a File

The simplest function to read a single character from a file:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is the

character read, or in case of any error it returns EOF. The following functions allow you to read a string

from a stream:

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the

read string into the buffer buf, appending a null character to terminate the string.

Page 72: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

If this function encounters a newline character '\n' or the end of the file EOF before they have read the

maximum number of characters, then it returns only the characters read up to that point including new

line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings

from a file but it stops reading after the first space character encounters.

Writing a File

Following is the simplest function to write individual characters to a stream:

int fputc(intc,FILE*fp);

The functionfputc() writes the character value of the argument c to the output stream referenced by fp.

It returns thewrittencharacter written on success otherwise EOF if there is an error. You can use the

following functions to write a null-terminated string to a stream:

int fputs(const char*s, FILE *fp );

The function fputs() writes the strings to the output stream referenced by fp. It returns a non-negative

value onsuccess, otherwiseEOF is returned in case of any error. You can use

int fprintf(FILE *fp,const char *format, ...)function as well to write a string into a file.

Try the following example:

#include<stdio.h>

main()

{

FILE *fp;

fp =fopen("/tmp/test.txt","w+");

fprintf(fp,"This is testing for fprintf...\n");

fputs("This is testing for fputs...\n",fp);

fclose(fp);

}

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and

writes two lines using two different functions.

Closing a File

Page 73: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

To close a file, use the fclose( ) function. The prototype of this function is:

int fclose (FILE *fp);

The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This

function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any

memory used for the file. The EOF is a constant defined in the header filestdio.h.There are various

functions provide by C standard library to read and write a file character by character or in the form of

a fixed length string.

EXAMPLES

Example 1: Write a C program to read name and marks of n number of students from user and

store them in a file

#include <stdio.h>

int main(){

char name[50];

int marks,i,n;

printf("Enter number of students: ");

scanf("%d",&n);

FILE *fptr;

fptr=(fopen("C:\\student.txt","w"));

if(fptr==NULL){

printf("Error!");

exit(1);

}

for(i=0;i<n;++i)

{

printf("For student%d\nEnter name: ",i+1);

scanf("%s",name);

printf("Enter marks: ");

scanf("%d",&marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);

}

fclose(fptr);

Page 74: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

return 0;

}

Example 2: Write a C program to read name and marks of n number of students from user and

store them in a file. If the file previously exits, add the information of n students.

#include <stdio.h>

int main(){

char name[50];

int marks,i,n;

printf("Enter number of students: ");

scanf("%d",&n);

FILE *fptr;

fptr=(fopen("C:\\student.txt","a"));

if(fptr==NULL){

printf("Error!");

exit(1);

}

for(i=0;i<n;++i)

{

printf("For student%d\nEnter name: ",i+1);

scanf("%s",name);

printf("Enter marks: ");

scanf("%d",&marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);

}

fclose(fptr);

return 0;

}

Example 3:Write a C program to write all the members of an array of strcutres to a file using

fwrite(). Read the array from the file and display on the screen.

#include <stdio.h>

Page 75: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

struct s

{

char name[50];

int height;

};

int main(){

struct s a[5],b[5];

FILE *fptr;

int i;

fptr=fopen("file.txt","wb");

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

{

fflush(stdin);

printf("Enter name: ");

gets(a[i].name);

printf("Enter height: ");

scanf("%d",&a[i].height);

}

fwrite(a,sizeof(a),1,fptr);

fclose(fptr);

fptr=fopen("file.txt","rb");

fread(b,sizeof(b),1,fptr);

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

{

printf("Name: %s\nHeight: %d",b[i].name,b[i].height);

}

fclose(fptr);

}

Example 4: Write a C program to merge two files.

#include <stdio.h>

#include <stdlib.h>

int main()

{

Page 76: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

FILE *fs1, *fs2, *ft;

char ch, file1[20], file2[20], file3[20];

printf("Enter name of first file\n");

gets(file1);

printf("Enter name of second file\n");

gets(file2);

printf("Enter name of file which will store contents of two files\n");

gets(file3);

fs1 = fopen(file1,"r");

fs2 = fopen(file2,"r");

if( fs1 == NULL || fs2 == NULL )

{

perror("Error ");

printf("Press any key to exit...\n");

getch();

exit(EXIT_FAILURE);

}

ft = fopen(file3,"w");

if( ft == NULL )

{

perror("Error ");

printf("Press any key to exit...\n");

exit(EXIT_FAILURE);

}

while( ( ch = fgetc(fs1) ) != EOF )

fputc(ch,ft);

while( ( ch = fgetc(fs2) ) != EOF )

fputc(ch,ft);

printf("Two files were merged into %s file successfully.\n",file3);

fclose(fs1);

fclose(fs2);

fclose(ft);

return 0;

Page 77: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

}

Example 5: Write a C program to find the number of lines in a text file.

#include <stdio.h>

int main()

{

FILE *fileptr;

int count_lines = 0;

char filechar[40], chr;

printf("Enter file name: ");

scanf("%s", filechar);

fileptr = fopen(filechar, "r");

chr = getc(fileptr); //extract character from file and store in chr

while (chr != EOF)

{

if (chr == 'n') //Count whenever new line is encountered

{

count_lines = count_lines + 1;

}

chr = getc(fileptr); //take next character from file.

}

fclose(fileptr); //close file.

printf("There are %d lines in %s in a file\n", count_lines, filechar);

return 0;

}

Example 6: Write a C program to find the size of file using file handling function

#include <stdio.h>

void main(int argc, char **argv)

{

FILE *fp;

Page 78: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

char ch;

int size = 0;

fp = fopen(argv[1], "r");

if (fp == NULL)

printf("\nFile unable to open ");

else

printf("\nFile opened ");

fseek(fp, 0, 2); /* file pointer at the end of file */

size = ftell(fp); /* take a position of file pointer un size variable */

printf("The size of given file is : %d\n", size);

fclose(fp);

}

Exercise:

1. write a C program that will copy one file to another file

2. the user should enter the file names from the command line

3. allow the user to enter file names from the command line OR if they don't put any file names on the

command line

4. allow the user to copy one file to multiple files simultaneously

5. is there a limit to how many output files they can create???

#include <stdlib.h>

#include <stdio.h>

#include<string.h>

/* argc is count of number of command line arguments */

/* argv is array of strings each string is one of the command line arguments */

void do_copy(char * s, char * d)

{

FILE *in, *out;

int c;

in = fopen(s,"r");

if (in == NULL)

{

printf("Cannot open %s \n",s);

Page 79: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

exit (-1);

}

out = fopen(d,"w");

if (out == NULL)

{

printf("Cannot open %s \n",d);

exit(-2);

}

while (c = getc(in) != EOF)

{

putc(c,out);

fclose(in);

fclose(out);

}}

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

{

int i;

char dest[20],source[20];

if (argc == 1)

{

printf("Please enter source file name \n");

scanf("%s", source);

printf("Please enter dest file name \n");

scanf("%s",dest);

}

else if (argc == 2)

{

strcpy(source,argv[1]);

printf("Please enter dest file name \n");

scanf("%s" ,dest);

}

if ( argc >= 3 )

{

Page 80: INTRODUCTION TO PROGRAMMING Exercise 1: /* … 5: /*Program to check whether the year is leap year or not */ 1. A year is called leap year if it is divisible by 400. If year is not

for ( i = 2; i < argc; i++ )

{

do_copy(argv[1],argv[i]);

}}

else

do_copy( source,dest);

printf("File copy complete \n");

}