IP LAB Manual
IP LAB Manual
C if...else Statement
In programming, decision making is used to specify the order in which statements are executed. In
this tutorial, you will learn to create decision making program using if...else statements.
C if statement
if (testExpression)
{
// statements
}
The if statement evaluates the test expression inside the parenthesis.
If the test expression is evaluated to true (nonzero), statements inside the body of if is executed.
If the test expression is evaluated to false (0), statements inside the body of if is skipped from execution.
Flowchart of if statement
Programming exercises
1) C Program to Check Whether a Number is Even or Odd
2) C Program to Check Whether a Character is Vowel or Consonant
3) C Program to Find the Largest Number Among Two Numbers
4) C Program to Find the Largest Number Among Three Numbers
5) C Program to Check Leap Year.
6) Write a C program to check whether a character is uppercase or lowercase alphabet.
7) Write a C program to input week number print week day.
8) Write a C program to input month number and print number of days in that month.
9) Write a C program to find all roots of a quadratic equation.
10) Write a C program to calculate profit or loss.
13) Write a C program to input electricity unit charges and calculate total electricity bill according to the
given condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill
Programming exercises
1. Write a C program to find maximum between two numbers using conditional operator.
2. Write a C program to find maximum between three numbers using conditional operator.
3. Write a C program to check whether a number is even or odd using conditional operator.
4. Write a C program to check whether year is leap year or not using conditional operator.
5. Write a C program to check whether character is an alphabet or not using conditional operator.
for loop
while loop
do...while loop
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test
expression is true (nonzero), codes inside the body of for loop is executed and the update expression is
updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
*
* *
* * *
* ** *
13) C program to print equilateral triangle or pyramid star pattern
*
**
****
******
14) C program to print Floyd's triangle
1
23
456
7 8 9 10
If the test expression is true (nonzero), codes inside the body of while loop are executed. The test expression is
evaluated again. The process goes on until the test expression is false.
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This
process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch
statement is cleaner and easy to understand.
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
When a case constant is found that matches the switch expression, control of the program passes to
the block of code associated with that case.
In the above pseudo code, suppose the value of n is equal to constant2. The compiler will execute
the block of code associate with the case statement until the end of switch block, or until the break
statement is encountered.
The break statement is used to prevent the code running into the next case.
Programming exercises
C Programming Arrays
An array is a collection of data that holds fixed
number of values of same type. For example: if you want to store marks of 100 students, you can create an
array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
1. One-dimensional arrays
data_type array_name[array_size];
For example,
float mark[5];
Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and
so on.
If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address
of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Programming exercises
1) C Program to Calculate Average of n (n < 10) numbers using arrays
2) C Program to Find Largest Element of an Array
3) Write a program in C to find the maximum and minimum element in an array.
4) Write a program in C to separate odd and even integers in separate arrays.
5) Write a program in C to sort elements of array in ascending order.
6) C Program to Add Two Matrix Using Multi-dimensional Arrays
7) C Program to multiply Two Matrix Using Multi-dimensional Arrays
Here, "c string tutorial" is a string. When, compiler encounter strings, it appends a null character /0 at the
end of string.
Declaration of strings
Strings are declared in a similar manner as arrays. Only difference is that, strings are of chartype.
Using arrays
char s[5];
Using pointers
char *p;
Initialization of strings
For convenience and ease, both initialization and declaration are done in the same step.
Using arrays
The given string is initialized and stored in the form of arrays as above.
Using pointers
char *c = "abcd";
You can use the scanf() function to read a string like any other data types.
However, the scanf() function only takes the first entered word. The function terminates when it
encounters a white space (or just space).
char c[20];
scanf("%s", c);
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
#include <stdio.h>
int main()
{
char name[30], ch;
int i = 0;
printf("Enter name: ");
while(ch != '\n') // terminates if user hit enter
{
ch = getchar();
name[i] = ch;
i++;
}
name[i] = '\0'; // inserting null character at end
printf("Name: %s", name);
return 0;
}
In the program above, using the function getchar(), ch gets a single character from the user each time.
This process is repeated until the user enters return (enter key). Finally, the null character is inserted at the
end to make it a string.
This process to take string is tedious.
To make life easier, there are predefined functions gets() and puts in C language to read and display string
respectively.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: "); IP Lab Manual Page | 16
puts(name); //Function to display string.
return 0;
}
Both programs have the same output below:
Output
Programming exercises
1) C Program to Reverse a String
2) C Program to Find the Length of a String
3) C program to Concatenate Two Strings
4) C Program to Copy a String
Depending on whether a function is defined by the user or already included in C compilers, there are two
types of functions in C programming
The standard library functions are built-in functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions are
available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output
on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these
functions are available for use.
User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by the user are called
user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many user-defined
functions as you want.
#include <stdio.h>
void functionName()
{
... .. ...
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
When the compiler encounters functionName(); inside the main function, control of the program jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside the
function definition are executed.
C allows you to define functions according to your need. These functions are known as user-defined
functions. For example:
createCircle() function
color() function
Example: User-defined function
Here is a example to add two integers. To perform this task, a user-defined function addNumbers() is
defined.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a,int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Function prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and
return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the program.
In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:
The function prototype is not needed if the user-defined function is defined before the main() function.
In the above example, function call is made using addNumbers(n1,n2); statement inside the main().
Function definition
Function definition contains the block of code to perform a specific task i.e. in this case, adding two numbers
and returning it.
The type of arguments passed to a function and the formal parameters must match, otherwise the compiler
throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float
type.
The return statement terminates the execution of a function and returns a value to the calling function. The
program control is transferred to the calling function after return statement.
In the above example, the value of variable result is returned to the variable sum in the main() function.
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type
specified in function prototype and function definition must
match.
For better understanding of arguments and return value from the function, user-defined functions can be
categorized as:
The 4 programs below check whether an integer entered by the user is a prime number or not. And, all these
programs generate the same output.
The 4 programs below check whether an integer entered by the user is a prime number or not. And, all these
programs generate the same output.
The checkPrimeNumber() function takes input from the user, checks whether it is a prime number or
not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main() function indicates that
no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
Here, the getInteger() function takes input from the user and returns it. The code to check whether a
number is prime or not is inside the main() function.
int main()
{
int n;
return 0;
}
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime number
or not and displays the appropriate message.
int main()
if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function
int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;
The checkPrimeNumber() function checks whether the passed argument is prime or not. If the passed
argument is a prime number, the function returns 0. If the passed argument is a non-prime number, the
function returns 1. The return value is assigned to flag variable.
Pointers are used in C program to access the memory and manipulate the address.
Address in C
Before you get into the concept of pointers, let's first get familiar with address in C.
If you have a variable var in your program, &var will give you its address in the memory, where & is
commonly called the reference operator.
You must have seen this notation while using scanf() function. It was used in the function to store the user
inputted value in the address of var.
scanf("%d", &var);
Value: 5
Address: 2686778
Note: You may obtain different value of address while using this code.
In above source code, value 5 is stored in the memory location 2686778. var is just the name given to that
location.
Pointer variables
In C, there is a special variable that stores just the address of another variable. It is called Pointer variable or,
simply, a pointer.
Declaration of Pointer
data_type* pointer_variable_name;
As discussed, & is called reference operator. It gives you the address of a variable.
Likewise, there is another operator that gets you the value from the address, it is called a dereference
operator (*).
Below example clearly demonstrates the use of pointers, reference operator and dereference operator.
Note: The * sign when declaring a pointer is not a dereference operator. It is just a similar notation that
creates a pointer.
Address of c: 2686784
Value of c: 2
2. c=22; assigns 22 to the variable c, i.e.,22 is stored in the memory location of variable c.
Note that, when printing &c (address of c), we use %u rather than %d since address is usually
expressed as an unsigned integer (always positive).
5. Since, pointer pc points to the same address as c, value pointed by pointer pc is 11 as well.
Printing the address and content of pc shows the updated content as 11.
int c, *pc;