C – Operators

C – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. By definition, an operator performs a certain operation on operands. An operator needs one or more operands for the operation to be performed. Depending on how many operands are required to perform the operation, operands are called as unary, binary or ternary operators. They need one, two or three operands respectively. Unary operators − ++ (increment), — (decrement), ! (NOT), ~ (compliment), & (address of), * (dereference) Binary operators − arithmetic, logical and relational operators except ! Ternary operators − The ? operator C language is rich in built-in operators and provides the following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators We will, in this chapter, look into the way each operator works. Here, you will get an overview of all these chapters. Thereafter, we have provided independent chapters on each of these operators that contain plenty of examples to show how these operators work in C Programming. Arithmetic Operators We are most familiar with the arithmetic operators. These operators are used to perform arithmetic operations on operands. The most common arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). In addition, the modulo (%) is an important arithmetic operator that computes the remainder of a division operation. Arithmetic operators are used in forming an arithmetic expression. These operators are binary in nature in the sense they need two operands, and they operate on numeric operands, which may be numeric literals, variables or expressions. For example, take a look at this simple expression − a + b Here “+” is an arithmetic operator. We shall learn more about arithmetic operators in C in a subsequent chapter. The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then − Show Examples Operator Description Example &plus; Adds two operands. A &plus; B = 30 − Subtracts second operand from the first. A − B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by de-numerator. B / A = 2 % Modulus Operator and remainder of after an integer division. B % A = 0 ++ Increment operator increases the integer value by one. A++ = 11 — Decrement operator decreases the integer value by one. A– = 9 Relational Operators We are also acquainted with relational operators while learning secondary mathematics. These operators are used to compare two operands and return a boolean value (true or false). They are used in a boolean expression. The most common relational operators are less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equal to (==), and not equal to (!=). Relational operators are also binary operators, needing two numeric operands. For example, in the Boolean expression − a > b Here, “>” is a relational operator. We shall learn more about with relational operators and their usage in one of the following chapters. Show Examples Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true. Logical Operators These operators are used to combine two or more boolean expressions. We can form a compound Boolean expression by combining Boolean expression with these operators. An example of logical operator is as follows − a >= 50 && b >= 50 The most common logical operators are AND (&&), OR(||), and NOT (!). Logical operators are also binary operators. Show Examples Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A && B) is true. We will discuss more about Logical Operators

C – Type Conversion

Type Conversion in C ”; Previous Next The C compiler attempts data type conversion, especially when dissimilar data types appear in an expression. There are certain times when the compiler does the conversion on its own (implicit type conversion) so that the data types are compatible with each other. On other occasions, the C compiler forcefully performs the conversion (explicit type conversion), which is carried out by the type cast operator. Implicit Type Conversion in C In C, implicit type conversion takes place automatically when the compiler converts the type of one value assigned to a variable to another data type. It typically happens when a type with smaller byte size is assigned to a “larger” data type. In such implicit data type conversion, the data integrity is preserved. While performing implicit or automatic type conversions, the C compiler follows the rules of type promotions. Generally, the principle followed is as follows − Byte and short values: They are promoted to int. If one operand is a long: The entire expression is promoted to long. If one operand is a float: The entire expression is promoted to float. If any of the operands is double: The result is promoted to double. Integer Promotion Integer promotion is the process by which values of integer type “smaller” than int or unsigned int are converted either to int or unsigned int. Example Consider an example of adding a character with an integer − #include <stdio.h> int main(){ int i = 17; char c = ”c”; /* ascii value is 99 */ int sum; sum = i + c; printf(“Value of sum: %dn”, sum); return 0; } Output When you run this code, it will produce the following output − Value of sum: 116 Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of “c” to ASCII before performing the actual addition operation. Usual Arithmetic Conversion Usual arithmetic conversions are implicitly performed to cast their values to a common type. The compiler first performs integer promotion; if the operands still have different types, then they are converted to the type that appears highest in the following hierarchy − Example Here is another example of implicit type conversion − #include <stdio.h> int main(){ char a = ”A”; float b = a + 5.5; printf(“%f”, b); return 0; } Output Run the code and check its output − 70.500000 When the above code runs, the char variable “a” (whose int equivalent value is 70) is promoted to float, as the other operand in the addition expression is a float. Explicit Type Conversion in C When you need to covert a data type with higher byte size to another data type having lower byte size, you need to specifically tell the compiler your intention. This is called explicit type conversion. C provides a typecast operator. You need to put the data type in parenthesis before the operand to be converted. type2 var2 = (type1) var1; Note that if type1 is smaller in length than type2, then you don’t need such explicit casting. It is only when type1 is greater in length than type2 that you should use the typecast operator. Typecasting is required when we want to demote a greater data type variable to a comparatively smaller one or convert it between unrelated types like float to int. Example Consider the following code − #include <stdio.h> int main(){ int x = 10, y = 4; float z = x/y; printf(“%f”, z); return 0; } Output On running this code, you will get the following output − 2.000000 While we expect the result to be 10/4 (that is, 2.5), it shows 2.000000. It is because both the operands in the division expression are of int type. In C, the result of a division operation is always in the data type with larger byte length. Hence, we have to typecast one of the integer operands to float, as shown below − Example Take a look at this example − #include <stdio.h> int main(){ int x = 10, y = 4; float z = (float)x/y; printf(“%f”, z); return 0; } Output Run the code and check its output − 2.500000 If we change the expression such that the division itself is cast to float, the result will be different. Typecasting Functions in C The standard C library includes a number of functions that perform typecasting. Some of the functions are explained here − The atoi() Function The atoi() function converts a string of characters to an integer value. The function is declared in the stdlib.h header file. Example The following code uses the atoi() function to convert the string “123” to a number 123 − #include <stdio.h> #include <stdlib.h> int main(){ char str[] = “123”; int num = atoi(str); printf(“%dn”, num); return 0; } Output Run the code and check its output − 123 The itoa() Function You can use the itoa() function to convert an integer to a null terminated string of characters. The function is declared in the stdlib.h header file. Example The following code uses itoa() function to convert an integer 123 to string “123” − #include <stdio.h> #include <stdlib.h> int main(){ int num = 123; char str[10]; itoa(num,str, 10); printf(“%sn”, str); return 0; } Output Run the code and check its output − 123

