Description
Lab 02: Introducing C
Programming (01)
Summary
● How to write a C program
● Data types in C
● Pointer in C
● Array in C
● String in C
How to write a C program:
Data types in C
Declare variables:
#include <stdio.h>
int main ()
{
// Variable definition: int a, b; int c; float f;
// actual initialization
a =10; b =20;
c = a + b;
printf(“value of c : %d “, c); f = 70.0/3.0;
printf(“value of f : %f “, f);
return 0;
}
Taking Inputs
scanf(const char *format, …) function reads input from the standard input stream stdin and scans that input according to format provided.
Character input:
Arrays in C
#include <stdio.h> int main ()
{ int n[ 10 ]; /* n is an array of 10 integers */ int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{ n[ i ] = i + 100; /* set element at location i to i + 100 */ }
/* output each array element’s value */
for (j = 0; j < 10; j++ )
{ printf(“Element[%d] = %d “, j, n[j] );
} return 0;
}
Multidimensional Arrays:
#include <stdio.h> int main ()
{
/* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j;
/* output each array element’s value */ for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{ printf(“a[%d][%d] = %d “, i,j, a[i][j] ); }
} return 0;
}
Pointers in C
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Following are the valid pointer declaration:
An example:
Output will be –
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. An example is –
The output will be –
Strings in C:
Strings are an array of characters ending with NULL in C.
Example program:
Output will be-
Functionalities provided by C –
Struct in C:
The struct statement defines a new data type, with more than one member for your program.
The format of the struct statement is –
An example program with struct –
The output will be –
Lab Tasks:
2. Write a C program to compute the perimeter and area of a rectangle with a height of 7 inches. and width of 5 inches.
3. Write a C program to compute the perimeter and area of a circle with a given radius.
4. Write a program in C to store elements in an array and print it.
5. Write a program in C to read n number of values in an array and display it in reverse order
6. Write a C program to convert a given integer (in seconds) to hours, minutes and seconds.
7. Write a C Program to Swap Values of Two Variables.
8. Write a C Program to Print ASCII Value of a given user input.
9. Write a C program to concatenate two strings given by the user.
10. Write a C program to store students information in a struct. Take input from users for a student and print it.




Reviews
There are no reviews yet.