bits pilani, dubai campus dubai international …bits pilani, dubai campus dubai international...
TRANSCRIPT
BITS PILANI, DUBAI CAMPUS
DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI
FIRST SEMESTER 2015 - 2016
COURSE : COMPUTER PROGRAMMING (CS F111)
Example program (for loop) in C:
In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main() {
int i;
for(i=0;i<10;i++) {
printf("%d ",i); }
}
Output:
0 1 2 3 4 5 6 7 8 9
Example program (while loop) in C:
In while loop control statement, loop is executed until condition becomes
false.
#include <stdio.h>
int main()
{ int i=3;
while(i<10)
{ printf("%d\n",i);
i++;
}
}
Output:
3 4 5 6 7 8 9
Example program (do while loop) in C:
In do..while loop control statement, while loop is executed irrespective
of the condition for first time. Then 2nd time onwards, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{ int i=1;
do {
printf("Value of i is %d\n",i); i++;
}while(i<=4 && i>=2);
}
Output:
Value of i is 1
Value of i is 2 Value of i is 3
Value of i is 4
Example program for switch..case statement in C:
#include <stdio.h>
int main () {
int value = 3;
switch(value) {
case 1: printf(“Value is 1 \n” );
break; case 2:
printf(“Value is 2 \n” ); break;
case 3: printf(“Value is 3 \n” );
break; case 4:
printf(“Value is 4 \n” ); break;
default :
printf(“Value is other than 1,2,3,4 \n” ); }
return 0; }
Output:
Value is 3
Example program for break statement in C:
#include <stdio.h> int main()
{
int i;
for(i=0;i<10;i++) {
if(i==5) {
printf(“\nComing out of for loop when i = 5″); break;
} printf(“%d “,i);
}
}
Output:
0 1 2 3 4
Coming out of for loop when i = 5
Example program for continue statement in C:
#include <stdio.h> int main()
{
int i; for(i=0;i<10;i++)
{ if(i==5 || i==6)
{ printf(“\nSkipping %d from display using ” \
“continue statement \n”,i); continue;
} printf(“%d “,i);
} }
Output:
0 1 2 3 4 Skipping 5 from display using continue statement
Skipping 6 from display using continue statement 7 8 9
Example program for goto statement in C:
#include <stdio.h> int main()
{ int i;
for(i=0;i<10;i++) {
if(i==5)
{ printf(“\nWe are using goto statement when i = 5″);
goto HAI; }
printf(“%d “,i); }
HAI : printf(“\nNow, we are inside label name \”hai\” \n”);
}
Output:
0 1 2 3 4 We are using goto statement when i = 5
Now, we are inside label name “hai”
Example program for one dimensional array in C:
#include<stdio.h>int main(){
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf(“value of arr[%d] is %d \n”, i, arr[i]);
}
}
Output:
value of arr[0] is 10 value of arr[1] is 20
value of arr[2] is 30 value of arr[3] is 40
value of arr[4] is 50
Example program for two dimensional array in C:
#include<stdio.h>int main(){
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf(“value of arr[%d] [%d] : %d\n”,i,j,arr[i][j]);
}
}
}
Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
Example program for C string:
#include <stdio.h>
int main ()
{ char string[20] = "fresh2refresh.com";
printf("The string is : %s \n", string );
return 0; }
Output:
The string is : fresh2refresh.com
Simple example program for C function:
As you know, functions should be declared and defined before
calling in a C program. In the below program, function “square” is called from main function.
The value of “m” is passed as argument to the function “square”. This value is multiplied by itself in this function and multiplied value “p” is
returned to main function from function “square”.
#include<stdio.h>
// function prototype, also called function declaration float square ( float x );
// main function, program starts from here
int main( ) {
float m, n ;
printf ( "\nEnter some number for finding square \n"); scanf ( "%f", &m ) ;
// function call
n = square ( m ) ; printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{ float p ;
p = x * x ; return ( p ) ;
}
Output:
Enter some number for finding square
2 Square of the given number 2.000000 is 4.000000
4. How to call C functions in a program?
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. Call by value:
In call by value method, the value of the variable is passed to the
function as parameter. The value of the actual parameter can not be modified by formal
parameter. Different Memory is allocated for both actual and formal parameters.
Because, value of actual parameter is copied to formal parameter.
Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
Example program for C function (using call by value):
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
// function prototype, also called function declaration void swap(int a, int b);
int main()
{ int m = 22, n = 44;
// calling swap function by value printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n); }
void swap(int a, int b)
{ int tmp;
tmp = a;
a = b; b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b); }
Output:
values before swap m = 22 and n = 44
values after swap m = 44 and n = 22
2. Call by reference:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both parameters.
Example program for C function (using call by reference):
In this program, the address of the variables “m” and “n” are passed to the function “swap”.
These values are not copied to formal parameters “a” and “b” in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.
#include<stdio.h>
// function prototype, also called function declaration void swap(int *a, int *b);
int main()
{
int m = 22, n = 44; // calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b) {
int tmp; tmp = *a;
*a = *b; *b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b); }
Output:
values before swap m = 22 and n = 44
values after swap a = 44 and b = 22
Pointers in C: Pointer is a variable that stores/points the address of another
variable. C Pointer is used to allocate memory dynamically i.e. at run
time. The pointer variable might be belonging to any of the data type such
as int, float, char, double, short etc.
Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a
normal variable.
Key points to remember about pointers in C:
Normal variable stores the value whereas pointer variable stores the
address of the variable. The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable. * symbol is used to get the value of the variable that the pointer is
pointing to. If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers.
But, Pointer addition, multiplication, division are not allowed. The size of any pointer is 2 byte (for 16 bit compiler).
Example program for pointer in C:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q’s value using ptr variable */
printf(“%d”, *ptr);
return 0;
}
OUTPUT: 50
Example program for C structure:
This program is used to store and access “id, name and percentage” for one student. We can also store and access these data for many students
using array of structures. You can check “C – Array of Structures“ to know how to store and access these data for many students.
#include <stdio.h> #include <string.h>
struct student
{ int id;
char name[20]; float percentage;
};
int main() {
struct student record = {0}; //Initializing to null
record.id=1;
strcpy(record.name, "Raju"); record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage);
return 0; }
Output:
Id is: 1 Name is: Raju
Percentage is: 86.500000
Example program – Another way of declaring C structure:
In this program, structure variable “record” is declared while
declaring structure itself. In above structure example program, structure variable “struct student record” is declared inside main function which is
after declaring structure.
#include <stdio.h> #include <string.h>
struct student
{ int id;
char name[20];
float percentage; } record;
int main()
{
record.id=1; strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage); return 0;
}
Output:
Id is: 1 Name is: Raju
Percentage is: 86.500000
Example program for C typedef:
// Structure using typedef:
#include <stdio.h>
#include <string.h>
typedef struct student {
int id; char name[20];
float percentage; } status;
int main()
{ status record;
record.id=1; strcpy(record.name, "Raju");
record.percentage = 86.5; printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage); return 0;
}
Output:
Id is: 1
Name is: Raju Percentage is: 86.500000
Example program for C union:
#include <stdio.h>
#include <string.h>
union student {
char name[20]; char subject[20];
float percentage; };
int main()
{
union student record1; union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju"); strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n"); printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject); printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani"); printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50; printf(" Percentage : %f \n", record2.percentage);
return 0; }
Output:
Union record1 values example
Name : Subject :
Percentage : 86.500000;
Union record2 values example Name : Mani
Subject : Physics Percentage : 99.500000
C type casting example program:
In the below C program, 7/5 alone will produce integer value as 1. So, type cast is done before division to retain float value (1.4).
#include <stdio.h> int main ()
{ float x;
x = (float) 7/5; printf("%f",x);
}
Output:
1.400000
Storage Class (lifetime and scope of variables): auto,extern,static, register
Example program for auto variable in C:
The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto variables by default.
#include<stdio.h>
void increment(void); int main()
{
increment(); increment();
increment(); increment();
return 0; }
void increment(void) {
auto int i = 0 ; printf ( “%d “, i ) ;
i++; }
Output:
0 0 0 0
Example program for static variable in C:
Static variables retain the value of the variable between different
function calls.
//C static example #include<stdio.h>
void increment(void);
int main() {
increment(); increment();
increment(); increment();
return 0; }
void increment(void) {
static int i = 0 ; printf ( “%d “, i ) ;
i++; }
Output:
0 1 2 3
Example program for extern variable in C:
The scope of this extern variable is throughout the main program. It is
equivalent to global variable. Definition for extern variable might be anywhere in the C program.
#include<stdio.h>
int x = 10 ; int main( )
{ extern int y;
printf(“The value of x is %d \n”,x); printf(“The value of y is %d”,y);
return 0;
} int y=50;
Output:
The value of x is 10
The value of y is 50
Example program for register variable in C:
Register variables are also local variables, but stored in register
memory. Whereas, auto variables are stored in main CPU memory. Register variables will be accessed very faster than the normal
variables since they are stored in register memory rather than main
memory. But, only limited variables can be used as register since register size is
very low. (16 bits, 32 bits or 64 bits)
#include <stdio.h> int main()
{ register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array arr[1] = 20;
arr[2] = 30; arr[3] = 40;
arr[4] = 50; for (i=0;i<5;i++)
{ // Accessing each variable
printf(“value of arr[%d] is %d \n”, i, arr[i]); }
return 0; }
Output:
value of arr[0] is 10 value of arr[1] is 20
value of arr[2] is 30 value of arr[3] is 40
value of arr[4] is 50
Example program for #define, #include preprocessors in C:
#define - This macro defines constant value and can be any of the basic data types.
#include <file_name> - The source code of the file “file_name” is included in the main C program where “#include <file_name>” is
mentioned.
#include <stdio.h>
#define height 100
#define number 3.14 #define letter 'A'
#define letter_sequence "ABC" #define backslash_char '\?'
void main()
{ printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence); printf("value of backslash_char : %c \n", backslash_char);
}
Output:
value of height : 100 value of number : 3.140000
value of letter : A value of letter_sequence : ABC
value of backslash_char : ?
Command line arguments in C:
main() function of a C program accepts arguments from command line
or from other shell scripts by following commands. They are,
argc
argv[]
where,
argc - Number of arguments in the command line including program
name argv[] – This is carrying all the arguments
In real time application, it will happen to pass arguments to the main
program itself. These arguments are passed to the main () function while executing binary file from command line.
For example, when we compile a program (test.c), we get executable file in the name “test”.
Now, we run the executable “test” along with 4 arguments in command line like below.
./test this is a program
Where,
argc = 5
argv[0] = “test”
argv[1] = “this”
argv[2] = “is” argv[3] = “a”
argv[4] = “program” argv[5] = NULL
Example program for argc() and argv() functions in C:
#include <stdio.h> #include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{ if(argc!=5)
{ printf("Arguments passed through command line " \
"not equal to 5"); return 1;
}
printf("\n Program name : %s \n", argv[0]); printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]); printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
return 0; }
Output:
Program name : test 1st arg : this
2nd arg : is 3rd arg : a
4th arg : program 5th arg : (null)