C – Questions & Answers

C Programming Questions and Answers ”; Previous Next C Programming Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. Sr.No Question/Answers Type 1 C Programming Interview Questions This section provides a huge collection of C Programming Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 C Programming Online Quiz This section provides a great collection of C Programming Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 C Programming Online Test If you are preparing to appear for a Java and C Programming Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 C Programming Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

C – Preprocessor Operators

Preprocessor Operators in C ”; Previous Next Preprocessor operators are special symbol(s) that are used in the context of the #define directive. These operators are also called preprocessor-specific operators. In C, a set of preprocessor operators have been defined, each with an important operation attached with it. In this chapter, we will explain the different types of preprocessor operators used in C. The following preprocessor operators are implemented by most of the modern C compilers − Operator Action Continuation operator (/) Used to continue a macro that is too long for a single line. Stringizing operator (#) Causes the corresponding actual argument to be enclosed in double quotation marks Token-pasting operator (##) Allows tokens used as actual arguments to be concatenated to form other tokens defined operator Simplifies the writing of compound expressions in certain macro directives Let us now discuss in detail about each of these preprocessor operators. Continuation Operator (/) This operator is used where the macro is quite complex, and spreads over multiple lines. In case of a complex logic inside macro expansion, you’ll need to break the line and write code that spreads over more than one lines. In such cases macro continuation operator is very helpful. Example 1: Preprocessor Continuation Operator (/) In the example below, we are writing a part of the macro in the next line, so we are making use of macro continuation preprocessor operator (). #include <stdio.h> #define message() { printf(“TutorialsPoint Library containsn”); printf(“High quality Programming Tutorials”); } int main() { message(); return 0; } Output When you run this code, it will produce the following output − TutorialsPoint Library contains High quality Programming Tutorials Example 2: Preprocessor Continuation Operator (/) In the following example, the macro definition involves evaluation of a switch case statement, hence it spreads over multiple lines, requiring the macro continuation character. #include <stdio.h> #define SHAPE(x) switch(x) { case 1: printf(“1. CIRCLEn”); break; case 2: printf(“2. RECTANGLEn”); break; case 3: printf(“3. SQUAREn”); break; default: printf(“default. LINEn”); } int main() { SHAPE(1); SHAPE(2); SHAPE(3); SHAPE(0); return 0; } Output When you run this code, it will produce the following output − 1. CIRCLE 2. RECTANGLE 3. SQUARE default. LINE Stringizing Operator (#) Sometimes you may want to convert a macro argument into a string constant. The number-sign or “stringizing” operator (#) converts macro parameters to string literals without expanding the parameter definition. This operator may be used only in a macro having a specified argument or parameter list. Example 1: Stringizing Operator Take a look at the following example − #include <stdio.h> #define stringize(x) printf(#x “n”) int main() { stringize(Welcome To TutorialsPoint); stringize(“The Largest Tutorials Library”); stringize(“Having video and Text Tutorials on Programming Languages”); } Output When you run this code, it will produce the following output − Welcome To TutorialsPoint “The Largest Tutorials Library” “Having video and Text Tutorials on Programming Languages” Example 2: Stringizing Operator The following code shows how you can use the stringize operator to convert some text into string without using any quotes. #include <stdio.h> #define STR_PRINT(x) #x main() { printf(STR_PRINT(This is a string without double quotes)); } Output Run the code and check its output − This is a string without double quotes Token Pasting Operator (##) The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator. It is often useful to merge two tokens into one while expanding macros. When a macro is expanded, the two tokens on either side of each “##” operator are combined into a single token, which then replaces the “##” and the two original tokens in the macro expansion. Example 1: Token Pasting Operator (##) Take a look at the following example − #include <stdio.h> #define PASTE(arg1,arg2) arg1##arg2 main() { int value_1 = 1000; printf(“value_1 = %dn”, PASTE(value_,1)); } Output When you run this code, it will produce the following output − value_1 = 1000 Example 2: Token Pasting Operator (##) In the example below, we pass two arguments to the macro. #include <stdio.h> #define TOKENS(X, Y) X##Y int main() { printf(“value1: %dn”,TOKENS(12,20)); printf(“value2: %dn”,TOKENS(12,20)+10); return 0; } Output When you run this code, it will produce the following output − value1: 1220 value2: 1230 The defined Operator The defined preprocessor operator can only be used as a part of #if and #elif directives. The syntax of defined operator is as follows − #if defined(macro1) // code #elif defined(macro2) // code #endif It is used in constant expressions to determine if an identifier is defined. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). Example 1: defined Operator In this example, the defined operator is used to check if the DEBUG macro is defined. If it is, the program prints “DEBUG mode is on.” Otherwise, it prints “DEBUG mode is off.” #include <stdio.h> #define DEBUG 1 int main() { #if defined(DEBUG) printf(“DEBUG mode is on.n”); #else printf(“DEBUG mode is off.n”); #endif return 0; } Output Run the code and check its output − DEBUG mode is on. Example 2: defined Operator The following code checks if the square macro has been already defined, and if so, expands it with the given value of “x”

C – Discussion

Discuss C ”; Previous Next C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers. Print Page Previous Next Advertisements ”;

C – Enumeration (or enum)

Enumeration (or enum) in C ”; Previous Next Enumeration (or enum) in C C enumeration (enum) is an enumerated data type that consists of a group of integral constants. Enums are useful when you want to assign user-defined names to integral constants. The enum keyword is used to define enums. Defining and Declaring an Enum Type To declare and define an enumeration (enum) data type, use the enum keyword followed by the enum name and assign all values inside the curly braces. Syntax This is the syntax you would use to define an enum type − enum enum_name{const1, const2, … }; Enum Variable Declaration After declaring an enumeration type, you can also declare its variable to access enumeration members (constants). To declare an enum variable, write the enum keyword followed by the enaum name (enum_name) and then the variable name (var). Syntax Below is the syntax to declare a variable of enum type − enum enum_name var; Example Let us define an enum type with the name myenum − enum myenum {val1, val2, val3, val4}; Identifier values are unsigned integers and they start from “0”. val1 refers 0, val2 refers 1, and so on. A variable of myenum type is declared as follows − enum myenum var; The possible constant values of myenum type are enumerated inside the curly brackets. Change Enum Constants Values When we declare an enum type, the first constant of the enum is initialized with 0 by default, the second constant is initialized with 1, and so on. We can also assign any integer value to any constant of enum. Example In the following example, we are declaring an enum type and assigning different values to the enum constants. #include <stdio.h> enum status_codes { OKAY = 1, CANCEL = 0, ALERT = 2 }; int main() { // Printing values printf(“OKAY = %dn”, OKAY); printf(“CANCEL = %dn”, CANCEL); printf(“ALERT = %dn”, ALERT); return 0; } Output It will produce the following output − OKAY = 1 CANCEL = 0 ALERT = 2 Enum in Switch Statements C language switch case statement works with integral values. We can use enum type to define constants with (or, without) integral type values to use them in switch case statements. Example In the following example, the colors in the rainbow are enumerated. #include <stdio.h> // Enum declaration enum colors { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED }; int main() { // Enum variable declaration enum colors color = YELLOW; // switch statement using enum switch (color) { case BLUE: printf(“Blue color”); break; case GREEN: printf(“Green color”); break; case RED: printf(“Red color”); break; default: printf(“Color other than RGB”); } return 0; } Output Run the code and check its output − Color other than RGB Examples of Enumeration (enum) Type Practice the following examples to understand the concept of enumeration (or, enum) type in C programming language. Example 1: Enum Constants Get Incrementing Integer Values C assigns incrementing integer values to each constant, starting with “0”. When we assign val2 to the above variable, var = val2; The integer value assigned to val2 is 1. Take a look at the following example − #include <stdio.h> enum myenum {val1, val2, val3, val4}; int main(){ enum myenum var; var = val2; printf(“var = %d”, var); return 0; } Output It will produce the following output − var = 1 Example 2: Enumerating the Weekdays Let us declare an enum type weekdays to enumerate the names of the days and assign its value to the enum type variable − #include <stdio.h> int main(){ enum weekdays {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; printf (“Monday = %dn”, Mon); printf (“Thursday = %dn”, Thu); printf (“Sunday = %dn”, Sun); } Output It will produce the following output − Monday = 1 Thursday = 4 Sunday = 0 Example 3: Declaring a Variable of Enum Type A typical application of enumerated data types is to assign weekdays to the integer values. In this code, we have declared a variable of weekdays enum type − #include <stdio.h> enum weekdays {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; int main(){ enum weekdays day; day = Wed; printf(“Day number of Wed is = %d”, day); return 0; } Output When you run this code, it will produce the following output − Day number of Wed is = 3 Example 4: Enum Values By Default Start from “0” In this code, we define an enum type for names of the month in a calendar year. By default, C assigns the values starting from “0”. For example, in the following C program, Jan gets the value “0”, Feb gets “1”, and so on. #include <stdio.h> enum months{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main(){ for (int i = Jan; i <= Dec; i++) printf(“Month No: %dn”, i); return 0; } Output Run the code and check its output − Month No: 0 Month No: 1 Month No: 2 Month No: 3 Month No: 4 Month No: 5 Month No: 6 Month No: 7 Month No: 8 Month No: 9 Month No: 10 Month No: 11 Example 5: Starting an Enum from 1 To start enumeration from 1, assign 1 explicitly to the first value, the compiler will assign incrementing numbers to the subsequent values. #include <stdio.h> enum

