🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

C Programming (3) (1) (1) (2).pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

HilariousChalcedony8823

Uploaded by HilariousChalcedony8823

Tags

c programming algorithms computer science

Full Transcript

1. System Software is the type of software that is the interface between application software and system. Low-level languages are used to write the system software. System Software maintains the system resources and gives the path for application software to run. An important thing is that withou...

1. System Software is the type of software that is the interface between application software and system. Low-level languages are used to write the system software. System Software maintains the system resources and gives the path for application software to run. An important thing is that without system software, the system can not run. It is a general-purpose software. Application Software is the type of software that runs as per user request. It runs on the platform which is provided by system software. High-level languages are used to write the application software. It’s a specific purpose software. The main difference between System Software and Application Software is that without system software, the system can not run on the other hand without application software, the Low-level maintains system always runs. 2. Algorithm to find greatest number of three given numbers Ask the user to enter three integer values. Read the three integer values in num1, num2, and num3 (integer variables). Check if num1 is greater than num2. If true, then check if num1 is greater than num3. If true, then print ‘num1’ as the greatest number. If false, then print ‘num3’ as the greatest number. If false, then check if num2 is greater than num3. If true, then print ‘num2’ as the greatest number. If false, then print ‘num3’ as the greatest number. 3. The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. 4. static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. static variable is used for a common value which is shared by all the methods and its scope is till the lifetime of whole program. In the C programming language, static is used with global variables and functions to set their scope to the containing file. 5. #include void main() { char string; int i, length = 0; printf("Enter a string \n"); gets(string); for (i = 0; string[i] != '\0'; i++) { length++; } printf("The length of a string is the number of characters in it \n"); printf("So, the length of %s = %d\n", string, length); } 6. An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier There are four different ways to initialize one-dimensional array in c programming. 1. Initialize array at the time of declaration One way is to initialize one-dimentional array is to initialize it at the time of declaration. You can use this syntax to declare an array at the time of initialization. int a = {10, 20, 30, 40, 50}; a is initialized with 10, a is initialized with 20 and so on. 2. Initialize all elements of an array with 0 (zero) C program does not assign any default value to declared variables. Same is true for the elements of an array. When we declare an array, all of its elements get initialized with garbage value. If you don’t want to get all elements initialized with garbage, you can initialize them with value 0 (zero). You can do this with the help of this syntax. int a = {0}; With the following syntax, a to a all are initialized with value 0 (zero). Important Point: You can initialize an array with 0 (zero) only. If you want to initialize elements with value 10, this syntax will not work. int a = {10}; //This will not initialize all statements with 10 3. Initialize to define the size of an array Till now, we declare an array with size. Although, it is also possible to define the size of an array by initializing elements of the array. You can use this syntax for this. int a[] = {10, 20, 30, 40, 50}; Remember: if you are not defining size inside [ ] brackets, you must initialize the array (it will define array’s size). If you will not define size of an array inside [ ] brackets, and you are also not initializing the array while declaring. Compiler will show an error “size of array is unknown or zero” and program will not compile. int a[]; //This will cause an error. 4. Initialize array elements individually Array is a group of variables, each variable is called element of the array. You can initialize all elements separately as you initialize any other variable. See following syntax. int a; a = 10; a = 20; a = 30; a = 40; a = 50; This is the most useful approach to initialize one-dimensional array in c programming. Most of the time, array elements are initialized with this method as per the requirement of the program. 7. 8. The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can also return a value to the calling function. A return statement causes your function to exit and hand back a value to its caller. The point of functions, in general, is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller. Example: void main() { int sum = sumDigits(); printf("%d\n", sum); return; } int sumDigits() { int sum = 0; int digit; for(digit = 0; digit ”): Validates greater than the relation between operands. Less than operator: (denoted by “=”): Validates greater than or equals to the relation between the two operands. Less than or equals to (denoted by “ b; Console.WriteLine(validate); validate = a < b; Console.WriteLine(validate); validate = a == b; Console.WriteLine(validate); validate = a >= b; Console.WriteLine(validate); validate = a =0;i--) { printf("%d",a[i]); } return 0; } (b) Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the user. These types of I/O functions can help to display the output to the user in different formats using the format specifiers. These I/O supports all data types like int, float, char, and many more. What is scanf() function in C The function int scanf(const char *format,...); reads formatted data from stdin(standard input device) and stores them in the variables pointed by the additional arguments. Additional arguments must point to variables of the same type as specified in the format. Function prototype of scanf int scanf(const char *format,...); format : This is a null terminated string that contains Whitespace character, Non-whitespace character and Format specifiers. additional arguments : As per the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the data read from stdin to be stored. Return value of scanf On success, scanf function returns the total number of objects successfully read, it may or may not be same as the expected number of items specified in format string. 15. (a) 1)strcat() For the cases when one string has to be appended at the end of another string, this function is being used. Function strcat can append a copy of the source string at the end of the destination string. The strcat() is one of the string operations in c which concatenates two strings, meaning it joins the character strings end-to-end. In the strcat() operation, the destination string’s null character will be overwritten by the source string’s first character, and the previous null character would now be added at the end of the new destination string which is a result of stcrat() operation. The user has to pass two arguments that are described below: i) src ii) dest Here at the place of “src” string is specified, while at the place of ‘dest’ the destination string in which we have to append the source string is specified. Example #include int main() { char src= “ before”; char dest= “after ”; strcat(dest, src); puts(dest); return 0; } The output will be: after before 2) Function strlen() One more function of string header file that can be directly used for the strings is strlen(). You can use the function strlen(), the string function in C, when you have to find out the length of any string. The strlen() string functions in c basically calculate the length of a given string. However, one can also write a program manually to find out the length of any string, but the use of this direct function can save your time and the example is given below: #include int main() { int length; char s = “We are Here”; length=strlen(s); printf(“\Length of the string is = %d \n”, length); return 0; } Length of the string is = 11 3) Function strcpy() If you have to copy the content of one string to another string, then this function is being used. Even the null characters are copied in the process. Syntax of the function is strcpy(dest,source). The function can copy the content of one string to another. One example of the function is given below: #include int main() { char src= “ Destination”; char dest= “”; printf(“\n source string is = %s”, src); printf(“\n destination string is = %s”, dest); strcpy(dest, src); printf (“\ntarget string after strcpy() = %s”, dest); return 0; } 4.Function strcmp() To compare two strings to know whether they are same or not we can use strcmp() function.This string functions in c, compares two strings. While comparing the strings takes two parameters into account namely – str1 str2 On comparing the return value be determined basis the strings setup as shown below. The function returns a definite value that may be either 0, >0, or first) { second = first; first = arr[i]; } else if(arr[i] > second && arr[i] < first) { second = arr[i]; } } printf("\n The Largest Number in this Array = %d", first); printf("\n The Second Largest Number in this Array = %d", second); return 0; } (b) #include int main() { char string; int length=0, flag=1,i; printf("Enter string:\n"); gets(string); for(i=0;string[i]!='\0';i++) { length++; } for(i=0;i< length/2;i++) { if( string[i] != string[length-1-i] ) { flag=0; break; } } if(flag==1) { printf("PALINDROME"); } else { printf("NOT PALINDROME"); } return 0; } 17. (a) There are total four types of standard storage classes. auto -It is a default storage class. extern -It is a global variable. static It is a local variable which is capable of returning a value even when control is transferred to the function call. register -It is a variable which is stored inside a Register. Auto Storage Class in C The variables defined using auto storage class are called as local variables. Auto stands for automatic storage class. A variable is in auto storage class by default if it is not explicitly specified. The scope of an auto variable is limited with the particular block only. Once the control goes out of the block, the access is destroyed. This means only the block in which the auto variable is declared can access it. A keyword auto is used to define an auto storage class. By default, an auto variable contains a garbage value. Extern Storage Class in C Extern stands for external storage class. Extern storage class is used when we have global functions or variables which are shared between two or more files. Keyword extern is used to declaring a global variable or function in another file to provide the reference of variable or function which have been already defined in the original file. The variables defined using an extern keyword are called as global variables. These variables are accessible throughout the program. Notice that the extern variable cannot be initialized it has already been defined in the original file. Static Storage Class in C The static variables are used within function/ file as local static variables. They can also be used as a global variable Static local variable is a local variable that retains and stores its value between function calls or block and remains visible only to the function or block in which it is defined. Static global variables are global variables visible only to the file in which it is declared. Example: static int count = 10; Keep in mind that static variable has a default initial value zero and is initialized only once in its lifetime. Register Storage Class in C You can use the register storage class when you want to store local variables within functions or blocks in CPU registers instead of RAM to have quick access to these variables. For example, “counters” are a good candidate to be stored in the register. Example: register int age; The keyword register is used to declare a register storage class. The variables declared using register storage class has lifespan throughout the program. It is similar to the auto storage class. The variable is limited to the particular block. The only difference is that the variables declared using register storage class are stored inside CPU registers instead of a memory. Register has faster access than that of the main memory. The variables declared using register storage class has no default value. These variables are often declared at the beginning of a program. (b) #include struct student { char firstName; int roll; float marks; } s; int main() { int i; printf("Enter information of students:\n"); // storing information for (i = 0; i < 5; ++i) { s[i].roll = i + 1; printf("\nFor roll number%d,\n", s[i].roll); printf("Enter first name: "); scanf("%s", s[i].firstName); printf("Enter marks: "); scanf("%f", &s[i].marks); } printf("Displaying Information:\n\n"); // displaying information for (i = 0; i < 5; ++i) { printf("\nRoll number: %d\n", i + 1); printf("First name: "); puts(s[i].firstName); printf("Marks: %.1f", s[i].marks); printf("\n"); } return 0; } 18. (a) Recursion is a process by which a function calls itself directly or indirectly. The corresponding function is called as recursive function. Using recursive algorithms, certain complex problems can be solved quite easily. #include int Fibonacci(int); int main() { int n, i = 0, c; scanf("%d",&n); printf("Fibonacci series\n"); for ( c = 1 ; c number[k]) { temp = number[j]; number[j] = number[k]; number[k] = temp; } } } printf("Numbers in ascending order:\n"); for (i = 0; i < count; ++i) printf("%d\n", number[i]); } void main() { int i, count, number; printf("How many numbers you are gonna enter:"); scanf("%d", &count); printf("\nEnter the numbers one by one:"); for (i = 0; i < count; ++i) scanf("%d", &number[i]); sort_numbers_ascending(number, count); } 19. (a) In C, you can make use of some functions which are used for file handling purposes. Below is the list of functions:- fopen()-Used for opening a new or existing file. fprintf()-Used to write data into a file. fscanf() -Used to read data from a file. fputc()- Used to write a character into a file. fgetc()- Used for reading a character from a file. fclose()- Closes a file. fseek() -Used to set the file pointer to a given position. fputw()-Used to write an integer to a file. fgetw()-Used for reading an integer from a file. ftell()- Used to return a current position. rewind()- Used to set the file pointer at the beginning of a file. (b) #include #include void main() { char *s; int len,i; clrscr(); printf("\nENTER A STRING: "); gets(s); len=strlen(s); printf("\nTHE REVERSE OF THE STRING IS:"); for(i=len;i>=0;i--) printf("%c",*(s+i)); getch(); } 20. (a) Key Differences Between Array and Pointer 1.An array stores the variables of similar data types and the data types of the variables must match the type of array. 2.Conversely, the pointer variable stores the address of a variable, of a type similar to a type of pointer variable type. 3.We can generate an array of pointers i.e. array whose variables are the pointer variables. 4.On the other hand, we can create a pointer that points to an array. 5. An array size decides the number of variables it can store. 6.As against, a pointer variable can store the address of the only variable. (b) #include int main() { FILE *fptr; int lcount = 0; char fname, chr; clrscr(); printf("Enter file name:"); scanf("%s", fname); fptr = fopen(fname, "r"); chr = getc(fptr); while (chr != EOF) { if (chr == 'n') { lcount = lcount + 1; } chr = getc(fptr); } fclose(fptr); //close file. printf("There are %d lines in %s in a file\n", lcount, fname); getch(); return 0; }

Use Quizgecko on...
Browser
Browser