0% found this document useful (0 votes)
282 views

C Programming Lab

The document provides 15 code examples of basic C programming concepts and problems. The examples cover a range of fundamental programming tasks like calculating sums, interests, areas of shapes, sorting numbers, checking types of numbers, and more. Each example problem is presented with its corresponding C code solution to demonstrate how each concept can be programmed in C.

Uploaded by

Faizan Moin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
282 views

C Programming Lab

The document provides 15 code examples of basic C programming concepts and problems. The examples cover a range of fundamental programming tasks like calculating sums, interests, areas of shapes, sorting numbers, checking types of numbers, and more. Each example problem is presented with its corresponding C code solution to demonstrate how each concept can be programmed in C.

Uploaded by

Faizan Moin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

C Programming

Link: http://www.c4learn.com/c-programs/
1. C Program to find sum of two numbers
#include<stdio.h>
int main()
{
int a, b, sum;
printf("\nEnter two no: ");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum : %d", sum);
return(0);
}

2. C Program to find Simple interest


#include<stdio.h>
int main()
{
int amount, rate, time, si;

printf("\nEnter Principal Amount : ");


scanf("%d", &amount);

printf("\nEnter Rate of Interest : ");


scanf("%d", &rate);

printf("\nEnter Period of Time : ");


scanf("%d", &time);
si = (amount * rate * time) / 100;
printf("\nSimple Interest : %d", si);

return(0);
}

3. C Program to find area and circumference of circle

#include<stdio.h>

int main()
{
int rad;
float PI = 3.14, area, ci;

printf("\nEnter radius of circle: ");


scanf("%d", &rad);

area = PI * rad * rad;


printf("\nArea of circle : %f ", area);
ci = 2 * PI * rad;
printf("\nCircumference : %f ", ci);

return (0);
}

4. C program to obtain second order quadratic equation


#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c;
floatdesc, root1, root2;
printf("\nEnter the Values of a : ");
scanf("%f", &a);
printf("\nEnter the Values of b : ");
scanf("%f", &b);
printf("\nEnter the Values of c : ");
scanf("%f", &c);

desc = sqrt(b * b - 4 * a * c);


root1 = (-b + desc) / (2.0 * a);
root2 = (-b - desc) / (2.0 * a);

printf("\nFirst Root : %f", root1);


printf("\nSecond Root : %f", root2);
return (0);
}
5. C Program to Find Area of Scalene Triangle :
#include<stdio.h>
#include<math.h>

int main() {
int s1, s2, angle;
float area;

printf("\nEnter Side1 : ");


scanf("%d", &s1);

printf("\nEnter Side2 : ");


scanf("%d", &s2);

printf("\nEnter included angle : ");


scanf("%d", &angle);

area = (s1 * s2 * sin((M_PI / 180) * angle)) / 2;

printf("\nArea of Scalene Triangle : %f", area);


return (0);
}

6.C Program for Beginners : Area of Square


#include<stdio.h>

int main() {
int side, area;
printf("\nEnter the Length of Side : ");
scanf("%d", &side);

area = side * side;


printf("\nArea of Square : %d", area);

return (0);
}

7.C Program for Beginners : Area of Circle


#include<stdio.h>
int main()
{
float radius, area;

printf("\nEnter the radius of Circle : ");


scanf("%d", &radius);

area = 3.14 * radius * radius;


printf("\nArea of Circle : %f", area);

return (0);
}

8. C Program to find greatest in 3 numbers