C – Basic Syntax

C – Basic Syntax ”; Previous Next In C programming, the term “syntax” refers to the set of rules laid down for the programmer to write the source code of a certain application. While there is a specific syntax recommended for each of the keywords in C, certain general rules need to be followed while developing a program in C. A typical source code of a C program has the following elements − /*Hello World program*/ // Comments #include <stdio.h> // Header File int a=10; // Global declarations // The main function int main() { char message[] = “Hello World”; // Local variable printf(“%s”, message); return 0; } Tokens in C A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens − printf(“Hello, World! n”); The individual tokens are − printf ( “Hello, World! n” ); The C compiler identifies whether the token is a keyword, identifier, comment, a literal, an operator, any of the other recognized special symbols or not. This exercise is done by the tokenizer in the first stage of the compilation process. Identifiers in C A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore ”_” followed by zero or more letters, underscores, and digits (0 to 9). C prescribes certain rules to form the names of variables, functions or other programming elements. They are not keywords. An identifier must start with an alphabet or underscore character, and must not have any other character apart from alphabets, digits and underscore. C does not allow punctuation characters such as @, $, and % within identifiers. C is a case−sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal Keywords in C The most important part of C language is its keywords. Keywords are the reserved words having a predefined meaning with prescribed syntax for usage. In ANSI C, all keywords have lowercase alphabets. The programmer needs to choose the correct keywords to construct the solution of the problem at hand. To learn programming is basically to learn to correctly use the keywords. The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names. auto else long switch break enum register typedef case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double Each keyword in C has a well−defined syntax in addition to the basic syntax explained in this chapter. The usage of each keyword will be explained in the subsequent chapters. Semicolons in C In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. Given below are two different statements − printf(“Hello, World! n”); return 0; Since the semicolon “;” is only the delimiter symbol for a C statement, there may be more than one statements in a one physical line in a C program. Similarly, a single statement may span over more than one lines in the source code. The following line is perfectly valid in C. In one line, there are multiple statements − int a=10; if (a>=50) printf(“pass”); else printf(“fail”); The following code is also valid even if a statement spills over multiple lines − if (a>=50) printf(“pass”); else printf(“fail”); Comments in C Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below − /* my first program in C */ You cannot have comments within comments and they do not occur within a string or character literals. Source Code The C program is a text file, containing a series of statements. The file must have a .c as its extension. The C compiler identifies only the .c file for compilation process. Only the English alphabets are used in the keywords and other identifiers of C language, although the string literals may contain any Unicode characters. The main() Function Every C program must have one (and only one) main() function, from where the compiler starts executing the code. However, it is not necessary that the main() function should be in the beginning of the code in the .c file. There can be any number of functions in a C program. If a function calls any other function before its definition, there should be its forward declaration. Header Files In addition to the keywords, a C program often needs to call predefined functions from the library of header files. The required header files are imported with the #include preprocessor directive. All the #include statements must be in the beginning of the source code. Variable Declaration C is a statically typed language. It requires, all the variables appearing in a program to be declared before using. Variables can be declared globally i.e. outside any function, or locally within

