C Programming Code Examples
C > Strings Code Examples
program to find the first occurrence of a character in a string
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* program to find the first occurrence of a character in a string
Write a C program to input any string from user and find the first occurrence of a given character in the string. How to find the first occurrence of a given character in a string in C programming.
Input string from user, store it in some variable say str.
Run a loop from start character of the string to end character.
Check if current character is matched with the search character. If match is found then terminate the above loop and return current character index. */
#include <stdio.h>
#include <string.h>
#define maxsize 100 // Maximum string size
/* Function declaration */
int indexOf(const char * str, const char toFind);
int main()
{
char str[maxsize];
char toFind;
int index;
/* Input string from user and character to be searched */
printf("Enter any string: ");
gets(str);
printf("Enter character to be searched: ");
toFind = getchar();
index = indexOf(str, toFind);
if(index == -1)
printf("'%c' not found.", toFind);
else
printf("'%c' is found at index %d.", toFind, index);
return 0;
}
/* Returns the first index of the given character toFind in the string.
If returns -1 if the given character toFind does not exists in the string. */
int indexOf(const char * str, const char toFind)
{
int j = 0;
while(str[j] != '\0')
{
if(str[j] == toFind)
return j;
j++;
}
// Return -1 as character not found
return -1;
}
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* if else statement in C language */
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
While Loop Statement in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.
The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
Syntax of While Loop Statement in C
while (testExpression) {
// the body of the loop
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* while loop statement in C language */
#include<stdio.h>
int main()
{
int n, num, sum = 0, remainder;
printf("Enter a number: ");
scanf("%d", &n);
num = n;
// keep looping while n > 0
while( n > 0 )
{
remainder = n % 10; // get the last digit of n
sum += remainder; // add the remainder to the sum
n /= 10; // remove the last digit from n
}
printf("Sum of digits of %d is %d", num, sum);
// signal to operating system everything works fine
return 0;
}
printf() Function in C
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h>
int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream.
The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* print formatted data to stdout by printf() function example */
#include <stdio.h>
int main()
{
char ch;
char str[100];
int a;
float b;
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts.
main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined.
main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.
Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main()
{
.........
// codes start from here
.........
}
void
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library.
• An operating system always calls the main() function when a programmers or users execute their programming code.
• It is responsible for starting and ends of the program.
• It is a universally accepted keyword in programming language and cannot change its meaning and name.
• A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program.
• A main() function is used to invoke the programming code at the run time, not at the compile time of a program.
• A main() function is followed by opening and closing parenthesis brackets.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* basic c program by main() function example */
#include <stdio.h>
#include <conio.h>
main()
{
printf (" It is a main() function ");
int fun2(); // jump to void fun1() function
printf ("\n Finally exit from the main() function. ");
}
void fun1()
{
printf (" It is a second function. ");
printf (" Exit from the void fun1() function. ");
}
int fun2()
{
void fun1(); // jump to the int fun1() function
printf (" It is a third function. ");
printf (" Exit from the int fun2() function. ");
return 0;
}
getchar() Function in C
Get character from stdin. Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument.
A getchar() function is a non-standard function whose meaning is already defined in the stdin.h header file to accept a single input from the user. In other words, it is the C library function that gets a single character (unsigned char) from the stdin. However, the getchar() function is similar to the getc() function, but there is a small difference between the getchar() and getc() function of the C programming language. A getchar() reads a single character from standard input, while a getc() reads a single character from any input stream.
Syntax for getchar() Function in C
#include <stdio.h>
int getchar ( void );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* gets a single character (unsigned char) from the stdin by getchar() function example */
#include <stdio.h>
#include <ctype.h>
int main()
{
int ch, i = 0;
char str[150];
printf (" Enter the characters from the keyboard (Press Enter button to stop).\n");
// use do while loop to define the condition
do
{
ch = getchar(); // takes character, number, etc from the user
str[i] = ch; // store the ch into str[i]
i++; // increment loop by 1
} while (ch != '\n'); // ch is not equal to '\n'
printf("Entered characters are %s ", str);
return 0;
}
#define Directive in C
In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.
Syntax for #define Directive in C
#define NAME value /* this syntax creates a constant using define*/
// Or
#define NAME (expression) /* this syntax creates a constant using define*/
NAME
is the name of a particular constant. It can either be defined in smaller case or upper case or both. Most of the developers prefer the constant names to be in the upper case to find the differences.
value
defines the value of the constant.
Expression
is the value that is assigned to that constant which is defined. The expression should always be enclosed within the brackets if it has any operators.
In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the micro substitution.
The #define directive can use any of the basic data types present in the C standard. The #define preprocessor directive lets a programmer or a developer define the macros within the source code.
This macro definition will allow the constant value that should be declared for the usage. Macro definitions cannot be changed within the program's code as one does with other variables, as macros are not variables.
The #define is usually used in syntax that created a constant that is used to represent numbers, strings, or other expressions.
The #define directive should not be enclosed with the semicolon(;). It is a common mistake done, and one should always treat this directive as any other header file. Enclosing it with a semicolon will generate an error.
The #define creates a macro, which is in association with an identifier or is parameterized identifier along with a token string. After the macro is defined, then the compiler can substitute the token string for each occurrence of the identifier within the source file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. */
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "XCoder");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
#include Directive in C
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:
• Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions.
• User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax for #include Directive in C
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */
// C program to illustrate file inclusion
// <> used to import system header file
#include <stdio.h>
// " " used to import user-defined file
#include "process.h"
// main function
int main()
{
// add function defined in process.h
add(10, 20);
// mult function defined in process.h
multiply(10, 20);
// printf defined in stdio.h
printf("Process completed");
return 0;
}
gets() Function in C
Get string from stdin. 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.
The newline character, if found, is not copied into str.
A terminating null character is automatically appended after the characters copied to str.
Notice that gets is quite different from fgets: not only gets uses stdin 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 str (which can lead to buffer overflows).
The gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Syntax for gets() Function in C
#include<stdio.h>
char * gets ( char * str );
str
Pointer to a block of memory (array of char) where the string read is copied as a C string.
On success, the function returns str.
If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* read characters from the standard input (stdin) and stores them as a C string */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
FILE *fp;
char fname[20];
printf("Enter filename : ");
gets(fname);
fp=fopen(fname, "r");
if(fp==NULL)
{
printf("Error in opening the file..!!\n");
printf("Press any key to exit..\n");
getch();
exit(1);
}
fclose(fp);
getch();
}
Recursive function in C to Check Palindrome number. Declare recursive function to check palindrome. First give a meaningful name to our function, say isPalindrome(). Along with