#include<stdio.h>
int main() {
int a, b, c;
printf("\nEnter value of a, b & c : ");
scanf("%d %d %d", &a, &b, &c);
if ((a > b) && (a > c))
printf("\na is greatest");
if ((b > c) && (b > a))
printf("\nb is greatest");
if ((c > a) && (c > b))
printf("\nc is greatest");
return(0);

9.C Program for Exponent Series :

#include<stdio.h>
#define ACCURACY 0.0001
int main() {
int n, count;
float x, term, sum;
printf("\nEnter value of x :");
scanf("%f", &x);
n = term = sum = count = 1;
while (n <= 100)
{
term = term * x / n;
sum = sum + term;
count = count + 1;

if (term < ACCURACY)


n = 999;
else
n = n + 1;
}
printf("\nTerms = %d Sum = %f", count, sum);
return 0;
}

9. Problem Statement : Write a program to read the values of


x, y and z and print the results of the following expressions in
one line.
1. (x+y+z) / (x-y-z)
2. (x+y+z) / 3
3. (x+y) * (x-y) * (y-z)
#include<stdio.h>
#include<conio.h>

void main() {
int x, y, z;
float a, b, c;
clrscr();

printf("\nEnter the values of x,y and z : ");


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

a = (x + y + z) / (x - y - z);
b = (x + y + z) / 3;
c = (x + y) * (x - y) * (y - z);

printf("\nValue of a = %f",a);
printf("\nValue of b = %f",b);
printf("\nValue of c = %f",c);

getch();
}

10.Write a C program that reads the customer number and


power consumed and prints the amount to be paid by the
customer.

#include<stdio.h>
#include<conio.h>
void main() {

intcust_no, powerUsage;
float amount;
clrscr();

printf("Enter the customer number: ");


scanf("%d", &cust_no);
printf("Enter the power consumed: ");
scanf("%d", &powerUsage);

if (powerUsage>= 0 &&powerUsage<= 200)


amount = powerUsage * 0.50;
else if (powerUsage> 200 &&powerUsage< 400)
amount = 100 + ((powerUsage - 200) * 0.65);
else if (powerUsage> 400 &&powerUsage<= 600)
amount = 230 + ((powerUsage - 400) * 0.80);

printf("Amount to be paid by customer no. %d is Rs.:%5.2f.",


cust_no, amount);

getch();
}

11.C Program to calculate gross salary of a person.


#include<stdio.h>

int main() {
intgross_salary, basic, da, ta;

printf("Enter basic salary : ");


scanf("%d", &basic);

da = (10 * basic) / 100;


ta = (12 * basic) / 100;

gross_salary = basic + da + ta;

printf("\nGross salary : %d", gross_salary);


return (0);
}

12.C Program to reverse a given number


#include<stdio.h>

int main() {
intnum, rem, rev = 0;

printf("\nEnter any no to be reversed : ");


scanf("%d", &num);

while (num>= 1) {
rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
printf("\nReversed Number : %d", rev);
return (0);
}

13. Program to convert temperature from degree


centigrade to Fahrenheit

#include<stdio.h>

int main() {
floatcelsius, fahrenheit;

printf("\nEnter temp in Celsius : ");


scanf("%f", &celsius);

fahrenheit = (1.8 * celsius) + 32;


printf("\nTemperature in Fahrenheit : %f ", fahrenheit);

return (0);

}
Calender Program in C Programming Language :
14, Program will accept Year,Month and Date
from the user and will display the day of the
month.

#include<stdio.h>
#include<conio.h>
#include<math.h>

intfm(int date, int month, int year) {


intfmonth, leap;

//leap function 1 for leap & 0 for non-leap


if ((year % 100 == 0) && (year % 400 != 0))
leap = 0;
else if (year % 4 == 0)
leap = 1;
else
leap = 0;

fmonth = 3 + (2 - leap) * ((month + 2) / (2 * month))


+ (5 * month + month / 9) / 2;

//bring it in range of 0 to 6
fmonth = fmonth % 7;

returnfmonth;
}

//----------------------------------------------
intday_of_week(int date, int month, int year) {

intdayOfWeek;
int YY = year % 100;
int century = year / 100;

printf("\nDate: %d/%d/%d \n", date, month, year);

dayOfWeek = 1.25 * YY + fm(date, month, year) + date - 2 *


(century % 4);

//remainder on division by 7
dayOfWeek = dayOfWeek % 7;

switch (dayOfWeek) {
case 0:
printf("weekday = Saturday");
break;
case 1:
printf("weekday = Sunday");
break;
case 2:
printf("weekday = Monday");
break;
case 3:
printf("weekday = Tuesday");
break;
case 4:
printf("weekday = Wednesday");
break;
case 5:
printf("weekday = Thursday");
break;
case 6:
printf("weekday = Friday");
break;
default:
printf("Incorrect data");
}
return 0;
}
//------------------------------------------
int main() {
int date, month, year;

printf("\nEnter the year ");


scanf("%d", &year);

printf("\nEnter the month ");


scanf("%d", &month);

printf("\nEnter the date ");


scanf("%d", &date);

day_of_week(date, month, year);


return 0;
}

15,Program to show swap of two no’s without using third


variable
include<stdio.h>

int main() {
int a, b;

printf("\nEnter value for num1 & num2 : ");


scanf("%d %d", &a, &b);

a = a + b;
b = a - b;
a = a - b;

printf("\nAfter swapping value of a : %d", a);


printf("\nAfter swapping value of b : %d", b);

return (0);
}
16 Sample program of pre increment and post increment
program in c

#include<stdio.h>

void main()
{
inta,b,x=10,y=10;

a = x++;
b = ++y;

printf("Value of a : %d",a);
printf("Value of b : %d",b);
}

16 Sample program of pre decrement and post decrement


program in c

#include<stdio.h>
void main()
{
inta,b,x=10,y=10;

a = x--;
b = --y;

printf("Value of a : %d",a);
printf("Value of b : %d",b);
}

17C program to check whether a number entered by user is


even or odd.

#include<stdio.h>
int main(){
intnum;
printf("Enter an integer you want to check: ");
scanf("%d",&num);
if((num%2)==0) /* Checking whether remainder is 0 or
not. */
printf("%d is even.",num);
else
printf("%d is odd.",num);
return0;
}

18. C program to check whether an integer is odd or even


using conditional operator

#include<stdio.h>
int main(){
intnum;
printf("Enter an integer you want to check: ");
scanf("%d",&num);
((num%2)==0) ? printf("%d is even.",num) : printf("%d
is odd.",num);
return0;
}
19.C Program to Check Vowel or Consonant

#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;
}

20,C Program to Calculate Sum of Natural Numbers

#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
count=1;
while(count<=n) /* while loop terminates if count>n */
{
sum+=count; /* sum=sum+count */
++count;
}
printf("Sum = %d",sum);
return 0;
}
21 ,C program to Generate Multiplication Table

#include <stdio.h>
int main()
{
int n, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %d\n", n, i, n*i);
}
return 0;
}

