atoi Function : Convert String of Number into Integer

Atoi Function :

  • Atoi = A to I = Alphabet to Integer
  • Convert String of number into Integer

Syntax:

num = atoi(String);
num   - Integer Variable
String- String of Numbers

Example :

num = atoi("1947");
printf("%d",num);

Output :

1947

Significance :

  1. Can Convert any String of Number into Integer Value that can Perform the arithmetic Operations like integer
  2. Header File : stdlib.h

Ways of Using Atoi Function :

Way 1 : Passing Variable in Atoi Function

// Variable marks is of Char Type
int num;
char marks[3] = "98";
num = atoi(marks);
printf("\nMarks : %d",num);

Way 2 : Passing Direct String in Atoi Function

int num;
num = atoi("98");
printf("\nMarks : %d",num);

C NULL Character

NULL Character : Terminating Character in String

We have already studied how string is declared and initialized now in this chapter we will be learning about terminating character of String i.e NULL Character.

Why do we need Terminating Character ?

  1. C Programming does not provide inbuilt ‘String‘ data type. [See Available Data Types in C]
  2. String is one of the most important and necessary Data Structure in C Programming
  3. We can say String as Variable length Structure stored in Fixed Length Structure
  4. Array Size is not the Actual Length of the String , So to recognize the End of the String we use NULL character

Pictorial Understanding :

NULL Character - Terminating String

Explanation :

In the above picture we can see -

  1. Before Initializing String it Contain Garbage Characters.
  2. Length of String [i.e Declared character array] is 7 so it Contain 7 Garbage Characters.
  3. When we attempt to store “CAT” in the string of Character length 7 then String Would be “CAT@’af
LocationValue Before InitializationValue After Initialization
name[0]aC
name[1];A
name[2]#T
name[3]`NULL Character
name[4]@@
name[5]aa
name[6]ff

Since valid String is “CAT” whenever we are trying to access the array using character array variable then valid string before NULL character will be considered as Valid.

Packing Up : Summary

Without NULL character string stored will beCAT'@af
NULL Character'\0'
ASCII Value of NULL Character0

C Reading String with Spaces : Using scanf()

Reading String with spaces by using scanf
Note that -

  1. scanf with %s accepts only String which does not contain whitespaces (blanks/space)
  2. C Supports the ‘ special Edit set Conversion Code ‘ , by using this method we can accept the line of String with spaces using scanf
  3. It Reads wide verity of Characters including blank

Syntax :

scanf("%[\^n]", name );

Live Example :

char name[100];
printf("\nEnter the name : ");
scanf("%[\^n]",name);
printf ("\nName of Student : %s ",name);

Output of this Block :

Enter the Name : Don Bosqo
Name of Student : Don Bosqo

C Arithmetic Operations On Character

Arithmetic Operations On Character :

  • C Programming Allows you to Manipulate on String
  • Whenever the Character is variable is used in the expression then it is automatically Converted into Integer Value called ASCII value
  • All Characters can be Manipulated with that Integer Value.(Addition,Subtraction)

Examples :

  1. ASCII value of : ‘a’ is 97
  2. ASCII value of : ‘z’ is 121

Possible Ways of Manipulation :
Way 1: Displays ASCII value[ Note that %d in Printf ]

char x = 'a';
printf("%d",x); // Display Result = 97

Way 2 : Displays Character value[ Note that %c in Printf ]

char x = 'a';
printf("%c",x); // Display Result = a

Way 3 : Displays Next ASCII value[ Note that %d in Printf ]

char x = 'a' + 1 ;
printf("%d",x);
// Display Result = 98 ( ascii of 'b' )

Way 4 Displays Next Character value[Note that %c in Printf ]

char x = 'a' + 1;
printf("%c",x); // Display Result = 'b'

Way 5 : Displays Difference between 2 ASCII in Integer[Note %d in Printf ]

char x = 'z' - 'a';
printf("%d",x);
/* Display Result = 25 
    (difference between ASCII of z and a ) */

Way 6 : Displays Difference between 2 ASCII in Char [Note that %c in Printf ]

char x = 'z' - 'a';
printf("%c",x);
/* Display Result = ↓ 
      ( difference between ASCII of z and a ) */

C putchar() Function : C Reference

Putchar function : Displaying String in C Programming
Syntax :

int putchar(int c);

Way 1 : Taking Character as Parameter

putchar('a') ;  // Displays : a
  1. Individual Character is Given as parameter to this function.
  2. We have to explicitly mention Character.

Way 2 : Taking Variable as Parameter

putchar(a); 
// Display Character Stored in a
  1. Input Parameter is Variable of Type “Character”.
  2. This type of putchar() displays character stored in variable.

Way 3 : Displaying Particular Character from Array

putchar(a[0]) ;  
// Display a[0] th element from array
  1. Character Array or String consists of collection of characters.
  2. Like accessing individual array element , characters can be displayed one by one using putchar().

Live Example :

#include< stdio.h>
#include< conio.h>
void main()
{
   char string[] = "This is an example string\n";
   int i=0;
   clrscr();
   while(string[i]!='\0')
   {
     putchar(string[i]);
     i++;
   }
getch();
}

What it Does ?

  1. Display String Character by Character
  2. Header File : stdio.h
  3. Putchar is a macro that outputs a character on stdout.

Related Articles :

  1. How to Input Password in C : Validation of User name
  2. Putchar function >> Displaying String in C
  3. Puts >> Displaying String in C Programming
  4. Printf >> Displaying String in C Programming

C puts() Function : C Reference

Puts >> Displaying String in C Programming :
Way 1 :Messaging

puts(" Type your Message / Instruction ");
  • Like Printf Statement puts() can be used to display message.

Way 2 : Display String

puts(string_Variable_name) ;

Notes or Facts :

  1. puts is included in header file “stdio.h”
  2. As name suggest it used for Printing or Displaying Messages or Instructions

Uses :

  1. Printing Message
  2. Ask user for entering the data ( Labels . Instructions )
  3. Printing Results

Live Example :

#include< stdio.h>
#include< conio.h>
void main()
  {
   char string[] = "This is an example string\n";
   puts(string);     // String is variable Here
   puts("String");   // String is in Double Quotes
   getch();
}

Output :

String is : This is an example string
String is : String

Related Articles :

  1. How to Input Password in C : Validation of User name
  2. Putchar function >> Displaying String in C
  3. Puts >> Displaying String in C Programming
  4. Printf >> Displaying String in C Programming

C printf() Function : C Reference

Printf >> Displaying String in C Programming :


Syntax :

  • Way 1 : Messaging
printf (" Type your Message / Instruction " ) ;
  • Way 2 : Display String
printf ("Name of Person is %s ", name ) ;

Notes or Facts :

  1. printf is included in header file “stdio.h”
  2. As name suggest it used for Printing or Displaying Messages or Instructions

Uses :

  1. Printing Message
  2. Ask user for entering the data ( Labels . Instructions )
  3. Printing Results

Live Example :

#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
printf("Enter the String : ");
scanf("%s",str);  // Accept String
printf("String is : %s ",str);
getch();
}

Output :

Enter the String : Pritesh
String is : Pritesh

Related Articles :

  1. How to Input Password in C : Validation of User name
  2. Putchar function >> Displaying String in C
  3. Puts >> Displaying String in C Programming
  4. Printf >> Displaying String in C Programming

C getchar() Function : C Reference

getchar() : Reading or Accepting String Character by Character

In C Programming we have many input/output functions that are useful for accepting input from the user. i.e scanf() | gets(). Getchar() function is also one of the function which is used to accept the single character from the user.
[box]

Note :

The characters accepted by getchar() are buffered until RETURN is hit means getchar() does not see the characters until the user presses return. (i.e Enter Key)
[/box]

Syntax for Accepting String and Working :

/* getchar accepts character & stores in ch */
char ch = getchar();

When control is on above line then getchar() function will accept the single character. After accepting character control remains on the same line. When user presses the enter key then getchar() function will read the character and that character is assigned to the variable ‘ch’.

ParameterExplanation
Header Filestdio.h
Return Typeint (ASCII Value of the character)
ParameterVoid
UseAccepting the Character

getchar() Example 1 :

In the following example we are just accepting the single character and printing it on the console -

main()
{
   char ch;
   ch = getchar();
   printf("Accepted Character : %c",ch);
}

Output :

Accepted Character : A

getchar() Example 2 : Accepting String (Use One of the Loop)

#include<stdio.h>
void main()
{
int i = 0;
char name[20]; 
printf("\nEnter the Name : "); 
while((name[i] = getchar())!='\n')
        i++ ;
getch();
}

Explanation of the above Program :

while((name[i] = getchar())!='\n')
        i++ ;

above while loop will accept the one character at a time and check it with newline character. Whenever user enters newline character then control comes out of the loop.

C gets() Function : C Reference

gets() function : Reading or Accepting String From User in C

Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.


Syntax for Accepting String :

char * gets ( char * str );

OR

gets( <variable-name> )

Live Example :

#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name : ");
gets(name);
}

Explanation :

  1. Whenever gets() statement encounters then characters entered by user (the string with spaces) will be copied into the variable.
  2. If user start accepting characters , and if new line character appears then the newline character will not be copied into the string variable(i.e name).
  3. A terminating null character is automatically appended after the characters copied to string vriable (i.e name)
  4. gets() uses stdin (Standered Input Output) as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for string variable (which can lead to buffer overflows).

Some Legal Declarations :

StatementUseSizeTerminates
gets(name)Accepting Name of Person with SpacesNo SpecificationAfter Enter Key
gets(city)Accepting Name of CityNo SpecificationAfter Enter Key
gets(address)Accepting address with SpacesNo SpecificationAfter Enter Key
gets(bname)Accepting book nameNo SpecificationAfter Enter Key

Some Rules and Facts :

A. %s is not Required :

Like scanf statement %s is not necessary while accepting string.

scanf("%s",name);

and here is gets() syntax which is simpler than scanf() -

gets(name);

B. Spaces are allowed in gets() :

gets(name);

Whenever the above line encounters then interrupt will wait for user to enter some text on the screen. When user starts typing the characters then all characters will be copied to string and when user enters newline character then process of accepting string will be stopped.

Sample Input Accepted by Above Statement :

Value Accepted : Pritesh Taral\n
Value Stored   : Pritesh Taral    (\n Neglected)
Initializing String / Charater Array in C Programming

C Strings Initialization

In the previous chapter we have learnt about declaring array of character i.e String. In this chapter we are looking one step forward - Initializing the String and Different ways of Initializing String.

Initializing String [Character Array] :

Whenever we declare a String then it will contain garbage values inside it. We have to initialize String or Character array before using it. Process of Assigning some legal default data to String is Called Initialization of String. There are different ways of initializing String in C Programming -

  1. Initializing Unsized Array of Character
  2. Initializing String Directly
  3. Initializing String Using Character Pointer

Way 1 : Unsized Array and Character

  1. Unsized Array : Array Length is not specified while initializing character array using this approach
  2. Array length is Automatically calculated by Compiler
  3. Individual Characters are written inside Single Quotes , Separated by comma to form a list of characters. Complete list is wrapped inside Pair of Curly braces
  4. Please Note : NULL Character should be written in the list because it is ending or terminating character in the String/Character Array
char name [] = {'P','R','I','T','E','S','H','\0'};

Way 2 : Directly initialize String Variable

  1. In this method we are directly assigning String to variable by writing text in double quotes.
  2. In this type of initialization , we don’t need to put NULL or Ending / Terminating character at the end of string. It is appended automatically by the compiler.
char name [ ] = "PRITESH";

Way 3 : Character Pointer Variable

  1. Declare Character variable of pointer type so that it can hold the base address of “String”
  2. Base address means address of first array element i.e (address of name[0] )
  3. NULL Character is appended Automatically
char *name = "PRITESH";

Initializing String / Charater Array in C Programming