C – Integer Promotions

Integer Promotions in C ”; Previous Next The C compiler promotes certain data types to a higher rank for the sake of achieving consistency in the arithmetic operations of integers. In addition to the standard int data type, the C language lets you work with its subtypes such as char, short int, long int, etc. Each of these data types occupy a different amount of memory space. For example, the size of a standard int is 4 bytes, whereas a char type is 2 bytes of length. When an arithmetic operation involves integer data types of unequal length, the compiler employs the policy of integer promotion. Integer Promotions As a general principle, the integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int. One must understand the concept of integer promotion to write reliable C code, and avoid unexpected problems related to the size of data types and arithmetic operations on smaller integer types. Example In this example, the two variables a and b seem to be storing the same value, but they are not equal. #include <stdio.h> int main(){ char a = 251; unsigned char b = a; printf(“a = %c”, a); printf(“nb = %c”, b); if (a == b) printf(“n Same”); else printf(“n Not Same”); return 0; } Output When you run this code, it will produce the following output − a = √ b = √ Not Same You get this output because “a” and “b” are treated as integers during comparison. “a” is a signed char converted to int as -5, while “b” is an unsigned char converted to int as 251. Example: Mechanism of Integer Promotions Let us try to understand the mechanism of integer promotions with this example − #include <stdio.h> int main(){ char a = ”e”, b = ”2”, c = ”M”; char d = (a * b) / c; printf(“d as int: %d as char: %c”, d, d); return 0; } Output Run the code and check its output − d as int: 65 as char: A When Integer Promotion is Applied? In the arithmetic expression “(a * b) / c”, the bracket is solved first. All the variables are of signed char type, which is of 2 byte length and can store integers between -128 to 127. Hence the multiplication goes beyond the range of char but the compiler doesn”t report any error. The C compiler applies integer promotion when it deals with arithmetic operations involving small types like char. Before the multiplication of these char types, the compiler changes them to int type. So, in this case, (a * b) gets converted to int, which can accommodate the result of multiplication, i.e., 1200. Example Integer promotions are applied as part of the usual arithmetic conversions to certain argument expressions; operands of the unary +, -, and ~ operators; and operands of the shift operators. Take a look at the following example − #include <stdio.h> int main(){ char a = 10; int b = a >> 3; printf(“b as int: %d as char: %c”, b, b); return 0; } Output When you run this code, it will produce the following output − b as int: 1 as char: In the above example, shifting the bit structure of “a” to the left by three bits still results in its value within the range of char (a << 3 results in 80). Example In this example, the rank of the char variable is prompted to int so that its left shift operation goes beyond the range of char type. #include <stdio.h> int main(){ char a = 50; int b = a << 2; printf (“b as int: %d as char: %c”, b, b); return 0; } Output Run the code and check its output − b as int: 200 as char: ╚ Integer Promotion Rules Promotion rules help the C compiler in maintaining consistency and avoiding unexpected results. The fundamental principle behind the rules of promotion is to ensure that the expression”s type is adjusted to accommodate the widest data type involved, preventing data loss or truncation. Here is a summary of promotion rules as per C11 specifications − The integer types in C are char, short, int, long, long long and enum. Booleans are also treated as an integer type when it comes to type promotions. No two signed integer types shall have the same rank, even if they have the same representation. The rank of a signed integer type shall be greater than the rank of any signed integer type with less precision. The rank of long int > the rank of int > the rank of short int > the rank of signed char. The rank of char is equal to the rank of signed char and unsigned char. Whenever a small integer type is used in an expression, it is implicitly converted to int which is always signed. All small integer types, irrespective of sign, are implicitly converted to (signed) int when used in most expressions. In short, we have the following integer promotion rules − Byte and short values − They are promoted to int. If one operand is a long − The entire expression is promoted to long. If one operand is a float − The entire expression is promoted to float. If any of the operands

