ID1063: Introduction to Programming
Tutorial-2
1 Multiple Choice Questions
1.F
2.A
3.B
4.
5.D
2 Coding Questions
1. #include <stdio.h>
#include <stdlib.h>
#define SIZE 100
struct Stack {
int arr[SIZE];
int top;
};
void push(struct Stack *s, int val) {
if (s->top == SIZE - 1) return;
s->arr[++(s->top)] = val;
int pop(struct Stack *s) {
if (s->top == -1) return -1;
return s->arr[(s->top)--];
}
int isEmpty(struct Stack *s) {
return (s->top == -1);
void display(struct Stack *s) {
for (int i = s->top; i >= 0; i--)
printf("%d ", s->arr[i]);
printf("\n");
int main() {
struct Stack s;
[Link] = -1;
push(&s, 10);
push(&s, 20);
display(&s); // 20 10
pop(&s);
display(&s); // 10
return 0;
2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct Expression {
char arr[SIZE];
int top;
};
void push(struct Expression *e, char c) {
e->arr[++(e->top)] = c;
void pop(struct Expression *e) {
if (e->top >= 0) e->top--;
int main() {
struct Expression e;
[Link] = -1;
char seq[SIZE];
printf("Enter a sequence of parentheses: ");
scanf("%s", seq);
int pairs = 0;
for (int i = 0; seq[i]; i++) {
if (seq[i] == '(') push(&e, '(');
else if (seq[i] == ')') {
if ([Link] >= 0) {
pop(&e);
pairs++;
}
if ([Link] == -1) printf("Valid\n");
else printf("Invalid\n");
printf("Number of valid parentheses pairs: %d\n", pairs);
return 0;
3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct Element {
char symbol[3];
int weight;
int total;
};
struct Element table[] = {
{"H",1},{"He",4},{"Li",7},{"Be",9},{"B",11},{"C",12},{"N",14},{"O",16},
{"F",19},{"Ne",20},{"Na",23},{"Mg",24},{"Al",27},{"Si",28},{"P",31},{"S",32},
{"Cl",35},{"Ar",40},{"K",39},{"Ca",40},{"Sc",45},{"Ti",48},{"V",51},{"Cr",52},
{"Mn",55},{"Fe",56},{"Co",59},{"Ni",59},{"Cu",64},{"Zn",65}
};
int findIndex(char *sym) {
for (int i=0; i<30; i++)
if (strcmp(table[i].symbol, sym)==0)
return i;
return -1;
void topKElements(char *compound, int K) {
for (int i=0; i<30; i++) table[i].total=0;
char *p = compound, elem[3];
int mult, idx;
while (*p) {
if (isupper(*p)) {
elem[0] = *p++;
elem[1] = (islower(*p)) ? *p++ : '\0';
elem[2] = '\0';
mult = 0;
while (isdigit(*p)) { mult = mult*10 + (*p - '0'); p++; }
if (mult==0) mult=1;
idx = findIndex(elem);
if (idx!=-1)
table[idx].total += table[idx].weight * mult;
} else p++;
for (int i=0;i<30;i++)
for (int j=i+1;j<30;j++)
if (table[j].total > table[i].total) {
struct Element t=table[i]; table[i]=table[j]; table[j]=t;
for (int i=0;i<K && table[i].total>0;i++)
printf("%s ", table[i].symbol);
printf("\n");
int main() {
char compound[100]; int K;
scanf("%s %d", compound, &K);
topKElements(compound, K);
return 0;