22,C Program to Find GCD of two Numbers

#include <stdio.h>
int main()
{
int num1, num2, i, hcf;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
for(i=1; i<=num1 || i<=num2; ++i)
{
if(num1%i==0 && num2%i==0) /* Checking whether i is
a factor of both number */
hcf=i;
}
printf("H.C.F of %d and %d is %d", num1, num2, hcf);
return 0;
}
23,C Program to Check Whether a Number is Prime or Not

#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}

24,C Program to Make a Simple Calculator to Add,


Subtract, Multiply or Divide Using switch...case

# include <stdio.h>
int main()
{
char o;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error
message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}
 Programs on Arrays
1.C Program to Delete an element from the specified
location from Array

#include<stdio.h>

int main() {
int i, arr[50], num;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Reading values into Array


printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}
//Printing of all elements of array
for (i = 0; i < num; i++) {
printf("\narr[%d] = %d", i, arr[i]);
}

return (0);
}

2. C Program to Search an element in Array


#include<stdio.h>

int main() {
int arr1[30], arr2[30], res[60];
int i, j, k, n1, n2;

printf("\nEnter no of elements in 1st array :");


scanf("%d", &n1);
for (i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}
printf("\nEnter no of elements in 2nd array :");
scanf("%d", &n2);
for (i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}

i = 0;
j = 0;
k = 0;

// Merging starts
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
res[k] = arr1[i];
i++;
k++;
} else {
res[k] = arr2[j];
k++;
j++;
}
}

C programming code for binary search


#include <stdio.h>

int main()
{
int c, first, last, middle, n,
search, array[100];

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

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] ==
search) {
printf("%d found at location
%d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d is not
present in the list.\n", search);

return 0;
}
Linear search c 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;
}
3.C Program to Reversing an Array Elements in C
Programming

#include<stdio.h>

int main() {
int arr[30], i, j, num, temp;

printf("\nEnter no of elements : ");


scanf("%d", &num);

//Read elements in an array


for (i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}

j = i - 1; // j will Point to last Element


i = 0; // i will be pointing to first element

while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++; // increment i
j--; // decrement j
}

//Print out the Result of Insertion


printf("\nResult after reversal : ");
for (i = 0; i < num; i++) {
printf("%d \t", arr[i]);
}

return (0);
}
The following program initializes an integer
array with five values and prints the array
in.

#include <stdio.h>
#include <conio.h>
int main()
{
int numbers[]={1,2,3,4,5};
int i;
clrscr();
printf("Array elements are\n");
for(i=0;i<=4;i++)
printf("%d\n",numbers[i]);
getch();
return 0;
}
 String Input and Output

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
clrscr();
printf("Enter a string");
scanf("%[^\n]",&str);
printf("%s",str);
getch();
}
 Accessing Two-Dimensional Array Elements:

#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\n", i,j,
a[i][j] );
}
} return 0;}

Illustration of string handling


functions.
Code for Illustration of string handling
functions in C Programming

#include <string.h>
main()
{ char s1[20], s2[20],
s3[20];
int x, l1, l2, l3;
printf("\n\nEnter two string
constants \n");
printf("?");
scanf("%s %s", s1, s2);
/* comparing s1 and s2 */

x = strcmp(s1, s2);
if(x != 0)
{ printf("\n\nStrings are
not equal \n");
strcat(s1, s2); /*
joining s1 and s2 */

}
else
printf("\n\nStrings are
equal \n");
/* copying s1 to s3
strcpy(s3, s1);
/* Finding length of strings */

l1 = strlen(s1);
l2 = strlen(s2);
l3 = strlen(s3);
/* output */

printf("\ns1 = %s\t length =


%d characters\n", s1, l1);
printf("s2 = %s\t length =
%d characters\n", s2, l2);
printf("s3 = %s\t length =
%d characters\n", s3, l3);

Reading Strings from the Terminal

#include <stdio.h>

void main() {

char fname[30];
char lname[30];
printf("Type first name:\n");
scanf("%s", fname);

printf("Type last name:\n");


scanf("%s", lname);

printf("Your name is: %s %s\n",


fname, lname);
}

4.C Program to Find Largest Element in Array in C


Programming

#include<stdio.h>

int main() {
int a[30], i, num, largest;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Read n elements in an array


for (i = 0; i < num; i++)
scanf("%d", &a[i]);

//Consider first element as largest


largest = a[0];

for (i = 0; i < num; i++) {


if (a[i] > largest) {
largest = a[i];
}
}

// Print out the Result


printf("\nLargest Element : %d", largest);

return (0);
}
5.Program : Find Smallest Element in Array in C
Programming
#include<stdio.h>

int main() {
int a[30], i, num, smallest;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Read n elements in an array


for (i = 0; i < num; i++)
scanf("%d", &a[i]);

//Consider first element as smallest


smallest = a[0];

for (i = 0; i < num; i++) {


if (a[i] < smallest) {
smallest = a[i];
}
}

// Print out the Result


printf("\nSmallest Element : %d", smallest);

return (0);
}

6.Program : Addition of All Elements of the Array


#include<stdio.h>
int main() {
int i, arr[50], sum, num;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Reading values into Array
printf("\nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
//Computation of total
sum = 0;
for (i = 0; i < num; i++)
sum = sum + arr[i];
//Printing of all elements of array
for (i = 0; i < num; i++)
printf("\na[%d]=%d", i, arr[i]);
//Printing of total
printf("\nSum=%d", sum);
return (0);
}

7.Program : To delete duplicate elements in an


array
#include<stdio.h>

int main() {
int arr[20], i, j, k, size;

printf("\nEnter array size : ");


scanf("%d", &size);

printf("\nAccept Numbers : ");


for (i = 0; i < size; i++)
scanf("%d", &arr[i]);

printf("\nArray with Unique list : ");


for (i = 0; i < size; i++) {
for (j = i + 1; j < size;) {
if (arr[j] == arr[i]) {
for (k = j; k < size; k++) {
arr[k] = arr[k + 1];
}
size--;
} else
j++;
}
}

for (i = 0; i < size; i++) {


printf("%d ", arr[i]);
}

return (0);
}

8.Write a C program using pointers to read in an array of


integers and print its elements in reverse order.

#include<stdio.h>
#include<conio.h>
#define MAX 30

void main() {
int size, i, arr[MAX];
int *ptr;
clrscr();
ptr = &arr[0];

printf("\nEnter the size of array : ");


scanf("%d", &size);

printf("\nEnter %d integers into array: ", size);


for (i = 0; i < size; i++) {
scanf("%d", ptr);
ptr++;
}
ptr = &arr[size - 1];
printf("\nElements of array in reverse order are :");
for (i = size - 1; i >= 0; i--) {
printf("\nElement%d is %d : ", i, *ptr);
ptr--;
}
getch();
}
9.Write a C Program which will accept string from the user
. Pass this string to the function. Calculate the length of the
string using pointer.
Program : Length of the String using Pointer
#include<stdio.h>
#include<conio.h>

int string_ln(char*);

void main() {
char str[20];
int length;
clrscr();

printf("\nEnter any string : ");


gets(str);

length = string_ln(str);
printf("The length of the given string %s is : %d", str,
length);
getch();
}

int string_ln(char*p) /* p=&str[0] */


{
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
10.Write a program to count the number of words, lines
and characters in a text
Program finding number of words, blank spaces, special
symbols, digits, vowels using pointers

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<conio.h>

/*low implies that position of pointer is within a word*/


#define low 1

/*high implies that position of pointer is out of word.*/


#define high 0

void main() {
int nob, now, nod, nov, nos, pos = high;
char *str;
nob = now = nod = nov = nos = 0;
clrscr();
printf("Enter any string : ");
gets(str);

while (*str != '\0') {

if (*str == ' ') {


// counting number of blank spaces.
pos = high;
++nob;
} else if (pos == high) {
// counting number of words.
pos = low;
++now;
}

if (isdigit(*str)) /* counting number of digits. */


++nod;
if (isalpha(*str)) /* counting number of vowels */
switch (*str) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
++nov;
break;
}

/* counting number of special characters */


if (!isdigit(*str) && !isalpha(*str))
++nos;
str++;
}

printf("\nNumber of words %d", now);


printf("\nNumber of spaces %d", nob);
printf("\nNumber of vowels %d", nov);
printf("\nNumber of digits %d", nod);
printf("\nNumber of special characters %d", nos);

getch();
}

11./* C program to find the sum marks of n students using


arrays */

#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}

12.Example of 3 Dimensional Array in Matrix


#include <stdio.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");

/* Reading two dimensional Array with the help of two for


loop. If there was an array of 'n' dimension, 'n' numbers of
loops are needed for inserting data to array.*/
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j){
/* Writing the elements of multidimensional array using
loop. */
c[i][j]=a[i][j]+b[i][j]; /* Sum of corresponding
elements of two arrays. */
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("%.1f\t",c[i][j]);
if(j==1) /* To display matrix sum in order. */
printf("\n");
}
return 0;
}

13. 2D arrays are generally known as matrix. We will


discuss two Dimensional array in detail but before this
have a look at the below piece of code
#include<stdio.h>
int main()
{
/* 2D array declaration*/
int disp[3][5];

/*Counter variables for the loop*/


int i, j;

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


{
for(j=0;j<=4;j++)
{
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
return 0;
}

Reference operator(&)
/* Example to demonstrate use of reference operator in C
programming. */
#include <stdio.h>
int main(){
int var=5;
printf("Value: %d\n",var);
printf("Address: %d",&var); //Notice, the ampersand(&)
before var.
return 0;
}

14.Program that accept values in 2-Dimensional 3


by 3 array and displays the sum of all the
elements.
void main()
{
int arr[3][3], i, j, sum=0;

/*Accepts input from the user and stores it in 2-D


array*/
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“\nEnter the value for A[%d][%d]:“,i,j);
scanf(“%d”,&arr[i][j]);
}
}

/*Calculate sum of elements in 2-D array*/


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum=sum+arr[i][j];
}
}

/*Display the value of sum*/


printf(“\nThe sum of the elements of 2-D array is %d”,
sum);
}

15. Example of Two Dimensional Array


#include <stdio.h>

void main()
{
int i, j, a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
for(i = 2; i >= 0; i = i - 1)
{
for(j = 3; j >= 0; j = j - 1)
printf("a[%d][%d] = %d\t", i, j, a[i][j]);
printf("\n");
}
}
In the following experiment, the first loop scans characters
into a character array and the second prints them. For
both loops, i stays fixed while j varies or the row stays fixed
while the column varies. Hence, the data is read in the
array row-wise and printed out row-wise. Enter this
data: a, b, c, d, e, f, g, h, i, j, k, l. Remember to put a space
preceding the %c in the scanf_s(). Show the output and
answer the questions.

#include <stdio.h>

void main()
{
int i, j;
char a[3][4];
for(i = 0; i <= 2; i = i + 1)
for(j = 0; j <= 3; j = j + 1)
// scanf(" %c", &a[i][j]);
scanf_s(" %c", &a[i][j], sizeof(a));
for(i = 0; i <= 2; i = i + 1)
{
for(j = 0; j <= 3; j = j + 1)
printf("a[%d][%d] = %c\t", i, j, a[i][j]);
printf("\n");
}
}

16.Source code of simple bubble sort implementation


using array ascending order in c programming language

#include<stdio.h>
int main(){

int s,temp,i,j,a[20];

printf("Enter total numbers of elements: ");


scanf("%d",&s);

printf("Enter %d elements: ",s);


for(i=0;i<s;i++)
scanf("%d",&a[i]);

//Bubble sorting algorithm


for(i=s-2;i>=0;i--){
for(j=0;j<=i;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

printf("After sorting: ");


for(i=0;i<s;i++)
printf(" %d",a[i]);

return 0;
}

17.C PROGRAM FOR INSERTION SORT


Source code of simple insertion sort implementation using
array in ascending order in c programming language

#include<stdio.h>
int main(){

int i,j,s,temp,a[20];

printf("Enter total elements: ");


scanf("%d",&s);

printf("Enter %d elements: ",s);


for(i=0;i<s;i++)
scanf("%d",&a[i]);

for(i=1;i<s;i++){
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0)){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}

printf("After sorting: ");


for(i=0;i<s;i++)
printf(" %d",a[i]);

return 0;
}

18.Source code of simple Selection sort implementation


using array ascending order in c programming language

#include<stdio.h>
int main(){

int s,i,j,temp,a[20];

printf("Enter total elements: ");


scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);

for(i=0;i<s;i++){
for(j=i+1;j<s;j++){
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

printf("After sorting is: ");


for(i=0;i<s;i++)
printf(" %d",a[i]);

return 0;
}
19.Source code of simple quick sort implementation using
array ascending order in c programming language

#include<stdio.h>

void quicksort(int [10],int,int);

int main(){
int x[20],size,i;

printf("Enter size of the array: ");


scanf("%d",&size);

printf("Enter %d elements: ",size);


for(i=0;i<size;i++)
scanf("%d",&x[i]);

quicksort(x,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",x[i]);

return 0;
}

void quicksort(int x[10],int first,int last){


int pivot,j,temp,i;

if(first<last){
pivot=first;
i=first;
j=last;

while(i<j){
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j){
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}

temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);

}
}

20.Source code of simple merge sort implementation using


array in ascending order in c programming language

#include<stdio.h>
#define MAX 50
void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);

int main(){

int merge[MAX],i,n;

printf("Enter the total number of elements: ");


scanf("%d",&n);

printf("Enter the elements which to be sort: ");


for(i=0;i<n;i++){
scanf("%d",&merge[i]);
}

partition(merge,0,n-1);

printf("After merge sorting elements are: ");


for(i=0;i<n;i++){
printf("%d ",merge[i]);
}
return 0;
}

void partition(int arr[],int low,int high){

int mid;

if(low<high){
mid=(low+high)/2;
partition(arr,low,mid);
partition(arr,mid+1,high);
mergeSort(arr,low,mid,high);
}
}

void mergeSort(int arr[],int low,int mid,int high){

int i,m,k,l,temp[MAX];

l=low;
i=low;
m=mid+1;

while((l<=mid)&&(m<=high)){

if(arr[l]<=arr[m]){
temp[i]=arr[l];
l++;
}
else{
temp[i]=arr[m];
m++;
}
i++;
}

if(l>mid){
for(k=m;k<=high;k++){
temp[i]=arr[k];
i++;
}
}
else{
for(k=l;k<=mid;k++){
temp[i]=arr[k];
i++;
}
}

for(k=low;k<=high;k++){
arr[k]=temp[k];
}
}

21.C programming code

#include <stdio.h>

int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);

p = &first;
q = &second;

sum = *p + *q;

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

return 0;
}

22.C program to add numbers using call by reference


#include <stdio.h>

long add(long *, long *);

int main()
{
long first, second, *p, *q, sum;
printf("Input two integers to add\n");
scanf("%ld%ld", &first, &second);

sum = add(&first, &second);

printf("(%ld) + (%ld) = (%ld)\n", first, second, sum);

return 0;
}

long add(long *x, long *y) {


long sum;

sum = *x + *y;

return sum;
}
23./* Source code to demonstrate, handling of pointers in
C program */
#include <stdio.h>
int main(){
int* pc;
int c;
c=22;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%d\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
c=11;
printf("Address of pointer pc:%d\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
}
24.#include <stdio.h>
int main(){
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}

24.//Program to find the sum of six numbers with arrays


and pointers.
#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to
&class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}

25./* C Program to swap two numbers using pointers and


function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is
passed to swap function */
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to
address of num1 and num2 respectively */
int temp;
temp=*a;
*a=*b;
*b=temp;
}

26.Write a C program to find sum of n elements entered by


user. To perform this program, allocate memory
dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated
using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

You might also like