C – User Input

C – User Input ”; Previous Next Need for User Input in C Every computer application accepts certain data from the user, performs a predefined process on the same to produce the output. There are no keywords in C that can read user inputs. The standard library that is bundled with the C compiler includes stdio.h header file, whose library function scanf() is most commonly used to accept user input from the standard input stream. In addition, the stdio.h library also provides other functions for accepting input. Example To understand the need for user input, consider the following C program − #include <stdio.h> int main(){ int price, qty, ttl; price = 100; qty = 5; ttl = price*qty; printf(“Total: %d”, ttl); return 0; } Output The above program calculates the total purchase amount by multiplying the price and quantity of an item purchased by a customer. Run the code and check its output − Total: 500 For another transaction with different values of price and quantity, you need to edit the program, put the values, then compile and run again. To do this every time is a tedious activity. Instead, there must be a provision to assign values to a variable after the program is run. The scanf() function reads the user input during the runtime, and assigns the value to a variable. C User Input Function: The scanf() The C language recognizes the standard input stream as stdin and is represented by the standard input device such as a keyboard. C always reads the data from the input stream in the form of characters. The scanf() function converts the input to a desired data type with appropriate format specifiers. Syntax of Scanf() This is how you would use the scanf() function in C − int scanf(const char *format, &var1, &var2, . . .); The first argument to the scanf() function is a format string. It indicates the data type of the variable in which the user input is to be parsed. It is followed by one or more pointers to the variables. The variable names prefixed by & gives the address of the variable. User Input Format Specifiers Following format specifiers are used in the format string − Format Specifier Type %c Character %d Signed integer %f Float values %i Unsigned integer %l or %ld or %li Long %lf Double %Lf Long double %lu Unsigned int or unsigned long %lli or %lld Long long %llu Unsigned long long Example: User Inputs in C Going back to the previous example, we shall use the scanf() function to accept the value for “price” and “qty”, instead of assigning them any fixed value. #include <stdio.h> int main(){ int price, qty, ttl; printf(“Enter price and quantity: “); scanf(“%d %d”, &price, &qty); ttl = price * qty; printf(“Total : %d”, ttl); return 0; } Output When the above program is run, C waits for the user to enter the values − Enter price and quantity: When the values are entered and you press Enter, the program proceeds to the subsequent steps. Enter price and quantity: 100 5 Total : 500 What is more important is that, for another set of values, you don”t need to edit and compile again. Just run the code and the program again waits for the user input. In this way, the program can be run any number of times with different inputs. Enter price and quantity: 150 10 Total : 1500 Integer Input The %d format specifier has been defined for signed integer. The following program reads the user input and stores it in the integer variable num. Example: Integer Input in C Take a look at the following program code − #include <stdio.h> int main(){ int num; printf(“Enter an integer: “); scanf(“%d”, &num); printf(“You entered an integer: %d”, num); return 0; } Output Run the code and check its output − Enter an integer: 234 You entered an integer: 234 If you enter a non-numeric value, the output will be “0”. The scanf() function can read values to one or more variables. While providing the input values, you must separate the consecutive values by a whitespace, a tab or an Enter. Example: Multiple Integer Inputs in C #include <stdio.h> int main(){ int num1, num2; printf(“Enter two integers: “); scanf(“%d %d”, &num1, &num2); printf(“You entered two integers : %d and %d”, num1, num2); return 0; } Output Run the code and check its output − Enter two integers: 45 57 You entered two integers : 45 and 57 or Enter two integers: 45 57 Float Input For floating point input, you need to use the %f format specifier. Example: Float Input in C #include <stdio.h> int main(){ float num1; printf(“Enter a number: “); scanf(“%f”, &num1); printf(“You entered a floating-point number: %f”, num1); return 0; } Output Run the code and check its output − Enter a number: 34.56 You entered a floating-point number: 34.560001 Example: Integer and Float Inputs in C The scanf() function may read inputs for different types of variables. In the following program, user input is stored in an integer and a float variable − #include

