Skip to content

Instantly share code, notes, and snippets.

@aaayushsingh
Last active September 17, 2017 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaayushsingh/f7a70eb0102446ea1e64361c2be7eaf8 to your computer and use it in GitHub Desktop.
Save aaayushsingh/f7a70eb0102446ea1e64361c2be7eaf8 to your computer and use it in GitHub Desktop.
c programs vishal
//Program 1, to reverse strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) //used to accept command line args
{
if(argc < 2 ){ //check if there are any inputs in command line
printf("please provide inputs"); //if no, exit
exit(1);
}
char *str = argv[1],temp; //get input from command line
int len = strlen(str),i;
for(i = 0; i<len/2 ; i++){ //reverse string, swap first and last values,
temp = str[i]; //then swap second and second last, and so on
str[i] = str [len-i-1];
str[len-i-1] = temp;
}
puts(str); //print final output
return 0;
}
// program to find factorial
#include <stdio.h>
#include <stdlib.h>
long long int fact(long long int n){ // we use long long int to calculate values for bigger numbers
return n >= 1 ? n*fact(n-1) : 1; // just int can also be used instead of long long int
} //this function calculates factorial using
//recursion and returns the value
int main(int argc, char *argv[]) //used to accept command line args
{
if(argc < 2 ){ //check if there are any inputs in command line
printf("please provide inputs"); //if no, exit
exit(1);
}
if(argv[1]>0){ //check if the input is greater than 0 if yes print factorial.
printf("%lld", fact(atoi(argv[1]))); //atoi(...) is used to convert ascii input to integer.
} else {
printf("Enter a number greater than 0"); //if input less than 0, exit
exit(1);
}
return 0;
}
//program to check prime
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) //used to accept command line args
{
if(argc < 2 ){ //check if there are any inputs in command line
printf("please provide inputs"); //if no, exit
exit(1);
}
int num = atoi(argv[1]); //atoi(...) is used to convert ascii input to integer.
int lim = ceil(sqrt(num)), flag = 0, i; //find square root
for(i = 2; i < lim; i++){ //check if prime
if(flag) break;
if (num%i == 0) flag = 1;
}
printf("%s", flag == 0 ? "prime" : "composite"); //print result
return 0;
}
//program to find area of circle with given radius
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) //used to accept command line args
{
if(argc < 2 ){ //check if there are any inputs in command line
printf("please provide inputs"); //if no, exit
exit(1);
}
int radius = atoi(argv[1]); //atoi(...) is used to convert ascii input to integer.
printf("%f", 3.14*radius*radius); //print 3.14 * radius^2
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment