Sunday, May 17, 2020

,

miscellaneous function in c programming (scanf(),printf(),sprintf() and more)

miscellaneous function in c programming (scanf(),printf(),sprintf() and more)
miscellaneous function in c programming (scanf(),printf(),sprintf() and more)

printf() Function in c programming

printf is a predefined function in "stdio.h" header file with the help of this function we can print data or user-defined messages on a computer screen. printf() function can take a number of argument and every argument should separate with a comma (, ) Within the double cotes but the first argument must be within the double cotes (" ").

Syntax : - 

 printf("user defined message"); 
 or 
 prinf("Format specifers",value1,value2,..); 

examples for printf() function in c programming  : -  

int a=20;
double d=12.4;
printf("%f%d",d,a);

scanf() Function in c programming:-

 scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value from the keyword.

Syntax: - 

scanf("format specifiers",&value1,&value2,.....);

examples for scanf() function in c programming  : - 

int a;
float b;
scanf("%d%f",&a,&b);

sprintf() function in c programming

sprintf() function is as printf() but insted of sending output to console it returns the formatted string.

Syntax: -
 int sprintf(char *str, const char *control_string, [ arg_1, arg_2, ... ]); 

The first argument in sprintf() function is a pointer which is pointed out towards the target string. All other arguments are the same as for printf() function in c.

sprintf() function write the data in string pointer str and return the number of characters written to str excluding the null character. if an error occurs in operation it returns -1.

  • Example to learn about how to use sprintf() function:-


#include <stdio.h>
#include <string.h>
int factorial(int );
 
int main()
{
 
    int sal;
    char name[30], designation[30], info[60];
 
    printf("your name: ");
    gets(name);
 
    printf("your designation: ");
    gets(designation);
 
    printf("your salary: ");
    scanf("%d", &sal);
 
    sprintf(info, "Welcome %s !\nName: %s \nDesignation: %s\nSalary: %d",
        name, name, designation, sal);
 
    printf("\n%s", info);
 
    // signal to operating system program ran fine
    return 0;
}

memcpy() function in c programming :-

memcpy() function in c programming using to copy n characters from the object pointed to s2 in the object pointed by s1. It returns a pointer to the destination. 

if objects overlap then memcpy() function may not work. 

  The syntax for c language: - 

void *memcpy(void *s1, const void *s2, size_t n);

s1:- an array where s2 will be copied.

s2:- a string that is going to copy in s1.

n:- number of characters to copy.

NOTE : - <string.h> header file should be included 

  • Example for memcpy() function

/* Example using memcpy by TechOnTheNet.com */

#include <stdio.h>
#include <string.h> 

int main(int argc, const char * argv[])
{

    return 0;
}

memmove() function in c programming :-

memmove() function in c programming use to copy n characters from the object pointed to s2 in the object pointed by s1. its returns a pointer to the destination.

memmove() function in c programming will work for objects overlap. 

Syntax: -

void *memmove(void *s1, const void *s2, size_t n);

memchr() function in c programming :-

memchr() function in c programming using to searches a character in an object and return a pointer for that character.

 Syntax :- 

void *memchr(const void *s, int c, size_t n);
  •  Example for memchr() function in c : - 
/* Example using memchr by functioninprogramming.com */

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
    char search[] = "functioninprogramming";
    char *ptr;

    /* Return a pointer to the first 'm' within the search string */
    ptr = (char*)memchr(search, 'm', strlen(search));

    /* If 'm' was found, print its location (This should produce "17") */
    if (ptr != NULL) printf("Found 'm' at position %ld.\n", 1+(ptr-search));
    else printf("'m' was not found.\n");

    return 0;
}

memset() function in c programming:-

memset() function in c programming use to stores a character into the first n character of object.

 syntax :- 

void *memset(void *s, int c, size_t n);

 strpbrk() function in c programming : - 

strbrk() function in c used to search a string for one of the set of characters. 

Syntax: - 

char *strpbrk(const char *s1, const char *s2);

 strbrk() function return a pointer of leftmost matching characterin the string. If due to any reason match not found  then it return NULL pointer.

 strspn() function in c  :- 

strspn() function in c programming is used to Search String for Initial Span of Characters in Set and return the index of the first character that is not in the set.

 strtok() function in c  : -

strtok() function in c programming splits the function in the number of tokens and returns a pointer to the first character of the token.

strtok() function stores a null character as the end of tokens as a termination.

syntax: - 

char *strtok(char *s1, const char *s2);

we hope these all function will help you to learn about c programming and its functions.

Saturday, May 16, 2020

, , , ,

Learn malloc(), calloc(), free() and realloc() function in c



This chapter will help you to learn about Dynamic memory allocation in your c program with the help of using standard library function : - malloc(), calloc(), free() and realloc().

Learn malloc(), calloc(), free() and realloc() function in c
Learn malloc(), calloc(), free() and realloc() function in c


As we know array is a collection of elements once the size of array is declared, It cannot be changed.

So Sometimes declared size is insufficient for an array. To solve these problems we can use Dynamic memory allocation During run time in c programming. This process is known as dynamic memory allocation in C programming.

To allocate memory dynamically in c programming, library funcation malloc(), calloc(), free() and realloc(), are used These functions are defined in the <stdlib.h> in C programming
header file. 

Let's learn about these function in c programming : - 


Malloc () Function In C  : -

The malloc() function stands for memory allocation in c programming. malloc() function is used to allocate block of memory dynamically.It reserves memory space of specified size and returns the null pointer pointing to the memory location. that pointer is usually a type of viod. so previous line clears that wen can assign malloc() function to any pointer.

Syntax for malloc() : -


ptr = (cast_type *) malloc (byte_size);

  • ptr is a pointer of cast_type.
  • The malloc function returns a pointer to the allocated memory of byte_size.

Example: ptr = (int *) malloc (50)

When this program statement is executed then a memory space of 50 byte is reserved, and address of the fist byte of reserved space is assign to pointer ptr of int type.

Example of malloc() function

#include 
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
    if (ptr != NULL) {
      *(ptr + 5) = 480; /* assign 480 to sixth integer */
      printf("6th integer is %d",*(ptr + 5));
    }
}

Output

6th integer is 480


malloc() function can be used With the character data type as well as complex data types such as structures.

free() Function : -  


As we know memory for variables is automatically deallocation at compile time in C programming But in dynamic memory allocation we have to deallocate memory with the help of "free() function. If dealocation is not done then  you may encounter out of memory error".

The free() function in c programming is basiclly called for release/deallocate memory. By freeing the memory in our program then we have more memory to use.

Example For  free() Function : -  

#include 
int main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
  *(ptr + 2) = 50;
  printf(" 2nd integer is %d",*(ptr + 2));
}
free(ptr);
} 

Output : -

2nd integer is 50

calloc() Function in C programming: - 


The calloc() function stands for contiguous allocation in c programming. calloc() function is used to allocate multiple number of block of memory dynamically.

calloc function is the same as malloc() function but it allocates the multiple numbers of the block of memory dynamically and each block allocated by calloc() function is the same size.

Syntax : -

ptr = (cast_type *) calloc (n, size);


  • Above statement is used to allocate n memory block of same size.

  • After the memory space is allocated, then all the bytes are initialized to zero.

  • The pointer which is currently at the first byte of the allocated memory space is returned. 
When a error is occured like shortage of memorythen a null pointer is returned 

calloc() Example  : - 

#include 
    int main() {
        int i, * ptr, sum = 0;
        ptr = calloc(10, sizeof(int));
        if (ptr == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("sum of the first 10 terms \ n ");
        for (i = 0; i < 10; ++i) { * (ptr + i) = i;
            sum += * (ptr + i);
        }
        printf("Sum = %d", sum);
        free(ptr);
        return 0;
    }

OUTPUT : -

sum of the first 10 terms sum = 45

realloc() Function in C programming: - 


realloc() stands for reallocation of memory realloc() function is use to add more memory size to already allocated memeory. It gives an opportunity to expand the current block without touch the orignal content.

realloc() function can also be used to reduce the size of  previously allocated memory. 

Syntax : -
ptr = realloc (ptr,newsize);

Above Statement allocates a new memory space with the specified size in the variable new. After executing the function pointer will returned to the first byte of memory block which can be samller and larger then previous assigned memory block, and we can't be sure that the newly allocated block will point to the same location as that of the previous memory block. realloc() function also copy all the data in the new one and make sure that data will remain safe.

Example for realloc() : -  



#include 
int main () {
   char *ptr;
   ptr = (char *) malloc(10);
   strcpy(ptr, "Programming");
   printf(" %s,  Address = %u\n", ptr, ptr);

   ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
   strcat(ptr, " In 'C'");
   printf(" %s,  Address = %u\n", ptr, ptr);
   free(ptr);
   return 0;
} 

If any error occur then it returns a null pointer,  and free the previous data is alsoed freed.

malloc(), calloc(), free() and realloc() functions is used to help all dynamic memory allocations and it will help yo save the memory in c programming programs.
,

string funcation like strcmp, strcpy, strlen and more in c



Learn about string function in c programming and how to perform various operation on string. We will use pre-defined function to perform those operation on the string in c programming


string funcation like strcmp, strcpy, strlen and more in c
string function like strcmp, strcpy, strlen and more in c


You will learn about how to compare two stings (strcmp function), concatenate strings (strcat function), copy (strcpy function) and many more operations using a pre-define function in c programming lets start with function.


First Declare String in c programming : -  

Method 1 - 

char address[]={'T', 'E', 'X', 'A', 'S', '\0'};

Method 2 - 


char address[]="Function In Programming";

NULL character (\0)  automatically at the end of any string.


  • strlen String Function in c - 


size_t strlen(const char *str)

size_t represents unsigned short
strlen function uses to count the length of any string without end character in c programming.

Example:-

#include 
#include 
int main()
{
     char str1[20] = "Function in programming";
     printf("Length of string str1: %d", strlen(str1));
     return 0;
}

sizeof function in c programming returns the value of total allocated size which is assigned in the array.


  • strnlen String Function in c - 

Syntax for strnlen -

size_t strnlen(const char *str, size_t maxlen)

size_t represents unsigned short
This function returns the length of a string if it is less than the value specified for maxlen (maximum length) otherwise it returns maxlen value.

Example - 


#include 
#include 
int main()
{
     char str1[20] = "functioninc";
     printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
     printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
     return 0;
}

Output - 
String length is 13 when maxlen is 30
String length is 10 when maxlen is 10

In the second string maxlen is 10 so its gives 10.
  • strcmp String Function in c - 

strcmp function compare two string and give integer value. If both string are same then it gives 0 otherwise it may return negative and positive values depends on the comparison.

Example - 


#include 
#include 
int main()
{
     char s1[20] = "functioninprogramming";
     char s2[20] = "functioninc";
     if (strcmp(s1, s2) ==0)
     {
        printf("string 1 and string 2 are equal");
     }else
      {
         printf("string 1 and 2 are different");
      }
     return 0;
}

  • strncmp String Function in c - 

int strncmp(const char *str1, const char *str2, size_t n)

size_t represents unsigned short
strncmp function compare two string for first n character for both string.

Example - 


#include 
#include 
int main()
{
     char s1[20] = "program";
     char s2[20] = "program";
     /* below it is comparing first 8 characters of s1 and s2*/
     if (strncmp(s1, s2, 7) ==0)
     {
         printf("string 1 and string 2 are equal");
     }else
     {
         printf("string 1 and 2 are different");
     }
     return 0;
}

Output
Both strings are same


  • strcat String Function in c - 

Syntax 

char *strcat(char *str1, char *str2)

This function merge two string and return concatenated string.

Example - 


#include 
#include 
int main()
{
     char s1[10] = "Hello";
     char s2[10] = "World";
     strcat(s1,s2);
     printf("Output string after concatenation: %s", s1);
     return 0;
}

Output

HelloWorld

  • strncat String Function in c -

This function merges n character of two string and return concatenated string.

 Example -

#include 
#include 
int main()
{
     char s1[10] = "Hello";
     char s2[10] = "World";
     strncat(s1,s2, 3);
     printf("Concatenation using strncat: %s", s1);
     return 0;
}

OUTPUT - 

Hellowor ( Where n is 3)

  •  strcpy String Function in c -


char *strcpy( char *str1, char *str2)

This function use to copy string str2 in str1 with (terminator char /0)

 Example - 

#include 
#include 
int main()
{
     char s1[30] = "string 1";
     char s2[30] = "string 2 : I’m gonna copied into s1";
     /* this function has copied s2 into s1*/
     strcpy(s1,s2);
     printf("String s1 is: %s", s1);
     return 0;
}

OUTPUT : -

 String s1 is
string 2 : I’m gonna copied into s1

  •  strncpy String Function in c -

char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned n number.


This function has two cases: - 
Case 1 : -  str2 > n then it just copies n number of character in str1 from str2.
Case 2 : - str2<n then it copies all the character in str1 from str2 and appends several terminator chars(‘\0’) in empty space because n is greater the str2.

Example of strncpy: 

#include 
#include 
int main()
{
     char first[30] = "string 1";
     char second[30] = "string 2: I’m using strncpy now";
     /* this function has copied first 10 chars of s2 into s1*/
     strncpy(s1,s2, 12);
     printf("String s1 is: %s", s1);
     return 0;
}

OUTPUT : - 
 str1 is
I’m using st

  •  strchr String Function in c - 

This function used to search string str for character ch

 Example of strchr : -


#include 
#include 
int main()
{
     char mystr[30] = "this is it";
     printf ("%s", strchr(mystr, 'i'));
     return 0;
}

Output : -

strchr gives it from mystr for i.

  •  strrchr String Function in c -

This function is  similar to the function strchr, the only difference is that function strrchr will search a string in reverse order let see the example : -

#include 
#include 
int main()
{
     char mystr[30] = "this is it";
     printf ("%s", strrchr(mystr, 'f'));
     return 0;
}

Output : -

strchr gives it from mystr for i.

  •  strstr String Function in c -


char *strstr(char *str, char *srch_term)

strstr function is similar to the strchr, the only difference is that it searches for a string instead of single char like strchr.

Example for strstr : -  
 

#include 
#include 
int main()
{
     char inputstr[70] = "String in C at funcationinprogramming.com";
     printf ("Output string is: %s", strstr(inputstr, 'func'));
     return 0;
}

Output : - 

String is funcationinprogramming

These all are the string functions in c programming you can learn about them and make a use of them to save time in programming.

Friday, May 15, 2020

learn function in c programming and header file

Function In C Programming is a reusable block of code that make a program simple and understandable a function can be modified or test without making any change in calling program. Function in programming language use to divided the code in number of subprograms which called as Function.


learn function in c programming and header file
learn function in c programming and header file


When you divided the program is Various subprograms, it becomes easy to manage every block of code or function easily. 


See positive end of function in programming : - 


If any error occur in any programming function then you can easily investigate faulty function and remove the error.

 You can easily call the function when you required which automatically save time and space of computer.


There Are Two Type Of Programming Function in C 

  • User Define Function In C
  • Library Function In C

 User Define Function In C programming Language : - 

As we all know a function is block of code that performs a specific task.

C Programming allows users to create an function according to their need and these function known as user define function in programming.

Library Function In C programming -

Instead of writing number of lines of code these function helps the programmer to save time by using already exist function in any programming language.  

Header File In C programming language

In order to access already function in C programming, certain header file need to be included before writing the body or any code.

List of header file in c programming language 

  • <stdio.h> (Standard input-output header)
This header file use to perform input and output operation like scanf() and printf().
  • <string.h> (String header)
use to perform all kind of operation related to string like strlen and strcpy.
  • <conio.h> (Console input-output header)
This header file Used to perform console input and console output operations like clrscr() to clear the screen and getch() to get the character from the keyboard.
  • <stdlib.h> (Standard library header)
This library header file used to perform standard function in c programming like malloc() and calloc() which are related to dynamic memory allocation.
  • <math.h> (Math header)
Use to perform mathematical operations like sqrt() and pow() and many more.
  • <ctype.h> (Character type header)
This header file helps to perform character type functions like isaplha() and isdigit() to find out about the given character is an alphabet or a digit.
  • <time.h> (Time header)
Use to perform function related to the date and time in c programming for example : - setdate() and getdate()
  • <assert.h> (Assertion header)
Use to perform function like assert( ) to get an integer type as a parameter.
  • <locale.h> (Localization header)
This header file Used to perform localization functions like setlocale() and localeconv() to set locale and get locale conventions.
  • <signal.h>(Signal header)
Used to perform signal handling functions like signal() and raise().
  • <setjmp.h> (Jump header)
Used in jump functions.
  • <stdarg.h> (Standard argument header)
Used to perform standard argument functions like va_start and va_arg().
  • <errno.h> (Error handling header)
Used to perform error handling operations like errno() to indicate errors in the program

Function in <stdio.h> header file 
this header file used almost in all kind of program written in c programming language.

  • printf() – Display output on the computer screen.
  • scanf() –  Take input from the user with the help of input device.
  • getchar() – Return characters on the computer screen.
  • putchar() – To display output as a single character on computer screen.
  • fgets() – Take a line as an input in C programming.
  • puts() –  Display a line as an output.
  • fopen() –  Open a file in C programming.
  • fclose() – Close a file in C programming.
Function in <Math.h> header file 

This header file is used in c programming when user wants to performs mathematical operations.

  • sqrt() – This function define in c to find the square root of a number
  • pow() – Function is used to find the power raised to that number.
  • fabs() – This function define in c to find the absolute value of a number.
  • log() – Find the logarithm of a number.
  • sin() – Find the sine value of a number.
  • cos() –  Define This function in c to find the cosine value of a number.
  • tan() – Define This function in c to find the tangent value of a number.
Example For Math.h in c programming 


#include 
#include 
int main()
{
printf("Welcome to DataFlair tutorials!\n\n");
double number=5, square_root;
int base = 6, power = 3, power_result;
int integer = -7, integer_result;
square_root = sqrt(number);
printf("The square root of %lf is: %lf\n", number, square_root);
power_result = pow(base,power);
printf("%d raised to the power %d is: %d\n", base, power, power_result);
integer_result = fabs(integer);
printf("The absolute value of %d is: %d\n", integer, integer_result);
return 0;
}

Function in <ctype.h> header file 

This header file is use character handling in  programming language. 

isalpha() –Check in c program if the character is an alphabet or not.
isdigit() – Check if the character is a digit or not in c program.
isalnum() – Used to check if the character is alphanumeric or not.
isupper() – Used to check if the character is in uppercase or not
islower() – Used to check if the character is in lowercase or not.
toupper() – Convert the character into uppercase.
tolower() – Convert the character into lowercase.
iscntrl() – Used to check if the character is a control character or not.
isgraph() – Used to check if the character is a graphic character or not.
isprint() – Check in c program if the character is a printable character or not
ispunct() – Check if the character is a punctuation mark or not.
isspace() – Used to check if the character is a white-space character or not.

isxdigit() – Used to check if the character is hexadecimal or not.


Summary 

This tutorial will help you to teach about all kind of used function in c programming language well this website design to explain library functions so we just focus on that. So here we discussed Header files and in build function in c programming language

Thank you for reading it.