C – Cheat Sheet

C Language – Cheat Sheet ”; Previous Next This C language cheat sheet gives a quick overview of C language concepts starting from the basics to the advanced level. This cheat sheet is very useful for students, developers, and those who are preparing for an interview. Go through this cheat sheet to learn all basic and advanced concepts of C programming language. Basis Structure of C Program The basic structure of a C program gives you an idea about the basic statements that you need to use to write a program in C language. The following is the basic structure of a C program − // Preprocessor directive/header file inclusion section #include <stdio.h> // Global declaration section // the main() function int main() { // Variable declarations section int x, y; // other code statements section // Return o return 0; } // Other user-defined function definition section #include <stdio.h> #include is a preprocessor directive that includes the header file in the C program. The stdio.h is a header file where all input and output-related functions are defined. main() Function The main() function is an entry point of a C program, the program”s executions start from the main() function. The below is the syntax of the main() function − int main() { return 0; } Comments There are two types of comments in C language. Single-line and multi-line comments. Comments are ignored by the compilers. Single-line Comments Use // to write a single-line comment. // This is a single-line comment Multi-line Comments Use /* and */ before and after the text to write multi-line comments in C language. /* This is line 1 This is line 2 .. */ Printing (printf() Function) The printf() function is a library function to print the formatted text on the console output. Whenever you want to print anything, use the printf(). Example printf(“Hello world”); User Input (scanf() Function) The scanf() function is used to take various types of inputs from the user. Here is the syntax of the scanf() function − scanf(“format_specifier”, &variable_name); Format Specifiers The following is the list of C format specifiers that are used in printf() and scanf() functions to print/input specific type of values. Format Specifier Type %c Character %d Signed integer %e or %E Scientific notation of floats %f Float values %g or %G Similar as %e or %E %hi Signed integer (short) %hu Unsigned Integer (short) %i Unsigned integer %l or %ld or %li Long %lf Double %Lf Long double %lu Unsigned int or unsigned long %lli or %lld Long long %llu Unsigned long long %o Octal representation %p Pointer %s String %u Unsigned int %x or %X Hexadecimal representation Example #include <stdio.h> int main(){ int age = 18; float percent = 67.75; printf(“Age: %d nPercent: %f”, age, percent); return 0; } Output Age: 18 Percent: 67.750000 Data Types The data types specify the type and size of the data to be stored in a variable. Data types are categorized in 3 sections − Basic Data Types Derived Data Types User-defined Data Types Basic Data Types The basic data types are the built-in data types in C language and they are also used to create derived data types. Data Type Name Description int Integer Represents integer Value char Character Represents a single character float Float Represents float value Derived Data Types The derived data types are derived from the basic data types. The derived data types are − Array Pointer User-defined Data Types The user-defined data types are created by the programmer to handle data of different type and based on the requirements. The user-defined data types are − Structures Unions Enumerations Basic Input & Output For basic input and output in C language, we use printf() and scanf() functions. The printf() function is used to print the formatted text on the console. printf(“Hello world”); The scanf() function is used to take input from the user. scanf(“%d”, &x); // Integer input scanf(“%f”, &y); // float input scanf(“%c”, &z); // Character Input scanf(“%s”, name); // String input Example of Basic Input and Output #include <stdio.h> int main() { int num; printf(“Input any integer number: “); scanf(“%d”, &num); printf(“The input is: %dn”, num); return 0; } Output Input any integer number: The input is: 0 Identifiers C identifiers are user-defined names for variables, constants, functions, etc. The following are the rules for defining identifiers − Keywords can”t be used as identifiers. Only alphabets, underscore symbol (_), and digits are allowed in the identifier. The identifier must start either with an alphabet or an underscore. The same identifier can”t be used as the name of two entities. Identifiers should be meaningful and descriptive. Examples of Valid Identifiers age, _name, person1, roll_no Keywords