C_CPP_Codes
114 subscribers
1 photo
About me :- alokosx.me

Books,notes and more at :- cp_resources.t.me

Discussion :- c_cpp_code.t.me
Download Telegram
Program to count number of blanks,digits,letters,other characters and total characters in a file using for loop :
#include <stdio.h>

int main(void)
{
    int blanks = 0, digits = 0, letters = 0, others = 0,totalchars = 0;
    int c;

    for(;(c = getchar())!=EOF;totalchars++)
    {
        if (c == ' ')
            ++blanks;
        else if (c >= '0' && c <= '9')
            ++digits;
        else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
            ++letters;
        else
            ++others;
    }

    printf(" Blanks = %d,\n Digits = %d,\n Letters = %d,\n Others = %d\n Total chars = %d\n\n", blanks, digits, letters, others, totalchars);

    return 0;
}
Output :

$ ./count.out <count.c

Blanks = 189,
Digits = 8,
Letters = 237,
Others = 145
Total chars = 579
Program to levy speeding ticket using ternary operator :
#include <stdio.h>
int main(void)
{
int speed;
printf("\nEnter speed as integer:");
scanf("%d",&speed); speed = (speed<=65)?(65):(speed<=70)?(70):(90);
switch(speed)
{
case 65: printf("\nNo speeding ticket.\n");break;
case 70: printf("\nSpeeding ticket.\n");break;
case 90: printf("\nExpensive speeding ticket.\n");break;
default: printf("\nIncorrect speed.\n");break;
}
return 0;
}
Output :

1)
Enter speed as integer:99

Expensive speeding ticket.

2)
Enter speed as integer:16

No speeding ticket.
Program to print values of sin and cos between 0 and 1 using for loop :
#include <stdio.h>
#include <math.h> /* has sin(),abs(),and fabs() */
int main(void)
{
double interval;
int i; double sine,cosine;
for(i=0;i<=10;i++) // taking values between 0 and 1 as range
{
interval = i/10.0;
sine = sin(interval);
cosine = cos(interval);
/* here in above lines we called fabs function as interval is
in float */
printf("sin(%0.3lf) = %0.3lf | cos(%0.3lf) = %0.3lf\n",in>


}
return 0;
}
Output :

sin(0.000) = 0.000 | cos(0.000) = 1.000
sin(0.100) = 0.100 | cos(0.100) = 0.995
sin(0.200) = 0.199 | cos(0.200) = 0.980
sin(0.300) = 0.296 | cos(0.300) = 0.955
sin(0.400) = 0.389 | cos(0.400) = 0.921
sin(0.500) = 0.479 | cos(0.500) = 0.878
sin(0.600) = 0.565 | cos(0.600) = 0.825
sin(0.700) = 0.644 | cos(0.700) = 0.765
sin(0.800) = 0.717 | cos(0.800) = 0.697
sin(0.900) = 0.783 | cos(0.900) = 0.622
sin(1.000) = 0.841 | cos(1.000) = 0.540
👍1
Program to create a void function in C to add 2 int :
#include <stdio.h>
void myfunc(int x,int y){
int sum;
sum = x+y;
printf("%d",sum);
}

int main(void)
{ int x = 10,y = 20;
  myfunc(x,y);
}
Output :

30
👍2
Program to define a function with return statement :
#include <stdio.h>
int myfunc(int x,int y)
{
return x+y;
}

int main(void)
{ int x = 10,y = 20;
  printf("%d",myfunc(x,y));
}
Output :
30
Function to print square and cubes of a given range of numbers :
#include <stdio.h>
int square(int);
int cube(int);
int main(void)
{
int end = 0,i,j;
printf("I want squares and cubes from 1 to:");
scanf("%d",&end);
printf("\nNumber\tSquare\tCube\n");
for(i=1;i<=end;i++)
{
printf("\n %d \t %d \t %d",i,square(i),cube(i));
}
printf("\n\n");
return 0;
};

int square(int x)
{
return x*x;
}

int cube(int x)
{
return x*x*x;
}
Output :

I want squares and cubes from 1 to:10

Number Square Cube

1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Program to print Fibonacci series till 10th term using iteration :
#include <stdio.h>
long fibonacci(int n)
{
long f2 = 0,f1 = 1,f_old;
int i;
for(i =0;i<n;i++)
{
  f_old = f2;
  f2 = f2+f1;
  f1 = f_old;
}
return f2;
}

int main(void)
{
int n;
for(n=1;n<=10;n++)
{
  printf("%d term = %ld\n",n,fibonacci(n));
}
return 0;
}
Output :

1 term = 1
2 term = 1
3 term = 2
4 term = 3
5 term = 5
6 term = 8
7 term = 13
8 term = 21
9 term = 34
10 term = 55
Program to print fibonacci series using recursion :
#include <stdio.h>
long recursive_fibonacci(int n)
{
if(n<=1)
  return n;
else
  return(recursive_fibonacci(n-1)+ recursive_fibonacci(n-2));
}

int main(void)
{
int n;
for(n=1;n<=10;n++)
{
printf("%d term = %ld\n",n,recursive_fibonacci(n));
}
return 0;
}
Output :

1 term = 1
2 term = 1
3 term = 2
4 term = 3
5 term = 5
6 term = 8
7 term = 13
8 term = 21
9 term = 34
10 term = 55
Program to print factorial upto n using recursion :
#include <stdio.h>
long int factorial(int n)
{
if(n == 0 | n == 1)
return 1;
else
return(factorial(n-1)*n);
}

int main(void)
{
int how_many = 0,i;
printf("I want table of factorial upto :");
scanf("%d",&how_many);

for(i=0;i<=how_many;i++)
printf("\n%d!\t=\t%ld\n",i,factorial(i));
return 0;
}
Output :

I want table of factorial upto :10

0! = 1

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

6! = 720

7! = 5040

8! = 40320

9! = 362880

10! = 3628800
Program to initialize pointer and print its adress in hex and decimal format :
#include <stdio.h>
int main(void)
{
int a = 10,*p = &a;
printf("Adress of pointer is %p or %lu  and is pointed to %d",p,p,*p);
return 0;
}
Output :

Adress of pointer is 0x7fffe569a6f4 or 140737042294516  and is pointed to 10
Program to swap value of 2 variables using pointers :
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main(void)
{
int a = 10,b = 20;
printf("Before swap:\n%d = \t%p or %lu \n%d = \t%p or %lu\n\n",a,&a,&a,b,&b,&b);
swap(&a,&b);
printf("After swap:\n%d = \t%p or %lu\n%d = \t%p or %lu\n",a,&a,&a,b,&b,&b);
}
Output :

Before swap:
10 = 0x7fe7e83c9c or 549351603356
20 = 0x7fe7e83c98 or 549351603352

After swap:
20 = 0x7fe7e83c9c or 549351603356
10 = 0x7fe7e83c98 or 549351603352
Program to take input of number of subject and grades from user in a array and calculate percentage:
#include <stdio.h>
int main(void)
{
int SIZE;
printf("Enter number of subjects:\n");
scanf("%d",&SIZE);
int grades[SIZE];
double sum = 0.0;
int i;
printf("\nEnter your grades:\n");
for(i = 0; i<SIZE; i++)
  scanf("%d",&grades[i]);
printf("\nYour grades are:\n");
for(i = 0; i<SIZE; i++)
  printf("%d\t",grades[i]);
printf("\n\n");
                                                                       for(i = 0; i<SIZE; i++)
sum += grades[i];
printf("Your percentage is %.2f %\n\n",sum/SIZE);
return 0;
}
Output :

Enter number of subjects:
5

Enter your grades:
98 96 94 92 90

Your grades are:
98      96      94      92      90

Yout percentage is 94.00 %
Program to bubble sort a array of numbers :
#include <stdio.h>
void swap(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void print_array(int how_many,int data[],char *str)
{
int i;
printf("%s",str);

for(i = 0;i < how_many;i++)
printf("%d\t",data[i]);
}

void bubble(int data[],int how_many)
{
int i,j;
int go_on;
for(i=0 ; i<how_many ;i++)
{
print_array(how_many,data,"\nInside bubble\n");
printf("\nEnter a number to continue : ");
scanf("%d",&go_on);
for(j=how_many-1;j>i;j--)
if(data[j-1] > data[j])
swap(&data[j-1],&data[j]);
}
}

int main(void)
{
int SIZE;
printf("Enter no. of numbers you want to sort:");
scanf("%d",&SIZE);
int num[SIZE];
printf("Enter %d digits which you want to sort:\n",SIZE);
for(int i = 0; i<SIZE ; i++)
scanf("%d",&num[i]);
print_array(SIZE,num,"Numbers you entered:\n");
printf("\n\n");
bubble(num,SIZE);
print_array(SIZE,num,"\n\nSorted numbers:\n");
printf("\n\n");
return 0;
}
Output :

Enter no. of numbers you want to sort:5
Enter 5 digits which you want to sort:
27 91 63 29 15
Numbers you entered:
27 91 63 29 15


Inside bubble
27 91 63 29 15

Enter a number to continue : 0

Inside bubble
15 27 91 63 29

Enter a number to continue : 2

Inside bubble
15 27 29 91 63

Enter a number to continue : 9

Inside bubble
15 27 29 63 91

Enter a number to continue : 2

Inside bubble
15 27 29 63 91

Enter a number to continue : 4


Sorted numbers:
15 27 29 63 91
1
Program to merge sort 2 arrays :
#include <stdio.h>
void print_array(int how_many,int data[],char *str)
{
int i;

printf("%s",str);

for(i=0;i<how_many;i++)
printf("%d\t",data[i]);
}

void merge(int a[],int b[],int c[],int how_many)
{
int i=0,j=0,k=0;

while(i<how_many && j<how_many)
if(a[i]<b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
while(i<how_many)
c[k++] = a[i++];
while(j<how_many)
c[k++] = b[j++];
}

int main(void)
{
const int SIZE = 5;
int a[SIZE] = {45,57,69,81,93};
int b[SIZE] = {44,56,68,80,92};
int c[2*SIZE];
print_array(SIZE,a,"My grades are:\n");
printf("\n\n");
print_array(SIZE,b,"More grades:\n");
merge(a,b,c,SIZE);
printf("\n\n");
print_array(2*SIZE,c,"My sorted grades are:\n");
printf("\n\n");
}
Output :

My grades are:
45 57 69 81 93

More grades:
44 56 68 80 92

My sorted grades are:
44 45 56 57 68 69 80 81 92 93
Program to sort a array given by user using merge sort algorithm :
#include <stdio.h>
void print_array(int how_many,int data[],char *str)
{
int i;

printf("%s",str);

for(i=0;i<how_many;i++)
printf("%d\t",data[i]);
}

void merge(int a[],int b[],int c[],int how_many)
/* here a and b are of same size */
{
int i=0,j=0,k=0;

while(i<how_many && j<how_many)
if(a[i]<b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
while(i<how_many)
c[k++] = a[i++];
while(j<how_many)
c[k++] = b[j++];
}

void mergesort(int key[],int how_many)
/* how_many is in power of 2*/
{
int j,k;
int w[how_many];

for(k=1;k<how_many;k*=2)
{
for(j=0;j<how_many;j+=2*k)
merge(key+j,key+j+k,w+j,k);
for(j=0;j<how_many;j++)
key[j] = w[j];
}
}

int main(void)
{
int size,i;
printf("Enter size of array:");
scanf("%d",&size);
int a[size];
printf("Enter %d numbers:\n",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
print_array(size,a,"Numbers you entered:\n\n");
printf("\n\n");
mergesort(a,size);
print_array(size,a,"Sorted numbers:\n\n");
printf("\n\n");
}
Output :

Enter size of array:8
Enter 8 numbers:
25 72 19 71 10 72 92 93
Numbers you entered:

25 72 19 71 10 72 92 93

Sorted numbers:

10 19 25 71 72 72 92 93
Program to define enum and print today and next day :
#include <stdio.h>
enum day{sun,mon,tue,wed,thr,fri,sat};
typedef enum day day;

void print_day(day d)
{
switch(d)
{
case sun:printf("Sunday\n");break;
case mon:printf("Monday\n");break;
case tue:printf("Tuesday\n");break;
case wed:printf("Wednesday\n");break;
case thr:printf("Thrusday\n");break;
case fri:printf("Friday\n");break;
case sat:printf("Saturday\n");break;
default :printf("This is not a valid day\n");break;
}
}

day next_day(day d)
{
return((d+1)%7);
}
int main(void)
{
day today = sun;
print_day(today);
print_day(next_day(today));
print_day(10);
return 0;
}
Ouput :

Sunday
Monday
This is not a valid day
Program to divide 2 number and remove divide by zero error using assert :
#include <stdio.h>
#include <assert.h>

int main(void)
{
double a,b;
while(1)
{
printf("Enter 2 number:");
scanf("%lf %lf",&a,&b);
assert(b!=0);
printf("a/b = %0.3lf\n",a/b);
}
return 0;
}
Output :

Enter 2 number:5 9
a/b = 0.556
Enter 2 number:10 2
a/b = 5.000
Enter 2 number:8 0
assert.c:15: int main(void): assertion "b!=0" failed
Aborted
Program to define employee details struct and print detail of 10 employee by generating random salary,ssn using srand function :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef enum dept{HR, Sales, Research, Software, Executive} dept;
typedef struct employee{
dept department;
int annual_sal;
unsigned int ssn;
} employee;

const char* dept_to_string(dept department) {
switch(department) {
case HR: return "HR";
case Sales: return "Sales";
case Research: return "Research";
case Software: return "Software";
case Executive: return "Executive";
default: return "Unknown";
}
}

int salary_gen(dept department)
{
int base_salary;
int offset = rand() % 10000;
if(department == HR)
base_salary = 100000;
else if(department == Sales)
base_salary = 30000;
else if(department == Research)
base_salary = 50000;
else if(department == Software)
base_salary = 60000;
else
base_salary = 80000; //for executive
return base_salary + offset;
}

int main(void)
{
srand(time(NULL)); // seed the random number generator
struct employee emp[10];
for(int i = 0; i < 10; i++)
{
emp[i].department = rand() % 5; // assign a random department
emp[i].annual_sal = salary_gen(emp[i].department); // generate a random salary
emp[i].ssn = rand() % 1000000000 + 100000000; // generate a random SSN

printf("Department: %s\n", dept_to_string(emp[i].department));
printf("Annual Salary: %d\n", emp[i].annual_sal);
printf("SSN: %u\n", emp[i].ssn);
}
}

Output :

Department: Executive
Annual Salary: 87266
SSN: 172060583


Department: Sales
Annual Salary: 35895
SSN: 803820085


Department: Executive
Annual Salary: 84152
SSN: 245588248


Department: Research
Annual Salary: 54407
SSN: 210668417


Department: HR
Annual Salary: 105633
SSN: 919574966


Department: Research
Annual Salary: 54230
SSN: 788124279


Department: Sales
Annual Salary: 35233
SSN: 506739685


Department: Software
Annual Salary: 62650
SSN: 725260271


Department: HR
Annual Salary: 104504
SSN: 550906751


Department: HR
Annual Salary: 100993
SSN: 480413954
👏1
Program to reverse a string using ADT stack :
#include <stdio.h>
#include <ctype.h>

#define MAX_LEN 1000 #define EMPTY -1
#define FULL MAX_LEN-1

typedef struct stack{char s[MAX_LEN];int top;} stack;

void reset(stack *stk){stk->top = EMPTY;} void push(char c,stack *stk)
{
stk->top++;
stk->s[stk->top] = c;
}

char pop(stack *stk){return (stk->s[stk->top--]);}
char top(stack *stk){return (stk->s[stk->top]);}

int is_empty(const stack *stk){return (stk->top==EMPTY);}
int is_full(const stack *stk){return(stk->top==FULL);}

int main(void)
{
stack stack_of_char;
char *str = "i am alok";
char str_back[10];
int i=0; reset(&stack_of_char); printf("Given string is: %s\n\nPushing to stack:\n\n",str);
while(str[i]!='\0')
{
printf("%c\n",str[i]);
push(str[i++],&stack_of_char);
}
i=0;
while(!is_empty(&stack_of_char)&&i<10)
{
str_back[i++]=pop(&stack_of_char);
}
printf("\nPoping from stack:\n\n");
i=0;
while(i<10)
{
printf("%c\n",str_back[i]);
i++;
}
printf("Reversed string is: %s\n",str_back);
return 0;
}
Output :

Given string is: i am alok

Pushing to stack:

i

a
m

a
l
o
k

Poping from stack:

k
o
l
a

m
a

i

Reversed string is: kola ma i
👍2
Code to create a singly linked list from a array :

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

typedef struct list {
int data; struct list *next;
} list;

int is_empty(const list *l) {
return (l == NULL);
}
list* create_list(int d) {
list* head = malloc(sizeof(list));
head->data = d;
head->next = NULL;
return head;
}
list* add_to_front(int d, list *h) {
list* head = create_list(d);
head->next = h;
return head;
}
list *array_to_list(int d[], int size) {
list *head = create_list(d[0]);
for(int i = 1; i < size; i++) {
head = add_to_front(d[i], head);
}
return head;
}
void print_list(list *h, char *title) {
printf("%s\n", title);
while(h != NULL) {
printf("%d :", h->data);
h = h->next;
}
}

int main(void) {
list list_of_int;
list* head = NULL;
int data[6] = {0,1,2,3,4,5};
head = array_to_list(data, 6);
print_list(head, "Singly linked list:");
printf("\n\n");
return 0;
}
Output :

Singly linked list:
5 :4 :3 :2 :1 :0 :
Code to create a file encryptor/decryptor with help of argc & argv :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void printfile(FILE *ifp)
{
int c;
rewind(ifp);
while((c=getc(ifp))!=EOF)
putc(c,stdout);
}

void encrypt(FILE *ifp,FILE *ofp)
{
int c;
rewind(ifp);
while((c=getc(ifp))!=EOF){
if((c>=65 && c<=77) || (c>=97&& c<=109))
putc(c+13,ofp);
else if((c>=78 && c<=90) || (c>=110 && c<=122))
putc(c-13,ofp);
else
putc(c,ofp);
}
}

void decrypt(FILE *ifp,FILE *ofp)
{
int c;
rewind(ifp);
while((c=getc(ifp))!=EOF){
if((c>=65 && c<=77) || (c>=97 && c<=109))
putc(c+13,ofp);
else if((c>=78 && c<=90) || (c>=110 && c<=122))
putc(c-13,ofp);
else
putc(c,ofp);
}
}

int main(int argc,char *argv[])
{
FILE *ifp,*ofp;
if(argc!=4){
printf("Need executable,operation,input file,output file");
exit(1);
}
ifp = fopen(argv[2],"r+");
ofp = fopen(argv[3],"w+");
if(strcmp(argv[1],"encrypt") == 0){
printf("%s File before encryption :\n\n", argv[2]);
printfile(ifp);
printf("\n\n");
encrypt(ifp,ofp);
printf("%s file is encrypted into file %s.\n\n Encrypted text:\n\n", argv[2], argv[3]);
printfile(ofp);
printf("\n\n");
}
else if(strcmp(argv[1],"decrypt") == 0){
decrypt(ifp,ofp);
printf("%s file is decrypted into file %s.\n\nDecrypted text:\n\n", argv[2], argv[3]);
printfile(ofp);
printf("\n\n");
}
}
👍3